1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the Sema class, which performs semantic analysis and
10 // builds ASTs.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_SEMA_SEMA_H
15 #define LLVM_CLANG_SEMA_SEMA_H
16 
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Availability.h"
20 #include "clang/AST/ComparisonCategories.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/DeclarationName.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprConcepts.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/LocInfoType.h"
29 #include "clang/AST/MangleNumberingContext.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/PrettyPrinter.h"
32 #include "clang/AST/StmtCXX.h"
33 #include "clang/AST/TypeLoc.h"
34 #include "clang/AST/TypeOrdering.h"
35 #include "clang/Basic/BitmaskEnum.h"
36 #include "clang/Basic/ExpressionTraits.h"
37 #include "clang/Basic/Module.h"
38 #include "clang/Basic/OpenMPKinds.h"
39 #include "clang/Basic/PragmaKinds.h"
40 #include "clang/Basic/Specifiers.h"
41 #include "clang/Basic/TemplateKinds.h"
42 #include "clang/Basic/TypeTraits.h"
43 #include "clang/Sema/AnalysisBasedWarnings.h"
44 #include "clang/Sema/CleanupInfo.h"
45 #include "clang/Sema/DeclSpec.h"
46 #include "clang/Sema/ExternalSemaSource.h"
47 #include "clang/Sema/IdentifierResolver.h"
48 #include "clang/Sema/ObjCMethodList.h"
49 #include "clang/Sema/Ownership.h"
50 #include "clang/Sema/Scope.h"
51 #include "clang/Sema/SemaConcept.h"
52 #include "clang/Sema/TypoCorrection.h"
53 #include "clang/Sema/Weak.h"
54 #include "llvm/ADT/ArrayRef.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SetVector.h"
57 #include "llvm/ADT/SmallBitVector.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/SmallVector.h"
60 #include "llvm/ADT/TinyPtrVector.h"
61 #include "llvm/Frontend/OpenMP/OMPConstants.h"
62 #include <deque>
63 #include <memory>
64 #include <string>
65 #include <tuple>
66 #include <vector>
67 
68 namespace llvm {
69   class APSInt;
70   template <typename ValueT> struct DenseMapInfo;
71   template <typename ValueT, typename ValueInfoT> class DenseSet;
72   class SmallBitVector;
73   struct InlineAsmIdentifierInfo;
74 }
75 
76 namespace clang {
77   class ADLResult;
78   class ASTConsumer;
79   class ASTContext;
80   class ASTMutationListener;
81   class ASTReader;
82   class ASTWriter;
83   class ArrayType;
84   class ParsedAttr;
85   class BindingDecl;
86   class BlockDecl;
87   class CapturedDecl;
88   class CXXBasePath;
89   class CXXBasePaths;
90   class CXXBindTemporaryExpr;
91   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
92   class CXXConstructorDecl;
93   class CXXConversionDecl;
94   class CXXDeleteExpr;
95   class CXXDestructorDecl;
96   class CXXFieldCollector;
97   class CXXMemberCallExpr;
98   class CXXMethodDecl;
99   class CXXScopeSpec;
100   class CXXTemporary;
101   class CXXTryStmt;
102   class CallExpr;
103   class ClassTemplateDecl;
104   class ClassTemplatePartialSpecializationDecl;
105   class ClassTemplateSpecializationDecl;
106   class VarTemplatePartialSpecializationDecl;
107   class CodeCompleteConsumer;
108   class CodeCompletionAllocator;
109   class CodeCompletionTUInfo;
110   class CodeCompletionResult;
111   class CoroutineBodyStmt;
112   class Decl;
113   class DeclAccessPair;
114   class DeclContext;
115   class DeclRefExpr;
116   class DeclaratorDecl;
117   class DeducedTemplateArgument;
118   class DependentDiagnostic;
119   class DesignatedInitExpr;
120   class Designation;
121   class EnableIfAttr;
122   class EnumConstantDecl;
123   class Expr;
124   class ExtVectorType;
125   class FormatAttr;
126   class FriendDecl;
127   class FunctionDecl;
128   class FunctionProtoType;
129   class FunctionTemplateDecl;
130   class ImplicitConversionSequence;
131   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
132   class InitListExpr;
133   class InitializationKind;
134   class InitializationSequence;
135   class InitializedEntity;
136   class IntegerLiteral;
137   class LabelStmt;
138   class LambdaExpr;
139   class LangOptions;
140   class LocalInstantiationScope;
141   class LookupResult;
142   class MacroInfo;
143   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
144   class ModuleLoader;
145   class MultiLevelTemplateArgumentList;
146   class NamedDecl;
147   class ObjCCategoryDecl;
148   class ObjCCategoryImplDecl;
149   class ObjCCompatibleAliasDecl;
150   class ObjCContainerDecl;
151   class ObjCImplDecl;
152   class ObjCImplementationDecl;
153   class ObjCInterfaceDecl;
154   class ObjCIvarDecl;
155   template <class T> class ObjCList;
156   class ObjCMessageExpr;
157   class ObjCMethodDecl;
158   class ObjCPropertyDecl;
159   class ObjCProtocolDecl;
160   class OMPThreadPrivateDecl;
161   class OMPRequiresDecl;
162   class OMPDeclareReductionDecl;
163   class OMPDeclareSimdDecl;
164   class OMPClause;
165   struct OMPVarListLocTy;
166   struct OverloadCandidate;
167   enum class OverloadCandidateParamOrder : char;
168   enum OverloadCandidateRewriteKind : unsigned;
169   class OverloadCandidateSet;
170   class OverloadExpr;
171   class ParenListExpr;
172   class ParmVarDecl;
173   class Preprocessor;
174   class PseudoDestructorTypeStorage;
175   class PseudoObjectExpr;
176   class QualType;
177   class StandardConversionSequence;
178   class Stmt;
179   class StringLiteral;
180   class SwitchStmt;
181   class TemplateArgument;
182   class TemplateArgumentList;
183   class TemplateArgumentLoc;
184   class TemplateDecl;
185   class TemplateInstantiationCallback;
186   class TemplateParameterList;
187   class TemplatePartialOrderingContext;
188   class TemplateTemplateParmDecl;
189   class Token;
190   class TypeAliasDecl;
191   class TypedefDecl;
192   class TypedefNameDecl;
193   class TypeLoc;
194   class TypoCorrectionConsumer;
195   class UnqualifiedId;
196   class UnresolvedLookupExpr;
197   class UnresolvedMemberExpr;
198   class UnresolvedSetImpl;
199   class UnresolvedSetIterator;
200   class UsingDecl;
201   class UsingShadowDecl;
202   class ValueDecl;
203   class VarDecl;
204   class VarTemplateSpecializationDecl;
205   class VisibilityAttr;
206   class VisibleDeclConsumer;
207   class IndirectFieldDecl;
208   struct DeductionFailureInfo;
209   class TemplateSpecCandidateSet;
210 
211 namespace sema {
212   class AccessedEntity;
213   class BlockScopeInfo;
214   class Capture;
215   class CapturedRegionScopeInfo;
216   class CapturingScopeInfo;
217   class CompoundScopeInfo;
218   class DelayedDiagnostic;
219   class DelayedDiagnosticPool;
220   class FunctionScopeInfo;
221   class LambdaScopeInfo;
222   class PossiblyUnreachableDiag;
223   class SemaPPCallbacks;
224   class TemplateDeductionInfo;
225 }
226 
227 namespace threadSafety {
228   class BeforeSet;
229   void threadSafetyCleanup(BeforeSet* Cache);
230 }
231 
232 // FIXME: No way to easily map from TemplateTypeParmTypes to
233 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
234 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
235                   SourceLocation> UnexpandedParameterPack;
236 
237 /// Describes whether we've seen any nullability information for the given
238 /// file.
239 struct FileNullability {
240   /// The first pointer declarator (of any pointer kind) in the file that does
241   /// not have a corresponding nullability annotation.
242   SourceLocation PointerLoc;
243 
244   /// The end location for the first pointer declarator in the file. Used for
245   /// placing fix-its.
246   SourceLocation PointerEndLoc;
247 
248   /// Which kind of pointer declarator we saw.
249   uint8_t PointerKind;
250 
251   /// Whether we saw any type nullability annotations in the given file.
252   bool SawTypeNullability = false;
253 };
254 
255 /// A mapping from file IDs to a record of whether we've seen nullability
256 /// information in that file.
257 class FileNullabilityMap {
258   /// A mapping from file IDs to the nullability information for each file ID.
259   llvm::DenseMap<FileID, FileNullability> Map;
260 
261   /// A single-element cache based on the file ID.
262   struct {
263     FileID File;
264     FileNullability Nullability;
265   } Cache;
266 
267 public:
268   FileNullability &operator[](FileID file) {
269     // Check the single-element cache.
270     if (file == Cache.File)
271       return Cache.Nullability;
272 
273     // It's not in the single-element cache; flush the cache if we have one.
274     if (!Cache.File.isInvalid()) {
275       Map[Cache.File] = Cache.Nullability;
276     }
277 
278     // Pull this entry into the cache.
279     Cache.File = file;
280     Cache.Nullability = Map[file];
281     return Cache.Nullability;
282   }
283 };
284 
285 /// Keeps track of expected type during expression parsing. The type is tied to
286 /// a particular token, all functions that update or consume the type take a
287 /// start location of the token they are looking at as a parameter. This allows
288 /// to avoid updating the type on hot paths in the parser.
289 class PreferredTypeBuilder {
290 public:
291   PreferredTypeBuilder() = default;
292   explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
293 
294   void enterCondition(Sema &S, SourceLocation Tok);
295   void enterReturn(Sema &S, SourceLocation Tok);
296   void enterVariableInit(SourceLocation Tok, Decl *D);
297   /// Computing a type for the function argument may require running
298   /// overloading, so we postpone its computation until it is actually needed.
299   ///
300   /// Clients should be very careful when using this funciton, as it stores a
301   /// function_ref, clients should make sure all calls to get() with the same
302   /// location happen while function_ref is alive.
303   void enterFunctionArgument(SourceLocation Tok,
304                              llvm::function_ref<QualType()> ComputeType);
305 
306   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
307   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
308                   SourceLocation OpLoc);
309   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
310   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
311   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
312   /// Handles all type casts, including C-style cast, C++ casts, etc.
313   void enterTypeCast(SourceLocation Tok, QualType CastType);
314 
315   QualType get(SourceLocation Tok) const {
316     if (Tok != ExpectedLoc)
317       return QualType();
318     if (!Type.isNull())
319       return Type;
320     if (ComputeType)
321       return ComputeType();
322     return QualType();
323   }
324 
325 private:
326   /// Start position of a token for which we store expected type.
327   SourceLocation ExpectedLoc;
328   /// Expected type for a token starting at ExpectedLoc.
329   QualType Type;
330   /// A function to compute expected type at ExpectedLoc. It is only considered
331   /// if Type is null.
332   llvm::function_ref<QualType()> ComputeType;
333 };
334 
335 /// Sema - This implements semantic analysis and AST building for C.
336 class Sema final {
337   Sema(const Sema &) = delete;
338   void operator=(const Sema &) = delete;
339 
340   /// A key method to reduce duplicate debug info from Sema.
341   virtual void anchor();
342 
343   ///Source of additional semantic information.
344   ExternalSemaSource *ExternalSource;
345 
346   ///Whether Sema has generated a multiplexer and has to delete it.
347   bool isMultiplexExternalSource;
348 
349   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
350 
351   bool isVisibleSlow(const NamedDecl *D);
352 
353   /// Determine whether two declarations should be linked together, given that
354   /// the old declaration might not be visible and the new declaration might
355   /// not have external linkage.
356   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
357                                     const NamedDecl *New) {
358     if (isVisible(Old))
359      return true;
360     // See comment in below overload for why it's safe to compute the linkage
361     // of the new declaration here.
362     if (New->isExternallyDeclarable()) {
363       assert(Old->isExternallyDeclarable() &&
364              "should not have found a non-externally-declarable previous decl");
365       return true;
366     }
367     return false;
368   }
369   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
370 
371   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
372                                       QualType ResultTy,
373                                       ArrayRef<QualType> Args);
374 
375 public:
376   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
377   typedef OpaquePtr<TemplateName> TemplateTy;
378   typedef OpaquePtr<QualType> TypeTy;
379 
380   OpenCLOptions OpenCLFeatures;
381   FPOptions FPFeatures;
382 
383   const LangOptions &LangOpts;
384   Preprocessor &PP;
385   ASTContext &Context;
386   ASTConsumer &Consumer;
387   DiagnosticsEngine &Diags;
388   SourceManager &SourceMgr;
389 
390   /// Flag indicating whether or not to collect detailed statistics.
391   bool CollectStats;
392 
393   /// Code-completion consumer.
394   CodeCompleteConsumer *CodeCompleter;
395 
396   /// CurContext - This is the current declaration context of parsing.
397   DeclContext *CurContext;
398 
399   /// Generally null except when we temporarily switch decl contexts,
400   /// like in \see ActOnObjCTemporaryExitContainerContext.
401   DeclContext *OriginalLexicalContext;
402 
403   /// VAListTagName - The declaration name corresponding to __va_list_tag.
404   /// This is used as part of a hack to omit that class from ADL results.
405   DeclarationName VAListTagName;
406 
407   bool MSStructPragmaOn; // True when \#pragma ms_struct on
408 
409   /// Controls member pointer representation format under the MS ABI.
410   LangOptions::PragmaMSPointersToMembersKind
411       MSPointerToMemberRepresentationMethod;
412 
413   /// Stack of active SEH __finally scopes.  Can be empty.
414   SmallVector<Scope*, 2> CurrentSEHFinally;
415 
416   /// Source location for newly created implicit MSInheritanceAttrs
417   SourceLocation ImplicitMSInheritanceAttrLoc;
418 
419   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
420   /// `TransformTypos` in order to keep track of any TypoExprs that are created
421   /// recursively during typo correction and wipe them away if the correction
422   /// fails.
423   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
424 
425   /// pragma clang section kind
426   enum PragmaClangSectionKind {
427     PCSK_Invalid      = 0,
428     PCSK_BSS          = 1,
429     PCSK_Data         = 2,
430     PCSK_Rodata       = 3,
431     PCSK_Text         = 4,
432     PCSK_Relro        = 5
433    };
434 
435   enum PragmaClangSectionAction {
436     PCSA_Set     = 0,
437     PCSA_Clear   = 1
438   };
439 
440   struct PragmaClangSection {
441     std::string SectionName;
442     bool Valid = false;
443     SourceLocation PragmaLocation;
444 
445     void Act(SourceLocation PragmaLocation,
446              PragmaClangSectionAction Action,
447              StringLiteral* Name);
448    };
449 
450    PragmaClangSection PragmaClangBSSSection;
451    PragmaClangSection PragmaClangDataSection;
452    PragmaClangSection PragmaClangRodataSection;
453    PragmaClangSection PragmaClangRelroSection;
454    PragmaClangSection PragmaClangTextSection;
455 
456   enum PragmaMsStackAction {
457     PSK_Reset     = 0x0,                // #pragma ()
458     PSK_Set       = 0x1,                // #pragma (value)
459     PSK_Push      = 0x2,                // #pragma (push[, id])
460     PSK_Pop       = 0x4,                // #pragma (pop[, id])
461     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
462     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
463     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
464   };
465 
466   template<typename ValueType>
467   struct PragmaStack {
468     struct Slot {
469       llvm::StringRef StackSlotLabel;
470       ValueType Value;
471       SourceLocation PragmaLocation;
472       SourceLocation PragmaPushLocation;
473       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
474            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
475           : StackSlotLabel(StackSlotLabel), Value(Value),
476             PragmaLocation(PragmaLocation),
477             PragmaPushLocation(PragmaPushLocation) {}
478     };
479     void Act(SourceLocation PragmaLocation,
480              PragmaMsStackAction Action,
481              llvm::StringRef StackSlotLabel,
482              ValueType Value);
483 
484     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
485     // method body to restore the stacks on exit, so it works like this:
486     //
487     //   struct S {
488     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
489     //     void Method {}
490     //     #pragma <name>(pop, InternalPragmaSlot)
491     //   };
492     //
493     // It works even with #pragma vtordisp, although MSVC doesn't support
494     //   #pragma vtordisp(push [, id], n)
495     // syntax.
496     //
497     // Push / pop a named sentinel slot.
498     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
499       assert((Action == PSK_Push || Action == PSK_Pop) &&
500              "Can only push / pop #pragma stack sentinels!");
501       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
502     }
503 
504     // Constructors.
505     explicit PragmaStack(const ValueType &Default)
506         : DefaultValue(Default), CurrentValue(Default) {}
507 
508     bool hasValue() const { return CurrentValue != DefaultValue; }
509 
510     SmallVector<Slot, 2> Stack;
511     ValueType DefaultValue; // Value used for PSK_Reset action.
512     ValueType CurrentValue;
513     SourceLocation CurrentPragmaLocation;
514   };
515   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
516   // we shouldn't do so if they're in a module).
517 
518   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
519   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
520   ///
521   /// 0: Suppress all vtordisps
522   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
523   ///    structors
524   /// 2: Always insert vtordisps to support RTTI on partially constructed
525   ///    objects
526   PragmaStack<MSVtorDispMode> VtorDispStack;
527   // #pragma pack.
528   // Sentinel to represent when the stack is set to mac68k alignment.
529   static const unsigned kMac68kAlignmentSentinel = ~0U;
530   PragmaStack<unsigned> PackStack;
531   // The current #pragma pack values and locations at each #include.
532   struct PackIncludeState {
533     unsigned CurrentValue;
534     SourceLocation CurrentPragmaLocation;
535     bool HasNonDefaultValue, ShouldWarnOnInclude;
536   };
537   SmallVector<PackIncludeState, 8> PackIncludeStack;
538   // Segment #pragmas.
539   PragmaStack<StringLiteral *> DataSegStack;
540   PragmaStack<StringLiteral *> BSSSegStack;
541   PragmaStack<StringLiteral *> ConstSegStack;
542   PragmaStack<StringLiteral *> CodeSegStack;
543 
544   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
545   // Actions should be performed only if we enter / exit a C++ method body.
546   class PragmaStackSentinelRAII {
547   public:
548     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
549     ~PragmaStackSentinelRAII();
550 
551   private:
552     Sema &S;
553     StringRef SlotLabel;
554     bool ShouldAct;
555   };
556 
557   /// A mapping that describes the nullability we've seen in each header file.
558   FileNullabilityMap NullabilityMap;
559 
560   /// Last section used with #pragma init_seg.
561   StringLiteral *CurInitSeg;
562   SourceLocation CurInitSegLoc;
563 
564   /// VisContext - Manages the stack for \#pragma GCC visibility.
565   void *VisContext; // Really a "PragmaVisStack*"
566 
567   /// This an attribute introduced by \#pragma clang attribute.
568   struct PragmaAttributeEntry {
569     SourceLocation Loc;
570     ParsedAttr *Attribute;
571     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
572     bool IsUsed;
573   };
574 
575   /// A push'd group of PragmaAttributeEntries.
576   struct PragmaAttributeGroup {
577     /// The location of the push attribute.
578     SourceLocation Loc;
579     /// The namespace of this push group.
580     const IdentifierInfo *Namespace;
581     SmallVector<PragmaAttributeEntry, 2> Entries;
582   };
583 
584   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
585 
586   /// The declaration that is currently receiving an attribute from the
587   /// #pragma attribute stack.
588   const Decl *PragmaAttributeCurrentTargetDecl;
589 
590   /// This represents the last location of a "#pragma clang optimize off"
591   /// directive if such a directive has not been closed by an "on" yet. If
592   /// optimizations are currently "on", this is set to an invalid location.
593   SourceLocation OptimizeOffPragmaLocation;
594 
595   /// Flag indicating if Sema is building a recovery call expression.
596   ///
597   /// This flag is used to avoid building recovery call expressions
598   /// if Sema is already doing so, which would cause infinite recursions.
599   bool IsBuildingRecoveryCallExpr;
600 
601   /// Used to control the generation of ExprWithCleanups.
602   CleanupInfo Cleanup;
603 
604   /// ExprCleanupObjects - This is the stack of objects requiring
605   /// cleanup that are created by the current full expression.  The
606   /// element type here is ExprWithCleanups::Object.
607   SmallVector<BlockDecl*, 8> ExprCleanupObjects;
608 
609   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
610   /// to a variable (constant) that may or may not be odr-used in this Expr, and
611   /// we won't know until all lvalue-to-rvalue and discarded value conversions
612   /// have been applied to all subexpressions of the enclosing full expression.
613   /// This is cleared at the end of each full expression.
614   using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
615   MaybeODRUseExprSet MaybeODRUseExprs;
616 
617   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
618 
619   /// Stack containing information about each of the nested
620   /// function, block, and method scopes that are currently active.
621   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
622 
623   /// The index of the first FunctionScope that corresponds to the current
624   /// context.
625   unsigned FunctionScopesStart = 0;
626 
627   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
628     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
629                               FunctionScopes.end());
630   }
631 
632   /// Stack containing information needed when in C++2a an 'auto' is encountered
633   /// in a function declaration parameter type specifier in order to invent a
634   /// corresponding template parameter in the enclosing abbreviated function
635   /// template. This information is also present in LambdaScopeInfo, stored in
636   /// the FunctionScopes stack.
637   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
638 
639   /// The index of the first InventedParameterInfo that refers to the current
640   /// context.
641   unsigned InventedParameterInfosStart = 0;
642 
643   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
644     return llvm::makeArrayRef(InventedParameterInfos.begin() +
645                                   InventedParameterInfosStart,
646                               InventedParameterInfos.end());
647   }
648 
649   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
650                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
651     ExtVectorDeclsType;
652 
653   /// ExtVectorDecls - This is a list all the extended vector types. This allows
654   /// us to associate a raw vector type with one of the ext_vector type names.
655   /// This is only necessary for issuing pretty diagnostics.
656   ExtVectorDeclsType ExtVectorDecls;
657 
658   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
659   std::unique_ptr<CXXFieldCollector> FieldCollector;
660 
661   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
662 
663   /// Set containing all declared private fields that are not used.
664   NamedDeclSetType UnusedPrivateFields;
665 
666   /// Set containing all typedefs that are likely unused.
667   llvm::SmallSetVector<const TypedefNameDecl *, 4>
668       UnusedLocalTypedefNameCandidates;
669 
670   /// Delete-expressions to be analyzed at the end of translation unit
671   ///
672   /// This list contains class members, and locations of delete-expressions
673   /// that could not be proven as to whether they mismatch with new-expression
674   /// used in initializer of the field.
675   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
676   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
677   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
678 
679   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
680 
681   /// PureVirtualClassDiagSet - a set of class declarations which we have
682   /// emitted a list of pure virtual functions. Used to prevent emitting the
683   /// same list more than once.
684   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
685 
686   /// ParsingInitForAutoVars - a set of declarations with auto types for which
687   /// we are currently parsing the initializer.
688   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
689 
690   /// Look for a locally scoped extern "C" declaration by the given name.
691   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
692 
693   typedef LazyVector<VarDecl *, ExternalSemaSource,
694                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
695     TentativeDefinitionsType;
696 
697   /// All the tentative definitions encountered in the TU.
698   TentativeDefinitionsType TentativeDefinitions;
699 
700   /// All the external declarations encoutered and used in the TU.
701   SmallVector<VarDecl *, 4> ExternalDeclarations;
702 
703   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
704                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
705     UnusedFileScopedDeclsType;
706 
707   /// The set of file scoped decls seen so far that have not been used
708   /// and must warn if not used. Only contains the first declaration.
709   UnusedFileScopedDeclsType UnusedFileScopedDecls;
710 
711   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
712                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
713     DelegatingCtorDeclsType;
714 
715   /// All the delegating constructors seen so far in the file, used for
716   /// cycle detection at the end of the TU.
717   DelegatingCtorDeclsType DelegatingCtorDecls;
718 
719   /// All the overriding functions seen during a class definition
720   /// that had their exception spec checks delayed, plus the overridden
721   /// function.
722   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
723     DelayedOverridingExceptionSpecChecks;
724 
725   /// All the function redeclarations seen during a class definition that had
726   /// their exception spec checks delayed, plus the prior declaration they
727   /// should be checked against. Except during error recovery, the new decl
728   /// should always be a friend declaration, as that's the only valid way to
729   /// redeclare a special member before its class is complete.
730   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
731     DelayedEquivalentExceptionSpecChecks;
732 
733   typedef llvm::MapVector<const FunctionDecl *,
734                           std::unique_ptr<LateParsedTemplate>>
735       LateParsedTemplateMapT;
736   LateParsedTemplateMapT LateParsedTemplateMap;
737 
738   /// Callback to the parser to parse templated functions when needed.
739   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
740   typedef void LateTemplateParserCleanupCB(void *P);
741   LateTemplateParserCB *LateTemplateParser;
742   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
743   void *OpaqueParser;
744 
745   void SetLateTemplateParser(LateTemplateParserCB *LTP,
746                              LateTemplateParserCleanupCB *LTPCleanup,
747                              void *P) {
748     LateTemplateParser = LTP;
749     LateTemplateParserCleanup = LTPCleanup;
750     OpaqueParser = P;
751   }
752 
753   class DelayedDiagnostics;
754 
755   class DelayedDiagnosticsState {
756     sema::DelayedDiagnosticPool *SavedPool;
757     friend class Sema::DelayedDiagnostics;
758   };
759   typedef DelayedDiagnosticsState ParsingDeclState;
760   typedef DelayedDiagnosticsState ProcessingContextState;
761 
762   /// A class which encapsulates the logic for delaying diagnostics
763   /// during parsing and other processing.
764   class DelayedDiagnostics {
765     /// The current pool of diagnostics into which delayed
766     /// diagnostics should go.
767     sema::DelayedDiagnosticPool *CurPool;
768 
769   public:
770     DelayedDiagnostics() : CurPool(nullptr) {}
771 
772     /// Adds a delayed diagnostic.
773     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
774 
775     /// Determines whether diagnostics should be delayed.
776     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
777 
778     /// Returns the current delayed-diagnostics pool.
779     sema::DelayedDiagnosticPool *getCurrentPool() const {
780       return CurPool;
781     }
782 
783     /// Enter a new scope.  Access and deprecation diagnostics will be
784     /// collected in this pool.
785     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
786       DelayedDiagnosticsState state;
787       state.SavedPool = CurPool;
788       CurPool = &pool;
789       return state;
790     }
791 
792     /// Leave a delayed-diagnostic state that was previously pushed.
793     /// Do not emit any of the diagnostics.  This is performed as part
794     /// of the bookkeeping of popping a pool "properly".
795     void popWithoutEmitting(DelayedDiagnosticsState state) {
796       CurPool = state.SavedPool;
797     }
798 
799     /// Enter a new scope where access and deprecation diagnostics are
800     /// not delayed.
801     DelayedDiagnosticsState pushUndelayed() {
802       DelayedDiagnosticsState state;
803       state.SavedPool = CurPool;
804       CurPool = nullptr;
805       return state;
806     }
807 
808     /// Undo a previous pushUndelayed().
809     void popUndelayed(DelayedDiagnosticsState state) {
810       assert(CurPool == nullptr);
811       CurPool = state.SavedPool;
812     }
813   } DelayedDiagnostics;
814 
815   /// A RAII object to temporarily push a declaration context.
816   class ContextRAII {
817   private:
818     Sema &S;
819     DeclContext *SavedContext;
820     ProcessingContextState SavedContextState;
821     QualType SavedCXXThisTypeOverride;
822     unsigned SavedFunctionScopesStart;
823     unsigned SavedInventedParameterInfosStart;
824 
825   public:
826     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
827       : S(S), SavedContext(S.CurContext),
828         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
829         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
830         SavedFunctionScopesStart(S.FunctionScopesStart),
831         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
832     {
833       assert(ContextToPush && "pushing null context");
834       S.CurContext = ContextToPush;
835       if (NewThisContext)
836         S.CXXThisTypeOverride = QualType();
837       // Any saved FunctionScopes do not refer to this context.
838       S.FunctionScopesStart = S.FunctionScopes.size();
839       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
840     }
841 
842     void pop() {
843       if (!SavedContext) return;
844       S.CurContext = SavedContext;
845       S.DelayedDiagnostics.popUndelayed(SavedContextState);
846       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
847       S.FunctionScopesStart = SavedFunctionScopesStart;
848       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
849       SavedContext = nullptr;
850     }
851 
852     ~ContextRAII() {
853       pop();
854     }
855   };
856 
857   /// Used to change context to isConstantEvaluated without pushing a heavy
858   /// ExpressionEvaluationContextRecord object.
859   bool isConstantEvaluatedOverride;
860 
861   bool isConstantEvaluated() {
862     return ExprEvalContexts.back().isConstantEvaluated() ||
863            isConstantEvaluatedOverride;
864   }
865 
866   /// RAII object to handle the state changes required to synthesize
867   /// a function body.
868   class SynthesizedFunctionScope {
869     Sema &S;
870     Sema::ContextRAII SavedContext;
871     bool PushedCodeSynthesisContext = false;
872 
873   public:
874     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
875         : S(S), SavedContext(S, DC) {
876       S.PushFunctionScope();
877       S.PushExpressionEvaluationContext(
878           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
879       if (auto *FD = dyn_cast<FunctionDecl>(DC))
880         FD->setWillHaveBody(true);
881       else
882         assert(isa<ObjCMethodDecl>(DC));
883     }
884 
885     void addContextNote(SourceLocation UseLoc) {
886       assert(!PushedCodeSynthesisContext);
887 
888       Sema::CodeSynthesisContext Ctx;
889       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
890       Ctx.PointOfInstantiation = UseLoc;
891       Ctx.Entity = cast<Decl>(S.CurContext);
892       S.pushCodeSynthesisContext(Ctx);
893 
894       PushedCodeSynthesisContext = true;
895     }
896 
897     ~SynthesizedFunctionScope() {
898       if (PushedCodeSynthesisContext)
899         S.popCodeSynthesisContext();
900       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
901         FD->setWillHaveBody(false);
902       S.PopExpressionEvaluationContext();
903       S.PopFunctionScopeInfo();
904     }
905   };
906 
907   /// WeakUndeclaredIdentifiers - Identifiers contained in
908   /// \#pragma weak before declared. rare. may alias another
909   /// identifier, declared or undeclared
910   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
911 
912   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
913   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
914   /// to define functions that occur in multiple standards to call the version
915   /// in the currently selected standard.
916   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
917 
918 
919   /// Load weak undeclared identifiers from the external source.
920   void LoadExternalWeakUndeclaredIdentifiers();
921 
922   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
923   /// \#pragma weak during processing of other Decls.
924   /// I couldn't figure out a clean way to generate these in-line, so
925   /// we store them here and handle separately -- which is a hack.
926   /// It would be best to refactor this.
927   SmallVector<Decl*,2> WeakTopLevelDecl;
928 
929   IdentifierResolver IdResolver;
930 
931   /// Translation Unit Scope - useful to Objective-C actions that need
932   /// to lookup file scope declarations in the "ordinary" C decl namespace.
933   /// For example, user-defined classes, built-in "id" type, etc.
934   Scope *TUScope;
935 
936   /// The C++ "std" namespace, where the standard library resides.
937   LazyDeclPtr StdNamespace;
938 
939   /// The C++ "std::bad_alloc" class, which is defined by the C++
940   /// standard library.
941   LazyDeclPtr StdBadAlloc;
942 
943   /// The C++ "std::align_val_t" enum class, which is defined by the C++
944   /// standard library.
945   LazyDeclPtr StdAlignValT;
946 
947   /// The C++ "std::experimental" namespace, where the experimental parts
948   /// of the standard library resides.
949   NamespaceDecl *StdExperimentalNamespaceCache;
950 
951   /// The C++ "std::initializer_list" template, which is defined in
952   /// \<initializer_list>.
953   ClassTemplateDecl *StdInitializerList;
954 
955   /// The C++ "std::coroutine_traits" template, which is defined in
956   /// \<coroutine_traits>
957   ClassTemplateDecl *StdCoroutineTraitsCache;
958 
959   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
960   RecordDecl *CXXTypeInfoDecl;
961 
962   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
963   RecordDecl *MSVCGuidDecl;
964 
965   /// Caches identifiers/selectors for NSFoundation APIs.
966   std::unique_ptr<NSAPI> NSAPIObj;
967 
968   /// The declaration of the Objective-C NSNumber class.
969   ObjCInterfaceDecl *NSNumberDecl;
970 
971   /// The declaration of the Objective-C NSValue class.
972   ObjCInterfaceDecl *NSValueDecl;
973 
974   /// Pointer to NSNumber type (NSNumber *).
975   QualType NSNumberPointer;
976 
977   /// Pointer to NSValue type (NSValue *).
978   QualType NSValuePointer;
979 
980   /// The Objective-C NSNumber methods used to create NSNumber literals.
981   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
982 
983   /// The declaration of the Objective-C NSString class.
984   ObjCInterfaceDecl *NSStringDecl;
985 
986   /// Pointer to NSString type (NSString *).
987   QualType NSStringPointer;
988 
989   /// The declaration of the stringWithUTF8String: method.
990   ObjCMethodDecl *StringWithUTF8StringMethod;
991 
992   /// The declaration of the valueWithBytes:objCType: method.
993   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
994 
995   /// The declaration of the Objective-C NSArray class.
996   ObjCInterfaceDecl *NSArrayDecl;
997 
998   /// The declaration of the arrayWithObjects:count: method.
999   ObjCMethodDecl *ArrayWithObjectsMethod;
1000 
1001   /// The declaration of the Objective-C NSDictionary class.
1002   ObjCInterfaceDecl *NSDictionaryDecl;
1003 
1004   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1005   ObjCMethodDecl *DictionaryWithObjectsMethod;
1006 
1007   /// id<NSCopying> type.
1008   QualType QIDNSCopying;
1009 
1010   /// will hold 'respondsToSelector:'
1011   Selector RespondsToSelectorSel;
1012 
1013   /// A flag to remember whether the implicit forms of operator new and delete
1014   /// have been declared.
1015   bool GlobalNewDeleteDeclared;
1016 
1017   /// A flag to indicate that we're in a context that permits abstract
1018   /// references to fields.  This is really a
1019   bool AllowAbstractFieldReference;
1020 
1021   /// Describes how the expressions currently being parsed are
1022   /// evaluated at run-time, if at all.
1023   enum class ExpressionEvaluationContext {
1024     /// The current expression and its subexpressions occur within an
1025     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1026     /// \c sizeof, where the type of the expression may be significant but
1027     /// no code will be generated to evaluate the value of the expression at
1028     /// run time.
1029     Unevaluated,
1030 
1031     /// The current expression occurs within a braced-init-list within
1032     /// an unevaluated operand. This is mostly like a regular unevaluated
1033     /// context, except that we still instantiate constexpr functions that are
1034     /// referenced here so that we can perform narrowing checks correctly.
1035     UnevaluatedList,
1036 
1037     /// The current expression occurs within a discarded statement.
1038     /// This behaves largely similarly to an unevaluated operand in preventing
1039     /// definitions from being required, but not in other ways.
1040     DiscardedStatement,
1041 
1042     /// The current expression occurs within an unevaluated
1043     /// operand that unconditionally permits abstract references to
1044     /// fields, such as a SIZE operator in MS-style inline assembly.
1045     UnevaluatedAbstract,
1046 
1047     /// The current context is "potentially evaluated" in C++11 terms,
1048     /// but the expression is evaluated at compile-time (like the values of
1049     /// cases in a switch statement).
1050     ConstantEvaluated,
1051 
1052     /// The current expression is potentially evaluated at run time,
1053     /// which means that code may be generated to evaluate the value of the
1054     /// expression at run time.
1055     PotentiallyEvaluated,
1056 
1057     /// The current expression is potentially evaluated, but any
1058     /// declarations referenced inside that expression are only used if
1059     /// in fact the current expression is used.
1060     ///
1061     /// This value is used when parsing default function arguments, for which
1062     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1063     /// through varargs) but do not want to mark declarations as "referenced"
1064     /// until the default argument is used.
1065     PotentiallyEvaluatedIfUsed
1066   };
1067 
1068   /// Data structure used to record current or nested
1069   /// expression evaluation contexts.
1070   struct ExpressionEvaluationContextRecord {
1071     /// The expression evaluation context.
1072     ExpressionEvaluationContext Context;
1073 
1074     /// Whether the enclosing context needed a cleanup.
1075     CleanupInfo ParentCleanup;
1076 
1077     /// Whether we are in a decltype expression.
1078     bool IsDecltype;
1079 
1080     /// The number of active cleanup objects when we entered
1081     /// this expression evaluation context.
1082     unsigned NumCleanupObjects;
1083 
1084     /// The number of typos encountered during this expression evaluation
1085     /// context (i.e. the number of TypoExprs created).
1086     unsigned NumTypos;
1087 
1088     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1089 
1090     /// The lambdas that are present within this context, if it
1091     /// is indeed an unevaluated context.
1092     SmallVector<LambdaExpr *, 2> Lambdas;
1093 
1094     /// The declaration that provides context for lambda expressions
1095     /// and block literals if the normal declaration context does not
1096     /// suffice, e.g., in a default function argument.
1097     Decl *ManglingContextDecl;
1098 
1099     /// If we are processing a decltype type, a set of call expressions
1100     /// for which we have deferred checking the completeness of the return type.
1101     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1102 
1103     /// If we are processing a decltype type, a set of temporary binding
1104     /// expressions for which we have deferred checking the destructor.
1105     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1106 
1107     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1108 
1109     /// Expressions appearing as the LHS of a volatile assignment in this
1110     /// context. We produce a warning for these when popping the context if
1111     /// they are not discarded-value expressions nor unevaluated operands.
1112     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1113 
1114     /// \brief Describes whether we are in an expression constext which we have
1115     /// to handle differently.
1116     enum ExpressionKind {
1117       EK_Decltype, EK_TemplateArgument, EK_Other
1118     } ExprContext;
1119 
1120     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1121                                       unsigned NumCleanupObjects,
1122                                       CleanupInfo ParentCleanup,
1123                                       Decl *ManglingContextDecl,
1124                                       ExpressionKind ExprContext)
1125         : Context(Context), ParentCleanup(ParentCleanup),
1126           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1127           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1128 
1129     bool isUnevaluated() const {
1130       return Context == ExpressionEvaluationContext::Unevaluated ||
1131              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1132              Context == ExpressionEvaluationContext::UnevaluatedList;
1133     }
1134     bool isConstantEvaluated() const {
1135       return Context == ExpressionEvaluationContext::ConstantEvaluated;
1136     }
1137   };
1138 
1139   /// A stack of expression evaluation contexts.
1140   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1141 
1142   /// Emit a warning for all pending noderef expressions that we recorded.
1143   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1144 
1145   /// Compute the mangling number context for a lambda expression or
1146   /// block literal. Also return the extra mangling decl if any.
1147   ///
1148   /// \param DC - The DeclContext containing the lambda expression or
1149   /// block literal.
1150   std::tuple<MangleNumberingContext *, Decl *>
1151   getCurrentMangleNumberContext(const DeclContext *DC);
1152 
1153 
1154   /// SpecialMemberOverloadResult - The overloading result for a special member
1155   /// function.
1156   ///
1157   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1158   /// integer are used to determine whether overload resolution succeeded.
1159   class SpecialMemberOverloadResult {
1160   public:
1161     enum Kind {
1162       NoMemberOrDeleted,
1163       Ambiguous,
1164       Success
1165     };
1166 
1167   private:
1168     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1169 
1170   public:
1171     SpecialMemberOverloadResult() : Pair() {}
1172     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1173         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1174 
1175     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1176     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1177 
1178     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1179     void setKind(Kind K) { Pair.setInt(K); }
1180   };
1181 
1182   class SpecialMemberOverloadResultEntry
1183       : public llvm::FastFoldingSetNode,
1184         public SpecialMemberOverloadResult {
1185   public:
1186     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1187       : FastFoldingSetNode(ID)
1188     {}
1189   };
1190 
1191   /// A cache of special member function overload resolution results
1192   /// for C++ records.
1193   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1194 
1195   /// A cache of the flags available in enumerations with the flag_bits
1196   /// attribute.
1197   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1198 
1199   /// The kind of translation unit we are processing.
1200   ///
1201   /// When we're processing a complete translation unit, Sema will perform
1202   /// end-of-translation-unit semantic tasks (such as creating
1203   /// initializers for tentative definitions in C) once parsing has
1204   /// completed. Modules and precompiled headers perform different kinds of
1205   /// checks.
1206   TranslationUnitKind TUKind;
1207 
1208   llvm::BumpPtrAllocator BumpAlloc;
1209 
1210   /// The number of SFINAE diagnostics that have been trapped.
1211   unsigned NumSFINAEErrors;
1212 
1213   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1214     UnparsedDefaultArgInstantiationsMap;
1215 
1216   /// A mapping from parameters with unparsed default arguments to the
1217   /// set of instantiations of each parameter.
1218   ///
1219   /// This mapping is a temporary data structure used when parsing
1220   /// nested class templates or nested classes of class templates,
1221   /// where we might end up instantiating an inner class before the
1222   /// default arguments of its methods have been parsed.
1223   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1224 
1225   // Contains the locations of the beginning of unparsed default
1226   // argument locations.
1227   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1228 
1229   /// UndefinedInternals - all the used, undefined objects which require a
1230   /// definition in this translation unit.
1231   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1232 
1233   /// Determine if VD, which must be a variable or function, is an external
1234   /// symbol that nonetheless can't be referenced from outside this translation
1235   /// unit because its type has no linkage and it's not extern "C".
1236   bool isExternalWithNoLinkageType(ValueDecl *VD);
1237 
1238   /// Obtain a sorted list of functions that are undefined but ODR-used.
1239   void getUndefinedButUsed(
1240       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1241 
1242   /// Retrieves list of suspicious delete-expressions that will be checked at
1243   /// the end of translation unit.
1244   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1245   getMismatchingDeleteExpressions() const;
1246 
1247   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1248   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1249 
1250   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1251   /// We need to maintain a list, since selectors can have differing signatures
1252   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1253   /// of selectors are "overloaded").
1254   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1255   /// methods inside categories with a particular selector.
1256   GlobalMethodPool MethodPool;
1257 
1258   /// Method selectors used in a \@selector expression. Used for implementation
1259   /// of -Wselector.
1260   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1261 
1262   /// List of SourceLocations where 'self' is implicitly retained inside a
1263   /// block.
1264   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1265       ImplicitlyRetainedSelfLocs;
1266 
1267   /// Kinds of C++ special members.
1268   enum CXXSpecialMember {
1269     CXXDefaultConstructor,
1270     CXXCopyConstructor,
1271     CXXMoveConstructor,
1272     CXXCopyAssignment,
1273     CXXMoveAssignment,
1274     CXXDestructor,
1275     CXXInvalid
1276   };
1277 
1278   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1279       SpecialMemberDecl;
1280 
1281   /// The C++ special members which we are currently in the process of
1282   /// declaring. If this process recursively triggers the declaration of the
1283   /// same special member, we should act as if it is not yet declared.
1284   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1285 
1286   /// Kinds of defaulted comparison operator functions.
1287   enum class DefaultedComparisonKind : unsigned char {
1288     /// This is not a defaultable comparison operator.
1289     None,
1290     /// This is an operator== that should be implemented as a series of
1291     /// subobject comparisons.
1292     Equal,
1293     /// This is an operator<=> that should be implemented as a series of
1294     /// subobject comparisons.
1295     ThreeWay,
1296     /// This is an operator!= that should be implemented as a rewrite in terms
1297     /// of a == comparison.
1298     NotEqual,
1299     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1300     /// terms of a <=> comparison.
1301     Relational,
1302   };
1303 
1304   /// The function definitions which were renamed as part of typo-correction
1305   /// to match their respective declarations. We want to keep track of them
1306   /// to ensure that we don't emit a "redefinition" error if we encounter a
1307   /// correctly named definition after the renamed definition.
1308   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1309 
1310   /// Stack of types that correspond to the parameter entities that are
1311   /// currently being copy-initialized. Can be empty.
1312   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1313 
1314   void ReadMethodPool(Selector Sel);
1315   void updateOutOfDateSelector(Selector Sel);
1316 
1317   /// Private Helper predicate to check for 'self'.
1318   bool isSelfExpr(Expr *RExpr);
1319   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1320 
1321   /// Cause the active diagnostic on the DiagosticsEngine to be
1322   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1323   /// should not be used elsewhere.
1324   void EmitCurrentDiagnostic(unsigned DiagID);
1325 
1326   /// Records and restores the FP_CONTRACT state on entry/exit of compound
1327   /// statements.
1328   class FPContractStateRAII {
1329   public:
1330     FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1331     ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1332 
1333   private:
1334     Sema& S;
1335     FPOptions OldFPFeaturesState;
1336   };
1337 
1338   void addImplicitTypedef(StringRef Name, QualType T);
1339 
1340   bool WarnedStackExhausted = false;
1341 
1342 public:
1343   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1344        TranslationUnitKind TUKind = TU_Complete,
1345        CodeCompleteConsumer *CompletionConsumer = nullptr);
1346   ~Sema();
1347 
1348   /// Perform initialization that occurs after the parser has been
1349   /// initialized but before it parses anything.
1350   void Initialize();
1351 
1352   const LangOptions &getLangOpts() const { return LangOpts; }
1353   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1354   FPOptions     &getFPOptions() { return FPFeatures; }
1355 
1356   DiagnosticsEngine &getDiagnostics() const { return Diags; }
1357   SourceManager &getSourceManager() const { return SourceMgr; }
1358   Preprocessor &getPreprocessor() const { return PP; }
1359   ASTContext &getASTContext() const { return Context; }
1360   ASTConsumer &getASTConsumer() const { return Consumer; }
1361   ASTMutationListener *getASTMutationListener() const;
1362   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1363 
1364   ///Registers an external source. If an external source already exists,
1365   /// creates a multiplex external source and appends to it.
1366   ///
1367   ///\param[in] E - A non-null external sema source.
1368   ///
1369   void addExternalSource(ExternalSemaSource *E);
1370 
1371   void PrintStats() const;
1372 
1373   /// Warn that the stack is nearly exhausted.
1374   void warnStackExhausted(SourceLocation Loc);
1375 
1376   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1377   /// guaranteed). Produces a warning if we're low on stack space and allocates
1378   /// more in that case. Use this in code that may recurse deeply (for example,
1379   /// in template instantiation) to avoid stack overflow.
1380   void runWithSufficientStackSpace(SourceLocation Loc,
1381                                    llvm::function_ref<void()> Fn);
1382 
1383   /// Helper class that creates diagnostics with optional
1384   /// template instantiation stacks.
1385   ///
1386   /// This class provides a wrapper around the basic DiagnosticBuilder
1387   /// class that emits diagnostics. SemaDiagnosticBuilder is
1388   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1389   /// does) and, if the diagnostic comes from inside a template
1390   /// instantiation, printing the template instantiation stack as
1391   /// well.
1392   class SemaDiagnosticBuilder : public DiagnosticBuilder {
1393     Sema &SemaRef;
1394     unsigned DiagID;
1395 
1396   public:
1397     SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1398       : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1399 
1400     // This is a cunning lie. DiagnosticBuilder actually performs move
1401     // construction in its copy constructor (but due to varied uses, it's not
1402     // possible to conveniently express this as actual move construction). So
1403     // the default copy ctor here is fine, because the base class disables the
1404     // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1405     // in that case anwyay.
1406     SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1407 
1408     ~SemaDiagnosticBuilder() {
1409       // If we aren't active, there is nothing to do.
1410       if (!isActive()) return;
1411 
1412       // Otherwise, we need to emit the diagnostic. First flush the underlying
1413       // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1414       // won't emit the diagnostic in its own destructor.
1415       //
1416       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1417       // do its own needless checks to see if the diagnostic needs to be
1418       // emitted. However, because we take care to ensure that the builder
1419       // objects never escape, a sufficiently smart compiler will be able to
1420       // eliminate that code.
1421       FlushCounts();
1422       Clear();
1423 
1424       // Dispatch to Sema to emit the diagnostic.
1425       SemaRef.EmitCurrentDiagnostic(DiagID);
1426     }
1427 
1428     /// Teach operator<< to produce an object of the correct type.
1429     template<typename T>
1430     friend const SemaDiagnosticBuilder &operator<<(
1431         const SemaDiagnosticBuilder &Diag, const T &Value) {
1432       const DiagnosticBuilder &BaseDiag = Diag;
1433       BaseDiag << Value;
1434       return Diag;
1435     }
1436   };
1437 
1438   /// Emit a diagnostic.
1439   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1440     DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1441     return SemaDiagnosticBuilder(DB, *this, DiagID);
1442   }
1443 
1444   /// Emit a partial diagnostic.
1445   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1446 
1447   /// Build a partial diagnostic.
1448   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1449 
1450   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1451 
1452   /// Get a string to suggest for zero-initialization of a type.
1453   std::string
1454   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1455   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1456 
1457   /// Calls \c Lexer::getLocForEndOfToken()
1458   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1459 
1460   /// Retrieve the module loader associated with the preprocessor.
1461   ModuleLoader &getModuleLoader() const;
1462 
1463   /// Invent a new identifier for parameters of abbreviated templates.
1464   IdentifierInfo *
1465   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1466                                              unsigned Index);
1467 
1468   void emitAndClearUnusedLocalTypedefWarnings();
1469 
1470   enum TUFragmentKind {
1471     /// The global module fragment, between 'module;' and a module-declaration.
1472     Global,
1473     /// A normal translation unit fragment. For a non-module unit, this is the
1474     /// entire translation unit. Otherwise, it runs from the module-declaration
1475     /// to the private-module-fragment (if any) or the end of the TU (if not).
1476     Normal,
1477     /// The private module fragment, between 'module :private;' and the end of
1478     /// the translation unit.
1479     Private
1480   };
1481 
1482   void ActOnStartOfTranslationUnit();
1483   void ActOnEndOfTranslationUnit();
1484   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1485 
1486   void CheckDelegatingCtorCycles();
1487 
1488   Scope *getScopeForContext(DeclContext *Ctx);
1489 
1490   void PushFunctionScope();
1491   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1492   sema::LambdaScopeInfo *PushLambdaScope();
1493 
1494   /// This is used to inform Sema what the current TemplateParameterDepth
1495   /// is during Parsing.  Currently it is used to pass on the depth
1496   /// when parsing generic lambda 'auto' parameters.
1497   void RecordParsingTemplateParameterDepth(unsigned Depth);
1498 
1499   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1500                                RecordDecl *RD, CapturedRegionKind K,
1501                                unsigned OpenMPCaptureLevel = 0);
1502 
1503   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1504   /// time after they've been popped.
1505   class PoppedFunctionScopeDeleter {
1506     Sema *Self;
1507 
1508   public:
1509     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1510     void operator()(sema::FunctionScopeInfo *Scope) const;
1511   };
1512 
1513   using PoppedFunctionScopePtr =
1514       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1515 
1516   PoppedFunctionScopePtr
1517   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1518                        const Decl *D = nullptr,
1519                        QualType BlockType = QualType());
1520 
1521   sema::FunctionScopeInfo *getCurFunction() const {
1522     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1523   }
1524 
1525   sema::FunctionScopeInfo *getEnclosingFunction() const;
1526 
1527   void setFunctionHasBranchIntoScope();
1528   void setFunctionHasBranchProtectedScope();
1529   void setFunctionHasIndirectGoto();
1530 
1531   void PushCompoundScope(bool IsStmtExpr);
1532   void PopCompoundScope();
1533 
1534   sema::CompoundScopeInfo &getCurCompoundScope() const;
1535 
1536   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1537 
1538   /// Retrieve the current block, if any.
1539   sema::BlockScopeInfo *getCurBlock();
1540 
1541   /// Get the innermost lambda enclosing the current location, if any. This
1542   /// looks through intervening non-lambda scopes such as local functions and
1543   /// blocks.
1544   sema::LambdaScopeInfo *getEnclosingLambda() const;
1545 
1546   /// Retrieve the current lambda scope info, if any.
1547   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1548   /// lambda scope info ignoring all inner capturing scopes that are not
1549   /// lambda scopes.
1550   sema::LambdaScopeInfo *
1551   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1552 
1553   /// Retrieve the current generic lambda info, if any.
1554   sema::LambdaScopeInfo *getCurGenericLambda();
1555 
1556   /// Retrieve the current captured region, if any.
1557   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1558 
1559   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1560   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1561 
1562   /// Called before parsing a function declarator belonging to a function
1563   /// declaration.
1564   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1565                                                unsigned TemplateParameterDepth);
1566 
1567   /// Called after parsing a function declarator belonging to a function
1568   /// declaration.
1569   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1570 
1571   void ActOnComment(SourceRange Comment);
1572 
1573   //===--------------------------------------------------------------------===//
1574   // Type Analysis / Processing: SemaType.cpp.
1575   //
1576 
1577   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1578                               const DeclSpec *DS = nullptr);
1579   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1580                               const DeclSpec *DS = nullptr);
1581   QualType BuildPointerType(QualType T,
1582                             SourceLocation Loc, DeclarationName Entity);
1583   QualType BuildReferenceType(QualType T, bool LValueRef,
1584                               SourceLocation Loc, DeclarationName Entity);
1585   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1586                           Expr *ArraySize, unsigned Quals,
1587                           SourceRange Brackets, DeclarationName Entity);
1588   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1589   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1590                               SourceLocation AttrLoc);
1591   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1592                                  SourceLocation AttrLoc);
1593 
1594   /// Same as above, but constructs the AddressSpace index if not provided.
1595   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1596                                  SourceLocation AttrLoc);
1597 
1598   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1599 
1600   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1601 
1602   /// Build a function type.
1603   ///
1604   /// This routine checks the function type according to C++ rules and
1605   /// under the assumption that the result type and parameter types have
1606   /// just been instantiated from a template. It therefore duplicates
1607   /// some of the behavior of GetTypeForDeclarator, but in a much
1608   /// simpler form that is only suitable for this narrow use case.
1609   ///
1610   /// \param T The return type of the function.
1611   ///
1612   /// \param ParamTypes The parameter types of the function. This array
1613   /// will be modified to account for adjustments to the types of the
1614   /// function parameters.
1615   ///
1616   /// \param Loc The location of the entity whose type involves this
1617   /// function type or, if there is no such entity, the location of the
1618   /// type that will have function type.
1619   ///
1620   /// \param Entity The name of the entity that involves the function
1621   /// type, if known.
1622   ///
1623   /// \param EPI Extra information about the function type. Usually this will
1624   /// be taken from an existing function with the same prototype.
1625   ///
1626   /// \returns A suitable function type, if there are no errors. The
1627   /// unqualified type will always be a FunctionProtoType.
1628   /// Otherwise, returns a NULL type.
1629   QualType BuildFunctionType(QualType T,
1630                              MutableArrayRef<QualType> ParamTypes,
1631                              SourceLocation Loc, DeclarationName Entity,
1632                              const FunctionProtoType::ExtProtoInfo &EPI);
1633 
1634   QualType BuildMemberPointerType(QualType T, QualType Class,
1635                                   SourceLocation Loc,
1636                                   DeclarationName Entity);
1637   QualType BuildBlockPointerType(QualType T,
1638                                  SourceLocation Loc, DeclarationName Entity);
1639   QualType BuildParenType(QualType T);
1640   QualType BuildAtomicType(QualType T, SourceLocation Loc);
1641   QualType BuildReadPipeType(QualType T,
1642                          SourceLocation Loc);
1643   QualType BuildWritePipeType(QualType T,
1644                          SourceLocation Loc);
1645 
1646   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1647   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1648 
1649   /// Package the given type and TSI into a ParsedType.
1650   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1651   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1652   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1653   static QualType GetTypeFromParser(ParsedType Ty,
1654                                     TypeSourceInfo **TInfo = nullptr);
1655   CanThrowResult canThrow(const Stmt *E);
1656   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1657                                                 const FunctionProtoType *FPT);
1658   void UpdateExceptionSpec(FunctionDecl *FD,
1659                            const FunctionProtoType::ExceptionSpecInfo &ESI);
1660   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1661   bool CheckDistantExceptionSpec(QualType T);
1662   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1663   bool CheckEquivalentExceptionSpec(
1664       const FunctionProtoType *Old, SourceLocation OldLoc,
1665       const FunctionProtoType *New, SourceLocation NewLoc);
1666   bool CheckEquivalentExceptionSpec(
1667       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1668       const FunctionProtoType *Old, SourceLocation OldLoc,
1669       const FunctionProtoType *New, SourceLocation NewLoc);
1670   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1671   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1672                                 const PartialDiagnostic &NestedDiagID,
1673                                 const PartialDiagnostic &NoteID,
1674                                 const PartialDiagnostic &NoThrowDiagID,
1675                                 const FunctionProtoType *Superset,
1676                                 SourceLocation SuperLoc,
1677                                 const FunctionProtoType *Subset,
1678                                 SourceLocation SubLoc);
1679   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1680                                const PartialDiagnostic &NoteID,
1681                                const FunctionProtoType *Target,
1682                                SourceLocation TargetLoc,
1683                                const FunctionProtoType *Source,
1684                                SourceLocation SourceLoc);
1685 
1686   TypeResult ActOnTypeName(Scope *S, Declarator &D);
1687 
1688   /// The parser has parsed the context-sensitive type 'instancetype'
1689   /// in an Objective-C message declaration. Return the appropriate type.
1690   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1691 
1692   /// Abstract class used to diagnose incomplete types.
1693   struct TypeDiagnoser {
1694     TypeDiagnoser() {}
1695 
1696     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1697     virtual ~TypeDiagnoser() {}
1698   };
1699 
1700   static int getPrintable(int I) { return I; }
1701   static unsigned getPrintable(unsigned I) { return I; }
1702   static bool getPrintable(bool B) { return B; }
1703   static const char * getPrintable(const char *S) { return S; }
1704   static StringRef getPrintable(StringRef S) { return S; }
1705   static const std::string &getPrintable(const std::string &S) { return S; }
1706   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1707     return II;
1708   }
1709   static DeclarationName getPrintable(DeclarationName N) { return N; }
1710   static QualType getPrintable(QualType T) { return T; }
1711   static SourceRange getPrintable(SourceRange R) { return R; }
1712   static SourceRange getPrintable(SourceLocation L) { return L; }
1713   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1714   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1715 
1716   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1717     unsigned DiagID;
1718     std::tuple<const Ts &...> Args;
1719 
1720     template <std::size_t... Is>
1721     void emit(const SemaDiagnosticBuilder &DB,
1722               std::index_sequence<Is...>) const {
1723       // Apply all tuple elements to the builder in order.
1724       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1725       (void)Dummy;
1726     }
1727 
1728   public:
1729     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1730         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1731       assert(DiagID != 0 && "no diagnostic for type diagnoser");
1732     }
1733 
1734     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1735       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1736       emit(DB, std::index_sequence_for<Ts...>());
1737       DB << T;
1738     }
1739   };
1740 
1741 private:
1742   /// Methods for marking which expressions involve dereferencing a pointer
1743   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
1744   /// they are parsed, meaning that a noderef pointer may not be accessed. For
1745   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
1746   /// `*p`, but need to check that `address of` is called on it. This requires
1747   /// keeping a container of all pending expressions and checking if the address
1748   /// of them are eventually taken.
1749   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
1750   void CheckAddressOfNoDeref(const Expr *E);
1751   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
1752 
1753   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1754                                TypeDiagnoser *Diagnoser);
1755 
1756   struct ModuleScope {
1757     SourceLocation BeginLoc;
1758     clang::Module *Module = nullptr;
1759     bool ModuleInterface = false;
1760     bool ImplicitGlobalModuleFragment = false;
1761     VisibleModuleSet OuterVisibleModules;
1762   };
1763   /// The modules we're currently parsing.
1764   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1765 
1766   /// Namespace definitions that we will export when they finish.
1767   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
1768 
1769   /// Get the module whose scope we are currently within.
1770   Module *getCurrentModule() const {
1771     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1772   }
1773 
1774   VisibleModuleSet VisibleModules;
1775 
1776 public:
1777   /// Get the module owning an entity.
1778   Module *getOwningModule(const Decl *Entity) {
1779     return Entity->getOwningModule();
1780   }
1781 
1782   /// Make a merged definition of an existing hidden definition \p ND
1783   /// visible at the specified location.
1784   void makeMergedDefinitionVisible(NamedDecl *ND);
1785 
1786   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
1787 
1788   /// Determine whether a declaration is visible to name lookup.
1789   bool isVisible(const NamedDecl *D) {
1790     return !D->isHidden() || isVisibleSlow(D);
1791   }
1792 
1793   /// Determine whether any declaration of an entity is visible.
1794   bool
1795   hasVisibleDeclaration(const NamedDecl *D,
1796                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1797     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1798   }
1799   bool hasVisibleDeclarationSlow(const NamedDecl *D,
1800                                  llvm::SmallVectorImpl<Module *> *Modules);
1801 
1802   bool hasVisibleMergedDefinition(NamedDecl *Def);
1803   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1804 
1805   /// Determine if \p D and \p Suggested have a structurally compatible
1806   /// layout as described in C11 6.2.7/1.
1807   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1808 
1809   /// Determine if \p D has a visible definition. If not, suggest a declaration
1810   /// that should be made visible to expose the definition.
1811   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1812                             bool OnlyNeedComplete = false);
1813   bool hasVisibleDefinition(const NamedDecl *D) {
1814     NamedDecl *Hidden;
1815     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1816   }
1817 
1818   /// Determine if the template parameter \p D has a visible default argument.
1819   bool
1820   hasVisibleDefaultArgument(const NamedDecl *D,
1821                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1822 
1823   /// Determine if there is a visible declaration of \p D that is an explicit
1824   /// specialization declaration for a specialization of a template. (For a
1825   /// member specialization, use hasVisibleMemberSpecialization.)
1826   bool hasVisibleExplicitSpecialization(
1827       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1828 
1829   /// Determine if there is a visible declaration of \p D that is a member
1830   /// specialization declaration (as opposed to an instantiated declaration).
1831   bool hasVisibleMemberSpecialization(
1832       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1833 
1834   /// Determine if \p A and \p B are equivalent internal linkage declarations
1835   /// from different modules, and thus an ambiguity error can be downgraded to
1836   /// an extension warning.
1837   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1838                                               const NamedDecl *B);
1839   void diagnoseEquivalentInternalLinkageDeclarations(
1840       SourceLocation Loc, const NamedDecl *D,
1841       ArrayRef<const NamedDecl *> Equiv);
1842 
1843   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
1844 
1845   bool isCompleteType(SourceLocation Loc, QualType T) {
1846     return !RequireCompleteTypeImpl(Loc, T, nullptr);
1847   }
1848   bool RequireCompleteType(SourceLocation Loc, QualType T,
1849                            TypeDiagnoser &Diagnoser);
1850   bool RequireCompleteType(SourceLocation Loc, QualType T,
1851                            unsigned DiagID);
1852 
1853   template <typename... Ts>
1854   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1855                            const Ts &...Args) {
1856     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1857     return RequireCompleteType(Loc, T, Diagnoser);
1858   }
1859 
1860   void completeExprArrayBound(Expr *E);
1861   bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1862   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1863 
1864   template <typename... Ts>
1865   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1866     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1867     return RequireCompleteExprType(E, Diagnoser);
1868   }
1869 
1870   bool RequireLiteralType(SourceLocation Loc, QualType T,
1871                           TypeDiagnoser &Diagnoser);
1872   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1873 
1874   template <typename... Ts>
1875   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1876                           const Ts &...Args) {
1877     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1878     return RequireLiteralType(Loc, T, Diagnoser);
1879   }
1880 
1881   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1882                              const CXXScopeSpec &SS, QualType T,
1883                              TagDecl *OwnedTagDecl = nullptr);
1884 
1885   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1886   /// If AsUnevaluated is false, E is treated as though it were an evaluated
1887   /// context, such as when building a type for decltype(auto).
1888   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1889                              bool AsUnevaluated = true);
1890   QualType BuildUnaryTransformType(QualType BaseType,
1891                                    UnaryTransformType::UTTKind UKind,
1892                                    SourceLocation Loc);
1893 
1894   //===--------------------------------------------------------------------===//
1895   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1896   //
1897 
1898   struct SkipBodyInfo {
1899     SkipBodyInfo()
1900         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1901           New(nullptr) {}
1902     bool ShouldSkip;
1903     bool CheckSameAsPrevious;
1904     NamedDecl *Previous;
1905     NamedDecl *New;
1906   };
1907 
1908   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1909 
1910   void DiagnoseUseOfUnimplementedSelectors();
1911 
1912   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1913 
1914   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1915                          Scope *S, CXXScopeSpec *SS = nullptr,
1916                          bool isClassName = false, bool HasTrailingDot = false,
1917                          ParsedType ObjectType = nullptr,
1918                          bool IsCtorOrDtorName = false,
1919                          bool WantNontrivialTypeSourceInfo = false,
1920                          bool IsClassTemplateDeductionContext = true,
1921                          IdentifierInfo **CorrectedII = nullptr);
1922   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1923   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1924   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1925                                SourceLocation IILoc,
1926                                Scope *S,
1927                                CXXScopeSpec *SS,
1928                                ParsedType &SuggestedType,
1929                                bool IsTemplateName = false);
1930 
1931   /// Attempt to behave like MSVC in situations where lookup of an unqualified
1932   /// type name has failed in a dependent context. In these situations, we
1933   /// automatically form a DependentTypeName that will retry lookup in a related
1934   /// scope during instantiation.
1935   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1936                                       SourceLocation NameLoc,
1937                                       bool IsTemplateTypeArg);
1938 
1939   /// Describes the result of the name lookup and resolution performed
1940   /// by \c ClassifyName().
1941   enum NameClassificationKind {
1942     /// This name is not a type or template in this context, but might be
1943     /// something else.
1944     NC_Unknown,
1945     /// Classification failed; an error has been produced.
1946     NC_Error,
1947     /// The name has been typo-corrected to a keyword.
1948     NC_Keyword,
1949     /// The name was classified as a type.
1950     NC_Type,
1951     /// The name was classified as a specific non-type, non-template
1952     /// declaration. ActOnNameClassifiedAsNonType should be called to
1953     /// convert the declaration to an expression.
1954     NC_NonType,
1955     /// The name was classified as an ADL-only function name.
1956     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
1957     /// result to an expression.
1958     NC_UndeclaredNonType,
1959     /// The name denotes a member of a dependent type that could not be
1960     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
1961     /// convert the result to an expression.
1962     NC_DependentNonType,
1963     /// The name was classified as a non-type, and an expression representing
1964     /// that name has been formed.
1965     NC_ContextIndependentExpr,
1966     /// The name was classified as a template whose specializations are types.
1967     NC_TypeTemplate,
1968     /// The name was classified as a variable template name.
1969     NC_VarTemplate,
1970     /// The name was classified as a function template name.
1971     NC_FunctionTemplate,
1972     /// The name was classified as an ADL-only function template name.
1973     NC_UndeclaredTemplate,
1974     /// The name was classified as a concept name.
1975     NC_Concept,
1976   };
1977 
1978   class NameClassification {
1979     NameClassificationKind Kind;
1980     union {
1981       ExprResult Expr;
1982       NamedDecl *NonTypeDecl;
1983       TemplateName Template;
1984       ParsedType Type;
1985     };
1986 
1987     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1988 
1989   public:
1990     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1991 
1992     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1993 
1994     static NameClassification Error() {
1995       return NameClassification(NC_Error);
1996     }
1997 
1998     static NameClassification Unknown() {
1999       return NameClassification(NC_Unknown);
2000     }
2001 
2002     static NameClassification ContextIndependentExpr(ExprResult E) {
2003       NameClassification Result(NC_ContextIndependentExpr);
2004       Result.Expr = E;
2005       return Result;
2006     }
2007 
2008     static NameClassification NonType(NamedDecl *D) {
2009       NameClassification Result(NC_NonType);
2010       Result.NonTypeDecl = D;
2011       return Result;
2012     }
2013 
2014     static NameClassification UndeclaredNonType() {
2015       return NameClassification(NC_UndeclaredNonType);
2016     }
2017 
2018     static NameClassification DependentNonType() {
2019       return NameClassification(NC_DependentNonType);
2020     }
2021 
2022     static NameClassification TypeTemplate(TemplateName Name) {
2023       NameClassification Result(NC_TypeTemplate);
2024       Result.Template = Name;
2025       return Result;
2026     }
2027 
2028     static NameClassification VarTemplate(TemplateName Name) {
2029       NameClassification Result(NC_VarTemplate);
2030       Result.Template = Name;
2031       return Result;
2032     }
2033 
2034     static NameClassification FunctionTemplate(TemplateName Name) {
2035       NameClassification Result(NC_FunctionTemplate);
2036       Result.Template = Name;
2037       return Result;
2038     }
2039 
2040     static NameClassification Concept(TemplateName Name) {
2041       NameClassification Result(NC_Concept);
2042       Result.Template = Name;
2043       return Result;
2044     }
2045 
2046     static NameClassification UndeclaredTemplate(TemplateName Name) {
2047       NameClassification Result(NC_UndeclaredTemplate);
2048       Result.Template = Name;
2049       return Result;
2050     }
2051 
2052     NameClassificationKind getKind() const { return Kind; }
2053 
2054     ExprResult getExpression() const {
2055       assert(Kind == NC_ContextIndependentExpr);
2056       return Expr;
2057     }
2058 
2059     ParsedType getType() const {
2060       assert(Kind == NC_Type);
2061       return Type;
2062     }
2063 
2064     NamedDecl *getNonTypeDecl() const {
2065       assert(Kind == NC_NonType);
2066       return NonTypeDecl;
2067     }
2068 
2069     TemplateName getTemplateName() const {
2070       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2071              Kind == NC_VarTemplate || Kind == NC_Concept ||
2072              Kind == NC_UndeclaredTemplate);
2073       return Template;
2074     }
2075 
2076     TemplateNameKind getTemplateNameKind() const {
2077       switch (Kind) {
2078       case NC_TypeTemplate:
2079         return TNK_Type_template;
2080       case NC_FunctionTemplate:
2081         return TNK_Function_template;
2082       case NC_VarTemplate:
2083         return TNK_Var_template;
2084       case NC_Concept:
2085         return TNK_Concept_template;
2086       case NC_UndeclaredTemplate:
2087         return TNK_Undeclared_template;
2088       default:
2089         llvm_unreachable("unsupported name classification.");
2090       }
2091     }
2092   };
2093 
2094   /// Perform name lookup on the given name, classifying it based on
2095   /// the results of name lookup and the following token.
2096   ///
2097   /// This routine is used by the parser to resolve identifiers and help direct
2098   /// parsing. When the identifier cannot be found, this routine will attempt
2099   /// to correct the typo and classify based on the resulting name.
2100   ///
2101   /// \param S The scope in which we're performing name lookup.
2102   ///
2103   /// \param SS The nested-name-specifier that precedes the name.
2104   ///
2105   /// \param Name The identifier. If typo correction finds an alternative name,
2106   /// this pointer parameter will be updated accordingly.
2107   ///
2108   /// \param NameLoc The location of the identifier.
2109   ///
2110   /// \param NextToken The token following the identifier. Used to help
2111   /// disambiguate the name.
2112   ///
2113   /// \param CCC The correction callback, if typo correction is desired.
2114   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2115                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2116                                   const Token &NextToken,
2117                                   CorrectionCandidateCallback *CCC = nullptr);
2118 
2119   /// Act on the result of classifying a name as an undeclared (ADL-only)
2120   /// non-type declaration.
2121   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2122                                                     SourceLocation NameLoc);
2123   /// Act on the result of classifying a name as an undeclared member of a
2124   /// dependent base class.
2125   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2126                                                    IdentifierInfo *Name,
2127                                                    SourceLocation NameLoc,
2128                                                    bool IsAddressOfOperand);
2129   /// Act on the result of classifying a name as a specific non-type
2130   /// declaration.
2131   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2132                                           NamedDecl *Found,
2133                                           SourceLocation NameLoc,
2134                                           const Token &NextToken);
2135 
2136   /// Describes the detailed kind of a template name. Used in diagnostics.
2137   enum class TemplateNameKindForDiagnostics {
2138     ClassTemplate,
2139     FunctionTemplate,
2140     VarTemplate,
2141     AliasTemplate,
2142     TemplateTemplateParam,
2143     Concept,
2144     DependentTemplate
2145   };
2146   TemplateNameKindForDiagnostics
2147   getTemplateNameKindForDiagnostics(TemplateName Name);
2148 
2149   /// Determine whether it's plausible that E was intended to be a
2150   /// template-name.
2151   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2152     if (!getLangOpts().CPlusPlus || E.isInvalid())
2153       return false;
2154     Dependent = false;
2155     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2156       return !DRE->hasExplicitTemplateArgs();
2157     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2158       return !ME->hasExplicitTemplateArgs();
2159     Dependent = true;
2160     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2161       return !DSDRE->hasExplicitTemplateArgs();
2162     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2163       return !DSME->hasExplicitTemplateArgs();
2164     // Any additional cases recognized here should also be handled by
2165     // diagnoseExprIntendedAsTemplateName.
2166     return false;
2167   }
2168   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2169                                           SourceLocation Less,
2170                                           SourceLocation Greater);
2171 
2172   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2173 
2174   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2175                               MultiTemplateParamsArg TemplateParameterLists);
2176   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2177   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2178   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2179                                     DeclarationName Name, SourceLocation Loc,
2180                                     bool IsTemplateId);
2181   void
2182   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2183                             SourceLocation FallbackLoc,
2184                             SourceLocation ConstQualLoc = SourceLocation(),
2185                             SourceLocation VolatileQualLoc = SourceLocation(),
2186                             SourceLocation RestrictQualLoc = SourceLocation(),
2187                             SourceLocation AtomicQualLoc = SourceLocation(),
2188                             SourceLocation UnalignedQualLoc = SourceLocation());
2189 
2190   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2191   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2192   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2193                                     const LookupResult &R);
2194   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2195   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2196                    const LookupResult &R);
2197   void CheckShadow(Scope *S, VarDecl *D);
2198 
2199   /// Warn if 'E', which is an expression that is about to be modified, refers
2200   /// to a shadowing declaration.
2201   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2202 
2203   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2204 
2205 private:
2206   /// Map of current shadowing declarations to shadowed declarations. Warn if
2207   /// it looks like the user is trying to modify the shadowing declaration.
2208   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2209 
2210 public:
2211   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2212   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2213   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2214                                     TypedefNameDecl *NewTD);
2215   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2216   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2217                                     TypeSourceInfo *TInfo,
2218                                     LookupResult &Previous);
2219   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2220                                   LookupResult &Previous, bool &Redeclaration);
2221   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2222                                      TypeSourceInfo *TInfo,
2223                                      LookupResult &Previous,
2224                                      MultiTemplateParamsArg TemplateParamLists,
2225                                      bool &AddToScope,
2226                                      ArrayRef<BindingDecl *> Bindings = None);
2227   NamedDecl *
2228   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2229                                MultiTemplateParamsArg TemplateParamLists);
2230   // Returns true if the variable declaration is a redeclaration
2231   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2232   void CheckVariableDeclarationType(VarDecl *NewVD);
2233   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2234                                      Expr *Init);
2235   void CheckCompleteVariableDeclaration(VarDecl *VD);
2236   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2237   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2238 
2239   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2240                                      TypeSourceInfo *TInfo,
2241                                      LookupResult &Previous,
2242                                      MultiTemplateParamsArg TemplateParamLists,
2243                                      bool &AddToScope);
2244   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2245 
2246   enum class CheckConstexprKind {
2247     /// Diagnose issues that are non-constant or that are extensions.
2248     Diagnose,
2249     /// Identify whether this function satisfies the formal rules for constexpr
2250     /// functions in the current lanugage mode (with no extensions).
2251     CheckValid
2252   };
2253 
2254   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2255                                         CheckConstexprKind Kind);
2256 
2257   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2258   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2259                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2260   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2261                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2262   // Returns true if the function declaration is a redeclaration
2263   bool CheckFunctionDeclaration(Scope *S,
2264                                 FunctionDecl *NewFD, LookupResult &Previous,
2265                                 bool IsMemberSpecialization);
2266   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2267   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2268                                       QualType NewT, QualType OldT);
2269   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2270   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2271   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2272                                                    bool IsDefinition);
2273   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2274   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2275   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2276                                           SourceLocation Loc,
2277                                           QualType T);
2278   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2279                               SourceLocation NameLoc, IdentifierInfo *Name,
2280                               QualType T, TypeSourceInfo *TSInfo,
2281                               StorageClass SC);
2282   void ActOnParamDefaultArgument(Decl *param,
2283                                  SourceLocation EqualLoc,
2284                                  Expr *defarg);
2285   void ActOnParamUnparsedDefaultArgument(Decl *param,
2286                                          SourceLocation EqualLoc,
2287                                          SourceLocation ArgLoc);
2288   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2289   bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2290                                SourceLocation EqualLoc);
2291 
2292   // Contexts where using non-trivial C union types can be disallowed. This is
2293   // passed to err_non_trivial_c_union_in_invalid_context.
2294   enum NonTrivialCUnionContext {
2295     // Function parameter.
2296     NTCUC_FunctionParam,
2297     // Function return.
2298     NTCUC_FunctionReturn,
2299     // Default-initialized object.
2300     NTCUC_DefaultInitializedObject,
2301     // Variable with automatic storage duration.
2302     NTCUC_AutoVar,
2303     // Initializer expression that might copy from another object.
2304     NTCUC_CopyInit,
2305     // Assignment.
2306     NTCUC_Assignment,
2307     // Compound literal.
2308     NTCUC_CompoundLiteral,
2309     // Block capture.
2310     NTCUC_BlockCapture,
2311     // lvalue-to-rvalue conversion of volatile type.
2312     NTCUC_LValueToRValueVolatile,
2313   };
2314 
2315   /// Emit diagnostics if the initializer or any of its explicit or
2316   /// implicitly-generated subexpressions require copying or
2317   /// default-initializing a type that is or contains a C union type that is
2318   /// non-trivial to copy or default-initialize.
2319   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2320 
2321   // These flags are passed to checkNonTrivialCUnion.
2322   enum NonTrivialCUnionKind {
2323     NTCUK_Init = 0x1,
2324     NTCUK_Destruct = 0x2,
2325     NTCUK_Copy = 0x4,
2326   };
2327 
2328   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2329   /// a non-trivial C union is used in an invalid context.
2330   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2331                              NonTrivialCUnionContext UseContext,
2332                              unsigned NonTrivialKind);
2333 
2334   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2335   void ActOnUninitializedDecl(Decl *dcl);
2336   void ActOnInitializerError(Decl *Dcl);
2337 
2338   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2339   void ActOnCXXForRangeDecl(Decl *D);
2340   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2341                                         IdentifierInfo *Ident,
2342                                         ParsedAttributes &Attrs,
2343                                         SourceLocation AttrEnd);
2344   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2345   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2346   void CheckStaticLocalForDllExport(VarDecl *VD);
2347   void FinalizeDeclaration(Decl *D);
2348   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2349                                          ArrayRef<Decl *> Group);
2350   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2351 
2352   /// Should be called on all declarations that might have attached
2353   /// documentation comments.
2354   void ActOnDocumentableDecl(Decl *D);
2355   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2356 
2357   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2358                                        SourceLocation LocAfterDecls);
2359   void CheckForFunctionRedefinition(
2360       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2361       SkipBodyInfo *SkipBody = nullptr);
2362   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2363                                 MultiTemplateParamsArg TemplateParamLists,
2364                                 SkipBodyInfo *SkipBody = nullptr);
2365   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2366                                 SkipBodyInfo *SkipBody = nullptr);
2367   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2368   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2369   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2370   bool isObjCMethodDecl(Decl *D) {
2371     return D && isa<ObjCMethodDecl>(D);
2372   }
2373 
2374   /// Determine whether we can delay parsing the body of a function or
2375   /// function template until it is used, assuming we don't care about emitting
2376   /// code for that function.
2377   ///
2378   /// This will be \c false if we may need the body of the function in the
2379   /// middle of parsing an expression (where it's impractical to switch to
2380   /// parsing a different function), for instance, if it's constexpr in C++11
2381   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2382   bool canDelayFunctionBody(const Declarator &D);
2383 
2384   /// Determine whether we can skip parsing the body of a function
2385   /// definition, assuming we don't care about analyzing its body or emitting
2386   /// code for that function.
2387   ///
2388   /// This will be \c false only if we may need the body of the function in
2389   /// order to parse the rest of the program (for instance, if it is
2390   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2391   bool canSkipFunctionBody(Decl *D);
2392 
2393   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2394   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2395   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2396   Decl *ActOnSkippedFunctionBody(Decl *Decl);
2397   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2398 
2399   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2400   /// attribute for which parsing is delayed.
2401   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2402 
2403   /// Diagnose any unused parameters in the given sequence of
2404   /// ParmVarDecl pointers.
2405   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2406 
2407   /// Diagnose whether the size of parameters or return value of a
2408   /// function or obj-c method definition is pass-by-value and larger than a
2409   /// specified threshold.
2410   void
2411   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2412                                          QualType ReturnTy, NamedDecl *D);
2413 
2414   void DiagnoseInvalidJumps(Stmt *Body);
2415   Decl *ActOnFileScopeAsmDecl(Expr *expr,
2416                               SourceLocation AsmLoc,
2417                               SourceLocation RParenLoc);
2418 
2419   /// Handle a C++11 empty-declaration and attribute-declaration.
2420   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2421                               SourceLocation SemiLoc);
2422 
2423   enum class ModuleDeclKind {
2424     Interface,      ///< 'export module X;'
2425     Implementation, ///< 'module X;'
2426   };
2427 
2428   /// The parser has processed a module-declaration that begins the definition
2429   /// of a module interface or implementation.
2430   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2431                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2432                                  ModuleIdPath Path, bool IsFirstDecl);
2433 
2434   /// The parser has processed a global-module-fragment declaration that begins
2435   /// the definition of the global module fragment of the current module unit.
2436   /// \param ModuleLoc The location of the 'module' keyword.
2437   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2438 
2439   /// The parser has processed a private-module-fragment declaration that begins
2440   /// the definition of the private module fragment of the current module unit.
2441   /// \param ModuleLoc The location of the 'module' keyword.
2442   /// \param PrivateLoc The location of the 'private' keyword.
2443   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2444                                                 SourceLocation PrivateLoc);
2445 
2446   /// The parser has processed a module import declaration.
2447   ///
2448   /// \param StartLoc The location of the first token in the declaration. This
2449   ///        could be the location of an '@', 'export', or 'import'.
2450   /// \param ExportLoc The location of the 'export' keyword, if any.
2451   /// \param ImportLoc The location of the 'import' keyword.
2452   /// \param Path The module access path.
2453   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2454                                SourceLocation ExportLoc,
2455                                SourceLocation ImportLoc, ModuleIdPath Path);
2456   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2457                                SourceLocation ExportLoc,
2458                                SourceLocation ImportLoc, Module *M,
2459                                ModuleIdPath Path = {});
2460 
2461   /// The parser has processed a module import translated from a
2462   /// #include or similar preprocessing directive.
2463   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2464   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2465 
2466   /// The parsed has entered a submodule.
2467   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2468   /// The parser has left a submodule.
2469   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2470 
2471   /// Create an implicit import of the given module at the given
2472   /// source location, for error recovery, if possible.
2473   ///
2474   /// This routine is typically used when an entity found by name lookup
2475   /// is actually hidden within a module that we know about but the user
2476   /// has forgotten to import.
2477   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2478                                                   Module *Mod);
2479 
2480   /// Kinds of missing import. Note, the values of these enumerators correspond
2481   /// to %select values in diagnostics.
2482   enum class MissingImportKind {
2483     Declaration,
2484     Definition,
2485     DefaultArgument,
2486     ExplicitSpecialization,
2487     PartialSpecialization
2488   };
2489 
2490   /// Diagnose that the specified declaration needs to be visible but
2491   /// isn't, and suggest a module import that would resolve the problem.
2492   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2493                              MissingImportKind MIK, bool Recover = true);
2494   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2495                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2496                              MissingImportKind MIK, bool Recover);
2497 
2498   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2499                              SourceLocation LBraceLoc);
2500   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2501                               SourceLocation RBraceLoc);
2502 
2503   /// We've found a use of a templated declaration that would trigger an
2504   /// implicit instantiation. Check that any relevant explicit specializations
2505   /// and partial specializations are visible, and diagnose if not.
2506   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2507 
2508   /// We've found a use of a template specialization that would select a
2509   /// partial specialization. Check that the partial specialization is visible,
2510   /// and diagnose if not.
2511   void checkPartialSpecializationVisibility(SourceLocation Loc,
2512                                             NamedDecl *Spec);
2513 
2514   /// Retrieve a suitable printing policy for diagnostics.
2515   PrintingPolicy getPrintingPolicy() const {
2516     return getPrintingPolicy(Context, PP);
2517   }
2518 
2519   /// Retrieve a suitable printing policy for diagnostics.
2520   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2521                                           const Preprocessor &PP);
2522 
2523   /// Scope actions.
2524   void ActOnPopScope(SourceLocation Loc, Scope *S);
2525   void ActOnTranslationUnitScope(Scope *S);
2526 
2527   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2528                                    RecordDecl *&AnonRecord);
2529   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2530                                    MultiTemplateParamsArg TemplateParams,
2531                                    bool IsExplicitInstantiation,
2532                                    RecordDecl *&AnonRecord);
2533 
2534   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2535                                     AccessSpecifier AS,
2536                                     RecordDecl *Record,
2537                                     const PrintingPolicy &Policy);
2538 
2539   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2540                                        RecordDecl *Record);
2541 
2542   /// Common ways to introduce type names without a tag for use in diagnostics.
2543   /// Keep in sync with err_tag_reference_non_tag.
2544   enum NonTagKind {
2545     NTK_NonStruct,
2546     NTK_NonClass,
2547     NTK_NonUnion,
2548     NTK_NonEnum,
2549     NTK_Typedef,
2550     NTK_TypeAlias,
2551     NTK_Template,
2552     NTK_TypeAliasTemplate,
2553     NTK_TemplateTemplateArgument,
2554   };
2555 
2556   /// Given a non-tag type declaration, returns an enum useful for indicating
2557   /// what kind of non-tag type this is.
2558   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2559 
2560   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2561                                     TagTypeKind NewTag, bool isDefinition,
2562                                     SourceLocation NewTagLoc,
2563                                     const IdentifierInfo *Name);
2564 
2565   enum TagUseKind {
2566     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
2567     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
2568     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
2569     TUK_Friend       // Friend declaration:  'friend struct foo;'
2570   };
2571 
2572   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2573                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2574                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
2575                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2576                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2577                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2578                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2579                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2580                  SkipBodyInfo *SkipBody = nullptr);
2581 
2582   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2583                                 unsigned TagSpec, SourceLocation TagLoc,
2584                                 CXXScopeSpec &SS, IdentifierInfo *Name,
2585                                 SourceLocation NameLoc,
2586                                 const ParsedAttributesView &Attr,
2587                                 MultiTemplateParamsArg TempParamLists);
2588 
2589   TypeResult ActOnDependentTag(Scope *S,
2590                                unsigned TagSpec,
2591                                TagUseKind TUK,
2592                                const CXXScopeSpec &SS,
2593                                IdentifierInfo *Name,
2594                                SourceLocation TagLoc,
2595                                SourceLocation NameLoc);
2596 
2597   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2598                  IdentifierInfo *ClassName,
2599                  SmallVectorImpl<Decl *> &Decls);
2600   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2601                    Declarator &D, Expr *BitfieldWidth);
2602 
2603   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2604                          Declarator &D, Expr *BitfieldWidth,
2605                          InClassInitStyle InitStyle,
2606                          AccessSpecifier AS);
2607   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2608                                    SourceLocation DeclStart, Declarator &D,
2609                                    Expr *BitfieldWidth,
2610                                    InClassInitStyle InitStyle,
2611                                    AccessSpecifier AS,
2612                                    const ParsedAttr &MSPropertyAttr);
2613 
2614   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2615                             TypeSourceInfo *TInfo,
2616                             RecordDecl *Record, SourceLocation Loc,
2617                             bool Mutable, Expr *BitfieldWidth,
2618                             InClassInitStyle InitStyle,
2619                             SourceLocation TSSL,
2620                             AccessSpecifier AS, NamedDecl *PrevDecl,
2621                             Declarator *D = nullptr);
2622 
2623   bool CheckNontrivialField(FieldDecl *FD);
2624   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2625 
2626   enum TrivialABIHandling {
2627     /// The triviality of a method unaffected by "trivial_abi".
2628     TAH_IgnoreTrivialABI,
2629 
2630     /// The triviality of a method affected by "trivial_abi".
2631     TAH_ConsiderTrivialABI
2632   };
2633 
2634   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2635                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2636                               bool Diagnose = false);
2637 
2638   /// For a defaulted function, the kind of defaulted function that it is.
2639   class DefaultedFunctionKind {
2640     CXXSpecialMember SpecialMember : 8;
2641     DefaultedComparisonKind Comparison : 8;
2642 
2643   public:
2644     DefaultedFunctionKind()
2645         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2646     }
2647     DefaultedFunctionKind(CXXSpecialMember CSM)
2648         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
2649     DefaultedFunctionKind(DefaultedComparisonKind Comp)
2650         : SpecialMember(CXXInvalid), Comparison(Comp) {}
2651 
2652     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
2653     bool isComparison() const {
2654       return Comparison != DefaultedComparisonKind::None;
2655     }
2656 
2657     explicit operator bool() const {
2658       return isSpecialMember() || isComparison();
2659     }
2660 
2661     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
2662     DefaultedComparisonKind asComparison() const { return Comparison; }
2663 
2664     /// Get the index of this function kind for use in diagnostics.
2665     unsigned getDiagnosticIndex() const {
2666       static_assert(CXXInvalid > CXXDestructor,
2667                     "invalid should have highest index");
2668       static_assert((unsigned)DefaultedComparisonKind::None == 0,
2669                     "none should be equal to zero");
2670       return SpecialMember + (unsigned)Comparison;
2671     }
2672   };
2673 
2674   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2675 
2676   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2677     return getDefaultedFunctionKind(MD).asSpecialMember();
2678   }
2679   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2680     return getDefaultedFunctionKind(FD).asComparison();
2681   }
2682 
2683   void ActOnLastBitfield(SourceLocation DeclStart,
2684                          SmallVectorImpl<Decl *> &AllIvarDecls);
2685   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2686                   Declarator &D, Expr *BitfieldWidth,
2687                   tok::ObjCKeywordKind visibility);
2688 
2689   // This is used for both record definitions and ObjC interface declarations.
2690   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2691                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
2692                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
2693 
2694   /// ActOnTagStartDefinition - Invoked when we have entered the
2695   /// scope of a tag's definition (e.g., for an enumeration, class,
2696   /// struct, or union).
2697   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2698 
2699   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2700   /// Differently from C++, actually parse the body and reject / error out
2701   /// in case of a structural mismatch.
2702   bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2703                                 SkipBodyInfo &SkipBody);
2704 
2705   typedef void *SkippedDefinitionContext;
2706 
2707   /// Invoked when we enter a tag definition that we're skipping.
2708   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2709 
2710   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2711 
2712   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2713   /// C++ record definition's base-specifiers clause and are starting its
2714   /// member declarations.
2715   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2716                                        SourceLocation FinalLoc,
2717                                        bool IsFinalSpelledSealed,
2718                                        SourceLocation LBraceLoc);
2719 
2720   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2721   /// the definition of a tag (enumeration, class, struct, or union).
2722   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2723                                 SourceRange BraceRange);
2724 
2725   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2726 
2727   void ActOnObjCContainerFinishDefinition();
2728 
2729   /// Invoked when we must temporarily exit the objective-c container
2730   /// scope for parsing/looking-up C constructs.
2731   ///
2732   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2733   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2734   void ActOnObjCReenterContainerContext(DeclContext *DC);
2735 
2736   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2737   /// error parsing the definition of a tag.
2738   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2739 
2740   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2741                                       EnumConstantDecl *LastEnumConst,
2742                                       SourceLocation IdLoc,
2743                                       IdentifierInfo *Id,
2744                                       Expr *val);
2745   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2746   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2747                               QualType EnumUnderlyingTy, bool IsFixed,
2748                               const EnumDecl *Prev);
2749 
2750   /// Determine whether the body of an anonymous enumeration should be skipped.
2751   /// \param II The name of the first enumerator.
2752   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2753                                       SourceLocation IILoc);
2754 
2755   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2756                           SourceLocation IdLoc, IdentifierInfo *Id,
2757                           const ParsedAttributesView &Attrs,
2758                           SourceLocation EqualLoc, Expr *Val);
2759   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2760                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
2761                      const ParsedAttributesView &Attr);
2762 
2763   DeclContext *getContainingDC(DeclContext *DC);
2764 
2765   /// Set the current declaration context until it gets popped.
2766   void PushDeclContext(Scope *S, DeclContext *DC);
2767   void PopDeclContext();
2768 
2769   /// EnterDeclaratorContext - Used when we must lookup names in the context
2770   /// of a declarator's nested name specifier.
2771   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2772   void ExitDeclaratorContext(Scope *S);
2773 
2774   /// Push the parameters of D, which must be a function, into scope.
2775   void ActOnReenterFunctionContext(Scope* S, Decl* D);
2776   void ActOnExitFunctionContext();
2777 
2778   DeclContext *getFunctionLevelDeclContext();
2779 
2780   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2781   /// to the function decl for the function being parsed.  If we're currently
2782   /// in a 'block', this returns the containing context.
2783   FunctionDecl *getCurFunctionDecl();
2784 
2785   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2786   /// the method decl for the method being parsed.  If we're currently
2787   /// in a 'block', this returns the containing context.
2788   ObjCMethodDecl *getCurMethodDecl();
2789 
2790   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2791   /// or C function we're in, otherwise return null.  If we're currently
2792   /// in a 'block', this returns the containing context.
2793   NamedDecl *getCurFunctionOrMethodDecl();
2794 
2795   /// Add this decl to the scope shadowed decl chains.
2796   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2797 
2798   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2799   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2800   /// true if 'D' belongs to the given declaration context.
2801   ///
2802   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2803   ///        enclosing namespace set of the context, rather than contained
2804   ///        directly within it.
2805   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2806                      bool AllowInlineNamespace = false);
2807 
2808   /// Finds the scope corresponding to the given decl context, if it
2809   /// happens to be an enclosing scope.  Otherwise return NULL.
2810   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2811 
2812   /// Subroutines of ActOnDeclarator().
2813   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2814                                 TypeSourceInfo *TInfo);
2815   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2816 
2817   /// Describes the kind of merge to perform for availability
2818   /// attributes (including "deprecated", "unavailable", and "availability").
2819   enum AvailabilityMergeKind {
2820     /// Don't merge availability attributes at all.
2821     AMK_None,
2822     /// Merge availability attributes for a redeclaration, which requires
2823     /// an exact match.
2824     AMK_Redeclaration,
2825     /// Merge availability attributes for an override, which requires
2826     /// an exact match or a weakening of constraints.
2827     AMK_Override,
2828     /// Merge availability attributes for an implementation of
2829     /// a protocol requirement.
2830     AMK_ProtocolImplementation,
2831   };
2832 
2833   /// Describes the kind of priority given to an availability attribute.
2834   ///
2835   /// The sum of priorities deteremines the final priority of the attribute.
2836   /// The final priority determines how the attribute will be merged.
2837   /// An attribute with a lower priority will always remove higher priority
2838   /// attributes for the specified platform when it is being applied. An
2839   /// attribute with a higher priority will not be applied if the declaration
2840   /// already has an availability attribute with a lower priority for the
2841   /// specified platform. The final prirority values are not expected to match
2842   /// the values in this enumeration, but instead should be treated as a plain
2843   /// integer value. This enumeration just names the priority weights that are
2844   /// used to calculate that final vaue.
2845   enum AvailabilityPriority : int {
2846     /// The availability attribute was specified explicitly next to the
2847     /// declaration.
2848     AP_Explicit = 0,
2849 
2850     /// The availability attribute was applied using '#pragma clang attribute'.
2851     AP_PragmaClangAttribute = 1,
2852 
2853     /// The availability attribute for a specific platform was inferred from
2854     /// an availability attribute for another platform.
2855     AP_InferredFromOtherPlatform = 2
2856   };
2857 
2858   /// Attribute merging methods. Return true if a new attribute was added.
2859   AvailabilityAttr *
2860   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
2861                         IdentifierInfo *Platform, bool Implicit,
2862                         VersionTuple Introduced, VersionTuple Deprecated,
2863                         VersionTuple Obsoleted, bool IsUnavailable,
2864                         StringRef Message, bool IsStrict, StringRef Replacement,
2865                         AvailabilityMergeKind AMK, int Priority);
2866   TypeVisibilityAttr *
2867   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2868                           TypeVisibilityAttr::VisibilityType Vis);
2869   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2870                                       VisibilityAttr::VisibilityType Vis);
2871   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
2872                           StringRef Uuid);
2873   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
2874   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
2875   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
2876                                             const AttributeCommonInfo &CI,
2877                                             bool BestCase,
2878                                             MSInheritanceModel Model);
2879   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
2880                               IdentifierInfo *Format, int FormatIdx,
2881                               int FirstArg);
2882   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2883                                 StringRef Name);
2884   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2885                                 StringRef Name);
2886   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
2887                                           const AttributeCommonInfo &CI,
2888                                           const IdentifierInfo *Ident);
2889   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
2890   NoSpeculativeLoadHardeningAttr *
2891   mergeNoSpeculativeLoadHardeningAttr(Decl *D,
2892                                       const NoSpeculativeLoadHardeningAttr &AL);
2893   SpeculativeLoadHardeningAttr *
2894   mergeSpeculativeLoadHardeningAttr(Decl *D,
2895                                     const SpeculativeLoadHardeningAttr &AL);
2896   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
2897                                           const AttributeCommonInfo &CI);
2898   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
2899   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
2900                                                 const InternalLinkageAttr &AL);
2901   CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
2902   CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
2903 
2904   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2905                            AvailabilityMergeKind AMK = AMK_Redeclaration);
2906   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2907                             LookupResult &OldDecls);
2908   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2909                          bool MergeTypeWithOld);
2910   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2911                                     Scope *S, bool MergeTypeWithOld);
2912   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2913   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2914   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2915   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2916   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2917   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2918   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2919 
2920   // AssignmentAction - This is used by all the assignment diagnostic functions
2921   // to represent what is actually causing the operation
2922   enum AssignmentAction {
2923     AA_Assigning,
2924     AA_Passing,
2925     AA_Returning,
2926     AA_Converting,
2927     AA_Initializing,
2928     AA_Sending,
2929     AA_Casting,
2930     AA_Passing_CFAudited
2931   };
2932 
2933   /// C++ Overloading.
2934   enum OverloadKind {
2935     /// This is a legitimate overload: the existing declarations are
2936     /// functions or function templates with different signatures.
2937     Ovl_Overload,
2938 
2939     /// This is not an overload because the signature exactly matches
2940     /// an existing declaration.
2941     Ovl_Match,
2942 
2943     /// This is not an overload because the lookup results contain a
2944     /// non-function.
2945     Ovl_NonFunction
2946   };
2947   OverloadKind CheckOverload(Scope *S,
2948                              FunctionDecl *New,
2949                              const LookupResult &OldDecls,
2950                              NamedDecl *&OldDecl,
2951                              bool IsForUsingDecl);
2952   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2953                   bool ConsiderCudaAttrs = true,
2954                   bool ConsiderRequiresClauses = true);
2955 
2956   ImplicitConversionSequence
2957   TryImplicitConversion(Expr *From, QualType ToType,
2958                         bool SuppressUserConversions,
2959                         bool AllowExplicit,
2960                         bool InOverloadResolution,
2961                         bool CStyle,
2962                         bool AllowObjCWritebackConversion);
2963 
2964   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2965   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2966   bool IsComplexPromotion(QualType FromType, QualType ToType);
2967   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2968                            bool InOverloadResolution,
2969                            QualType& ConvertedType, bool &IncompatibleObjC);
2970   bool isObjCPointerConversion(QualType FromType, QualType ToType,
2971                                QualType& ConvertedType, bool &IncompatibleObjC);
2972   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2973                                  QualType &ConvertedType);
2974   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2975                                 QualType& ConvertedType);
2976   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2977                                   const FunctionProtoType *NewType,
2978                                   unsigned *ArgPos = nullptr);
2979   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2980                                   QualType FromType, QualType ToType);
2981 
2982   void maybeExtendBlockObject(ExprResult &E);
2983   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2984   bool CheckPointerConversion(Expr *From, QualType ToType,
2985                               CastKind &Kind,
2986                               CXXCastPath& BasePath,
2987                               bool IgnoreBaseAccess,
2988                               bool Diagnose = true);
2989   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2990                                  bool InOverloadResolution,
2991                                  QualType &ConvertedType);
2992   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2993                                     CastKind &Kind,
2994                                     CXXCastPath &BasePath,
2995                                     bool IgnoreBaseAccess);
2996   bool IsQualificationConversion(QualType FromType, QualType ToType,
2997                                  bool CStyle, bool &ObjCLifetimeConversion);
2998   bool IsFunctionConversion(QualType FromType, QualType ToType,
2999                             QualType &ResultTy);
3000   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3001   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3002 
3003   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3004                                              const VarDecl *NRVOCandidate,
3005                                              QualType ResultType,
3006                                              Expr *Value,
3007                                              bool AllowNRVO = true);
3008 
3009   bool CanPerformAggregateInitializationForOverloadResolution(
3010       const InitializedEntity &Entity, InitListExpr *From);
3011 
3012   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3013                                     ExprResult Init);
3014   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3015                                        SourceLocation EqualLoc,
3016                                        ExprResult Init,
3017                                        bool TopLevelOfInitList = false,
3018                                        bool AllowExplicit = false);
3019   ExprResult PerformObjectArgumentInitialization(Expr *From,
3020                                                  NestedNameSpecifier *Qualifier,
3021                                                  NamedDecl *FoundDecl,
3022                                                  CXXMethodDecl *Method);
3023 
3024   /// Check that the lifetime of the initializer (and its subobjects) is
3025   /// sufficient for initializing the entity, and perform lifetime extension
3026   /// (when permitted) if not.
3027   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3028 
3029   ExprResult PerformContextuallyConvertToBool(Expr *From);
3030   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3031 
3032   /// Contexts in which a converted constant expression is required.
3033   enum CCEKind {
3034     CCEK_CaseValue,   ///< Expression in a case label.
3035     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
3036     CCEK_TemplateArg, ///< Value of a non-type template parameter.
3037     CCEK_NewExpr,     ///< Constant expression in a noptr-new-declarator.
3038     CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
3039     CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3040   };
3041   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3042                                               llvm::APSInt &Value, CCEKind CCE);
3043   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3044                                               APValue &Value, CCEKind CCE);
3045 
3046   /// Abstract base class used to perform a contextual implicit
3047   /// conversion from an expression to any type passing a filter.
3048   class ContextualImplicitConverter {
3049   public:
3050     bool Suppress;
3051     bool SuppressConversion;
3052 
3053     ContextualImplicitConverter(bool Suppress = false,
3054                                 bool SuppressConversion = false)
3055         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3056 
3057     /// Determine whether the specified type is a valid destination type
3058     /// for this conversion.
3059     virtual bool match(QualType T) = 0;
3060 
3061     /// Emits a diagnostic complaining that the expression does not have
3062     /// integral or enumeration type.
3063     virtual SemaDiagnosticBuilder
3064     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3065 
3066     /// Emits a diagnostic when the expression has incomplete class type.
3067     virtual SemaDiagnosticBuilder
3068     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3069 
3070     /// Emits a diagnostic when the only matching conversion function
3071     /// is explicit.
3072     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3073         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3074 
3075     /// Emits a note for the explicit conversion function.
3076     virtual SemaDiagnosticBuilder
3077     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3078 
3079     /// Emits a diagnostic when there are multiple possible conversion
3080     /// functions.
3081     virtual SemaDiagnosticBuilder
3082     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3083 
3084     /// Emits a note for one of the candidate conversions.
3085     virtual SemaDiagnosticBuilder
3086     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3087 
3088     /// Emits a diagnostic when we picked a conversion function
3089     /// (for cases when we are not allowed to pick a conversion function).
3090     virtual SemaDiagnosticBuilder diagnoseConversion(
3091         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3092 
3093     virtual ~ContextualImplicitConverter() {}
3094   };
3095 
3096   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3097     bool AllowScopedEnumerations;
3098 
3099   public:
3100     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3101                         bool Suppress, bool SuppressConversion)
3102         : ContextualImplicitConverter(Suppress, SuppressConversion),
3103           AllowScopedEnumerations(AllowScopedEnumerations) {}
3104 
3105     /// Match an integral or (possibly scoped) enumeration type.
3106     bool match(QualType T) override;
3107 
3108     SemaDiagnosticBuilder
3109     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3110       return diagnoseNotInt(S, Loc, T);
3111     }
3112 
3113     /// Emits a diagnostic complaining that the expression does not have
3114     /// integral or enumeration type.
3115     virtual SemaDiagnosticBuilder
3116     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3117   };
3118 
3119   /// Perform a contextual implicit conversion.
3120   ExprResult PerformContextualImplicitConversion(
3121       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3122 
3123 
3124   enum ObjCSubscriptKind {
3125     OS_Array,
3126     OS_Dictionary,
3127     OS_Error
3128   };
3129   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3130 
3131   // Note that LK_String is intentionally after the other literals, as
3132   // this is used for diagnostics logic.
3133   enum ObjCLiteralKind {
3134     LK_Array,
3135     LK_Dictionary,
3136     LK_Numeric,
3137     LK_Boxed,
3138     LK_String,
3139     LK_Block,
3140     LK_None
3141   };
3142   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3143 
3144   ExprResult PerformObjectMemberConversion(Expr *From,
3145                                            NestedNameSpecifier *Qualifier,
3146                                            NamedDecl *FoundDecl,
3147                                            NamedDecl *Member);
3148 
3149   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3150   // TODO: make this is a typesafe union.
3151   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3152   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3153 
3154   using ADLCallKind = CallExpr::ADLCallKind;
3155 
3156   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3157                             ArrayRef<Expr *> Args,
3158                             OverloadCandidateSet &CandidateSet,
3159                             bool SuppressUserConversions = false,
3160                             bool PartialOverloading = false,
3161                             bool AllowExplicit = true,
3162                             bool AllowExplicitConversion = false,
3163                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3164                             ConversionSequenceList EarlyConversions = None,
3165                             OverloadCandidateParamOrder PO = {});
3166   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3167                       ArrayRef<Expr *> Args,
3168                       OverloadCandidateSet &CandidateSet,
3169                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3170                       bool SuppressUserConversions = false,
3171                       bool PartialOverloading = false,
3172                       bool FirstArgumentIsBase = false);
3173   void AddMethodCandidate(DeclAccessPair FoundDecl,
3174                           QualType ObjectType,
3175                           Expr::Classification ObjectClassification,
3176                           ArrayRef<Expr *> Args,
3177                           OverloadCandidateSet& CandidateSet,
3178                           bool SuppressUserConversion = false,
3179                           OverloadCandidateParamOrder PO = {});
3180   void AddMethodCandidate(CXXMethodDecl *Method,
3181                           DeclAccessPair FoundDecl,
3182                           CXXRecordDecl *ActingContext, QualType ObjectType,
3183                           Expr::Classification ObjectClassification,
3184                           ArrayRef<Expr *> Args,
3185                           OverloadCandidateSet& CandidateSet,
3186                           bool SuppressUserConversions = false,
3187                           bool PartialOverloading = false,
3188                           ConversionSequenceList EarlyConversions = None,
3189                           OverloadCandidateParamOrder PO = {});
3190   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3191                                   DeclAccessPair FoundDecl,
3192                                   CXXRecordDecl *ActingContext,
3193                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3194                                   QualType ObjectType,
3195                                   Expr::Classification ObjectClassification,
3196                                   ArrayRef<Expr *> Args,
3197                                   OverloadCandidateSet& CandidateSet,
3198                                   bool SuppressUserConversions = false,
3199                                   bool PartialOverloading = false,
3200                                   OverloadCandidateParamOrder PO = {});
3201   void AddTemplateOverloadCandidate(
3202       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3203       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3204       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3205       bool PartialOverloading = false, bool AllowExplicit = true,
3206       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3207       OverloadCandidateParamOrder PO = {});
3208   bool CheckNonDependentConversions(
3209       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3210       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3211       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3212       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3213       Expr::Classification ObjectClassification = {},
3214       OverloadCandidateParamOrder PO = {});
3215   void AddConversionCandidate(
3216       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3217       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3218       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3219       bool AllowExplicit, bool AllowResultConversion = true);
3220   void AddTemplateConversionCandidate(
3221       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3222       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3223       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3224       bool AllowExplicit, bool AllowResultConversion = true);
3225   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3226                              DeclAccessPair FoundDecl,
3227                              CXXRecordDecl *ActingContext,
3228                              const FunctionProtoType *Proto,
3229                              Expr *Object, ArrayRef<Expr *> Args,
3230                              OverloadCandidateSet& CandidateSet);
3231   void AddNonMemberOperatorCandidates(
3232       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3233       OverloadCandidateSet &CandidateSet,
3234       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3235   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3236                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3237                                    OverloadCandidateSet &CandidateSet,
3238                                    OverloadCandidateParamOrder PO = {});
3239   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3240                            OverloadCandidateSet& CandidateSet,
3241                            bool IsAssignmentOperator = false,
3242                            unsigned NumContextualBoolArguments = 0);
3243   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3244                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3245                                     OverloadCandidateSet& CandidateSet);
3246   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3247                                             SourceLocation Loc,
3248                                             ArrayRef<Expr *> Args,
3249                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3250                                             OverloadCandidateSet& CandidateSet,
3251                                             bool PartialOverloading = false);
3252 
3253   // Emit as a 'note' the specific overload candidate
3254   void NoteOverloadCandidate(
3255       NamedDecl *Found, FunctionDecl *Fn,
3256       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3257       QualType DestType = QualType(), bool TakingAddress = false);
3258 
3259   // Emit as a series of 'note's all template and non-templates identified by
3260   // the expression Expr
3261   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3262                                  bool TakingAddress = false);
3263 
3264   /// Check the enable_if expressions on the given function. Returns the first
3265   /// failing attribute, or NULL if they were all successful.
3266   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
3267                               bool MissingImplicitThis = false);
3268 
3269   /// Find the failed Boolean condition within a given Boolean
3270   /// constant expression, and describe it with a string.
3271   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3272 
3273   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3274   /// non-ArgDependent DiagnoseIfAttrs.
3275   ///
3276   /// Argument-dependent diagnose_if attributes should be checked each time a
3277   /// function is used as a direct callee of a function call.
3278   ///
3279   /// Returns true if any errors were emitted.
3280   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3281                                            const Expr *ThisArg,
3282                                            ArrayRef<const Expr *> Args,
3283                                            SourceLocation Loc);
3284 
3285   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3286   /// ArgDependent DiagnoseIfAttrs.
3287   ///
3288   /// Argument-independent diagnose_if attributes should be checked on every use
3289   /// of a function.
3290   ///
3291   /// Returns true if any errors were emitted.
3292   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3293                                              SourceLocation Loc);
3294 
3295   /// Returns whether the given function's address can be taken or not,
3296   /// optionally emitting a diagnostic if the address can't be taken.
3297   ///
3298   /// Returns false if taking the address of the function is illegal.
3299   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3300                                          bool Complain = false,
3301                                          SourceLocation Loc = SourceLocation());
3302 
3303   // [PossiblyAFunctionType]  -->   [Return]
3304   // NonFunctionType --> NonFunctionType
3305   // R (A) --> R(A)
3306   // R (*)(A) --> R (A)
3307   // R (&)(A) --> R (A)
3308   // R (S::*)(A) --> R (A)
3309   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3310 
3311   FunctionDecl *
3312   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3313                                      QualType TargetType,
3314                                      bool Complain,
3315                                      DeclAccessPair &Found,
3316                                      bool *pHadMultipleCandidates = nullptr);
3317 
3318   FunctionDecl *
3319   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3320 
3321   bool resolveAndFixAddressOfSingleOverloadCandidate(
3322       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3323 
3324   FunctionDecl *
3325   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3326                                               bool Complain = false,
3327                                               DeclAccessPair *Found = nullptr);
3328 
3329   bool ResolveAndFixSingleFunctionTemplateSpecialization(
3330                       ExprResult &SrcExpr,
3331                       bool DoFunctionPointerConverion = false,
3332                       bool Complain = false,
3333                       SourceRange OpRangeForComplaining = SourceRange(),
3334                       QualType DestTypeForComplaining = QualType(),
3335                       unsigned DiagIDForComplaining = 0);
3336 
3337 
3338   Expr *FixOverloadedFunctionReference(Expr *E,
3339                                        DeclAccessPair FoundDecl,
3340                                        FunctionDecl *Fn);
3341   ExprResult FixOverloadedFunctionReference(ExprResult,
3342                                             DeclAccessPair FoundDecl,
3343                                             FunctionDecl *Fn);
3344 
3345   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3346                                    ArrayRef<Expr *> Args,
3347                                    OverloadCandidateSet &CandidateSet,
3348                                    bool PartialOverloading = false);
3349 
3350   // An enum used to represent the different possible results of building a
3351   // range-based for loop.
3352   enum ForRangeStatus {
3353     FRS_Success,
3354     FRS_NoViableFunction,
3355     FRS_DiagnosticIssued
3356   };
3357 
3358   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3359                                            SourceLocation RangeLoc,
3360                                            const DeclarationNameInfo &NameInfo,
3361                                            LookupResult &MemberLookup,
3362                                            OverloadCandidateSet *CandidateSet,
3363                                            Expr *Range, ExprResult *CallExpr);
3364 
3365   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3366                                      UnresolvedLookupExpr *ULE,
3367                                      SourceLocation LParenLoc,
3368                                      MultiExprArg Args,
3369                                      SourceLocation RParenLoc,
3370                                      Expr *ExecConfig,
3371                                      bool AllowTypoCorrection=true,
3372                                      bool CalleesAddressIsTaken=false);
3373 
3374   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3375                               MultiExprArg Args, SourceLocation RParenLoc,
3376                               OverloadCandidateSet *CandidateSet,
3377                               ExprResult *Result);
3378 
3379   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3380                                      UnaryOperatorKind Opc,
3381                                      const UnresolvedSetImpl &Fns,
3382                                      Expr *input, bool RequiresADL = true);
3383 
3384   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3385                              OverloadedOperatorKind Op,
3386                              const UnresolvedSetImpl &Fns,
3387                              ArrayRef<Expr *> Args, bool RequiresADL = true);
3388   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3389                                    BinaryOperatorKind Opc,
3390                                    const UnresolvedSetImpl &Fns,
3391                                    Expr *LHS, Expr *RHS,
3392                                    bool RequiresADL = true,
3393                                    bool AllowRewrittenCandidates = true,
3394                                    FunctionDecl *DefaultedFn = nullptr);
3395   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3396                                                 const UnresolvedSetImpl &Fns,
3397                                                 Expr *LHS, Expr *RHS,
3398                                                 FunctionDecl *DefaultedFn);
3399 
3400   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3401                                                 SourceLocation RLoc,
3402                                                 Expr *Base,Expr *Idx);
3403 
3404   ExprResult
3405   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3406                             SourceLocation LParenLoc,
3407                             MultiExprArg Args,
3408                             SourceLocation RParenLoc);
3409   ExprResult
3410   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3411                                MultiExprArg Args,
3412                                SourceLocation RParenLoc);
3413 
3414   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3415                                       SourceLocation OpLoc,
3416                                       bool *NoArrowOperatorFound = nullptr);
3417 
3418   /// CheckCallReturnType - Checks that a call expression's return type is
3419   /// complete. Returns true on failure. The location passed in is the location
3420   /// that best represents the call.
3421   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3422                            CallExpr *CE, FunctionDecl *FD);
3423 
3424   /// Helpers for dealing with blocks and functions.
3425   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3426                                 bool CheckParameterNames);
3427   void CheckCXXDefaultArguments(FunctionDecl *FD);
3428   void CheckExtraCXXDefaultArguments(Declarator &D);
3429   Scope *getNonFieldDeclScope(Scope *S);
3430 
3431   /// \name Name lookup
3432   ///
3433   /// These routines provide name lookup that is used during semantic
3434   /// analysis to resolve the various kinds of names (identifiers,
3435   /// overloaded operator names, constructor names, etc.) into zero or
3436   /// more declarations within a particular scope. The major entry
3437   /// points are LookupName, which performs unqualified name lookup,
3438   /// and LookupQualifiedName, which performs qualified name lookup.
3439   ///
3440   /// All name lookup is performed based on some specific criteria,
3441   /// which specify what names will be visible to name lookup and how
3442   /// far name lookup should work. These criteria are important both
3443   /// for capturing language semantics (certain lookups will ignore
3444   /// certain names, for example) and for performance, since name
3445   /// lookup is often a bottleneck in the compilation of C++. Name
3446   /// lookup criteria is specified via the LookupCriteria enumeration.
3447   ///
3448   /// The results of name lookup can vary based on the kind of name
3449   /// lookup performed, the current language, and the translation
3450   /// unit. In C, for example, name lookup will either return nothing
3451   /// (no entity found) or a single declaration. In C++, name lookup
3452   /// can additionally refer to a set of overloaded functions or
3453   /// result in an ambiguity. All of the possible results of name
3454   /// lookup are captured by the LookupResult class, which provides
3455   /// the ability to distinguish among them.
3456   //@{
3457 
3458   /// Describes the kind of name lookup to perform.
3459   enum LookupNameKind {
3460     /// Ordinary name lookup, which finds ordinary names (functions,
3461     /// variables, typedefs, etc.) in C and most kinds of names
3462     /// (functions, variables, members, types, etc.) in C++.
3463     LookupOrdinaryName = 0,
3464     /// Tag name lookup, which finds the names of enums, classes,
3465     /// structs, and unions.
3466     LookupTagName,
3467     /// Label name lookup.
3468     LookupLabel,
3469     /// Member name lookup, which finds the names of
3470     /// class/struct/union members.
3471     LookupMemberName,
3472     /// Look up of an operator name (e.g., operator+) for use with
3473     /// operator overloading. This lookup is similar to ordinary name
3474     /// lookup, but will ignore any declarations that are class members.
3475     LookupOperatorName,
3476     /// Look up of a name that precedes the '::' scope resolution
3477     /// operator in C++. This lookup completely ignores operator, object,
3478     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3479     LookupNestedNameSpecifierName,
3480     /// Look up a namespace name within a C++ using directive or
3481     /// namespace alias definition, ignoring non-namespace names (C++
3482     /// [basic.lookup.udir]p1).
3483     LookupNamespaceName,
3484     /// Look up all declarations in a scope with the given name,
3485     /// including resolved using declarations.  This is appropriate
3486     /// for checking redeclarations for a using declaration.
3487     LookupUsingDeclName,
3488     /// Look up an ordinary name that is going to be redeclared as a
3489     /// name with linkage. This lookup ignores any declarations that
3490     /// are outside of the current scope unless they have linkage. See
3491     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3492     LookupRedeclarationWithLinkage,
3493     /// Look up a friend of a local class. This lookup does not look
3494     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3495     LookupLocalFriendName,
3496     /// Look up the name of an Objective-C protocol.
3497     LookupObjCProtocolName,
3498     /// Look up implicit 'self' parameter of an objective-c method.
3499     LookupObjCImplicitSelfParam,
3500     /// Look up the name of an OpenMP user-defined reduction operation.
3501     LookupOMPReductionName,
3502     /// Look up the name of an OpenMP user-defined mapper.
3503     LookupOMPMapperName,
3504     /// Look up any declaration with any name.
3505     LookupAnyName
3506   };
3507 
3508   /// Specifies whether (or how) name lookup is being performed for a
3509   /// redeclaration (vs. a reference).
3510   enum RedeclarationKind {
3511     /// The lookup is a reference to this name that is not for the
3512     /// purpose of redeclaring the name.
3513     NotForRedeclaration = 0,
3514     /// The lookup results will be used for redeclaration of a name,
3515     /// if an entity by that name already exists and is visible.
3516     ForVisibleRedeclaration,
3517     /// The lookup results will be used for redeclaration of a name
3518     /// with external linkage; non-visible lookup results with external linkage
3519     /// may also be found.
3520     ForExternalRedeclaration
3521   };
3522 
3523   RedeclarationKind forRedeclarationInCurContext() {
3524     // A declaration with an owning module for linkage can never link against
3525     // anything that is not visible. We don't need to check linkage here; if
3526     // the context has internal linkage, redeclaration lookup won't find things
3527     // from other TUs, and we can't safely compute linkage yet in general.
3528     if (cast<Decl>(CurContext)
3529             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3530       return ForVisibleRedeclaration;
3531     return ForExternalRedeclaration;
3532   }
3533 
3534   /// The possible outcomes of name lookup for a literal operator.
3535   enum LiteralOperatorLookupResult {
3536     /// The lookup resulted in an error.
3537     LOLR_Error,
3538     /// The lookup found no match but no diagnostic was issued.
3539     LOLR_ErrorNoDiagnostic,
3540     /// The lookup found a single 'cooked' literal operator, which
3541     /// expects a normal literal to be built and passed to it.
3542     LOLR_Cooked,
3543     /// The lookup found a single 'raw' literal operator, which expects
3544     /// a string literal containing the spelling of the literal token.
3545     LOLR_Raw,
3546     /// The lookup found an overload set of literal operator templates,
3547     /// which expect the characters of the spelling of the literal token to be
3548     /// passed as a non-type template argument pack.
3549     LOLR_Template,
3550     /// The lookup found an overload set of literal operator templates,
3551     /// which expect the character type and characters of the spelling of the
3552     /// string literal token to be passed as template arguments.
3553     LOLR_StringTemplate
3554   };
3555 
3556   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3557                                                   CXXSpecialMember SM,
3558                                                   bool ConstArg,
3559                                                   bool VolatileArg,
3560                                                   bool RValueThis,
3561                                                   bool ConstThis,
3562                                                   bool VolatileThis);
3563 
3564   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3565   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3566       TypoRecoveryCallback;
3567 
3568 private:
3569   bool CppLookupName(LookupResult &R, Scope *S);
3570 
3571   struct TypoExprState {
3572     std::unique_ptr<TypoCorrectionConsumer> Consumer;
3573     TypoDiagnosticGenerator DiagHandler;
3574     TypoRecoveryCallback RecoveryHandler;
3575     TypoExprState();
3576     TypoExprState(TypoExprState &&other) noexcept;
3577     TypoExprState &operator=(TypoExprState &&other) noexcept;
3578   };
3579 
3580   /// The set of unhandled TypoExprs and their associated state.
3581   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3582 
3583   /// Creates a new TypoExpr AST node.
3584   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3585                               TypoDiagnosticGenerator TDG,
3586                               TypoRecoveryCallback TRC);
3587 
3588   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3589   //
3590   // The boolean value will be true to indicate that the namespace was loaded
3591   // from an AST/PCH file, or false otherwise.
3592   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3593 
3594   /// Whether we have already loaded known namespaces from an extenal
3595   /// source.
3596   bool LoadedExternalKnownNamespaces;
3597 
3598   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3599   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3600   /// should be skipped entirely.
3601   std::unique_ptr<TypoCorrectionConsumer>
3602   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3603                              Sema::LookupNameKind LookupKind, Scope *S,
3604                              CXXScopeSpec *SS,
3605                              CorrectionCandidateCallback &CCC,
3606                              DeclContext *MemberContext, bool EnteringContext,
3607                              const ObjCObjectPointerType *OPT,
3608                              bool ErrorRecovery);
3609 
3610 public:
3611   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3612 
3613   /// Clears the state of the given TypoExpr.
3614   void clearDelayedTypo(TypoExpr *TE);
3615 
3616   /// Look up a name, looking for a single declaration.  Return
3617   /// null if the results were absent, ambiguous, or overloaded.
3618   ///
3619   /// It is preferable to use the elaborated form and explicitly handle
3620   /// ambiguity and overloaded.
3621   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3622                               SourceLocation Loc,
3623                               LookupNameKind NameKind,
3624                               RedeclarationKind Redecl
3625                                 = NotForRedeclaration);
3626   bool LookupBuiltin(LookupResult &R);
3627   bool LookupName(LookupResult &R, Scope *S,
3628                   bool AllowBuiltinCreation = false);
3629   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3630                            bool InUnqualifiedLookup = false);
3631   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3632                            CXXScopeSpec &SS);
3633   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3634                         bool AllowBuiltinCreation = false,
3635                         bool EnteringContext = false);
3636   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3637                                    RedeclarationKind Redecl
3638                                      = NotForRedeclaration);
3639   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3640 
3641   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3642                                     QualType T1, QualType T2,
3643                                     UnresolvedSetImpl &Functions);
3644 
3645   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3646                                  SourceLocation GnuLabelLoc = SourceLocation());
3647 
3648   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3649   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3650   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3651                                                unsigned Quals);
3652   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3653                                          bool RValueThis, unsigned ThisQuals);
3654   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3655                                               unsigned Quals);
3656   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3657                                         bool RValueThis, unsigned ThisQuals);
3658   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3659 
3660   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3661   LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3662                                                     ArrayRef<QualType> ArgTys,
3663                                                     bool AllowRaw,
3664                                                     bool AllowTemplate,
3665                                                     bool AllowStringTemplate,
3666                                                     bool DiagnoseMissing);
3667   bool isKnownName(StringRef name);
3668 
3669   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
3670   enum class FunctionEmissionStatus {
3671     Emitted,
3672     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
3673     OMPDiscarded,      // Discarded due to OpenMP hostness
3674     TemplateDiscarded, // Discarded due to uninstantiated templates
3675     Unknown,
3676   };
3677   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
3678 
3679   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
3680   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
3681 
3682   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3683                                ArrayRef<Expr *> Args, ADLResult &Functions);
3684 
3685   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3686                           VisibleDeclConsumer &Consumer,
3687                           bool IncludeGlobalScope = true,
3688                           bool LoadExternal = true);
3689   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3690                           VisibleDeclConsumer &Consumer,
3691                           bool IncludeGlobalScope = true,
3692                           bool IncludeDependentBases = false,
3693                           bool LoadExternal = true);
3694 
3695   enum CorrectTypoKind {
3696     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
3697     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3698   };
3699 
3700   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3701                              Sema::LookupNameKind LookupKind,
3702                              Scope *S, CXXScopeSpec *SS,
3703                              CorrectionCandidateCallback &CCC,
3704                              CorrectTypoKind Mode,
3705                              DeclContext *MemberContext = nullptr,
3706                              bool EnteringContext = false,
3707                              const ObjCObjectPointerType *OPT = nullptr,
3708                              bool RecordFailure = true);
3709 
3710   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3711                                Sema::LookupNameKind LookupKind, Scope *S,
3712                                CXXScopeSpec *SS,
3713                                CorrectionCandidateCallback &CCC,
3714                                TypoDiagnosticGenerator TDG,
3715                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3716                                DeclContext *MemberContext = nullptr,
3717                                bool EnteringContext = false,
3718                                const ObjCObjectPointerType *OPT = nullptr);
3719 
3720   /// Process any TypoExprs in the given Expr and its children,
3721   /// generating diagnostics as appropriate and returning a new Expr if there
3722   /// were typos that were all successfully corrected and ExprError if one or
3723   /// more typos could not be corrected.
3724   ///
3725   /// \param E The Expr to check for TypoExprs.
3726   ///
3727   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3728   /// initializer.
3729   ///
3730   /// \param Filter A function applied to a newly rebuilt Expr to determine if
3731   /// it is an acceptable/usable result from a single combination of typo
3732   /// corrections. As long as the filter returns ExprError, different
3733   /// combinations of corrections will be tried until all are exhausted.
3734   ExprResult
3735   CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3736                             llvm::function_ref<ExprResult(Expr *)> Filter =
3737                                 [](Expr *E) -> ExprResult { return E; });
3738 
3739   ExprResult
3740   CorrectDelayedTyposInExpr(Expr *E,
3741                             llvm::function_ref<ExprResult(Expr *)> Filter) {
3742     return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3743   }
3744 
3745   ExprResult
3746   CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3747                             llvm::function_ref<ExprResult(Expr *)> Filter =
3748                                 [](Expr *E) -> ExprResult { return E; }) {
3749     return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3750   }
3751 
3752   ExprResult
3753   CorrectDelayedTyposInExpr(ExprResult ER,
3754                             llvm::function_ref<ExprResult(Expr *)> Filter) {
3755     return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3756   }
3757 
3758   void diagnoseTypo(const TypoCorrection &Correction,
3759                     const PartialDiagnostic &TypoDiag,
3760                     bool ErrorRecovery = true);
3761 
3762   void diagnoseTypo(const TypoCorrection &Correction,
3763                     const PartialDiagnostic &TypoDiag,
3764                     const PartialDiagnostic &PrevNote,
3765                     bool ErrorRecovery = true);
3766 
3767   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3768 
3769   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3770                                           ArrayRef<Expr *> Args,
3771                                    AssociatedNamespaceSet &AssociatedNamespaces,
3772                                    AssociatedClassSet &AssociatedClasses);
3773 
3774   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3775                             bool ConsiderLinkage, bool AllowInlineNamespace);
3776 
3777   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3778 
3779   void DiagnoseAmbiguousLookup(LookupResult &Result);
3780   //@}
3781 
3782   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3783                                           SourceLocation IdLoc,
3784                                           bool TypoCorrection = false);
3785   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3786                                  Scope *S, bool ForRedeclaration,
3787                                  SourceLocation Loc);
3788   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3789                                       Scope *S);
3790   void AddKnownFunctionAttributes(FunctionDecl *FD);
3791 
3792   // More parsing and symbol table subroutines.
3793 
3794   void ProcessPragmaWeak(Scope *S, Decl *D);
3795   // Decl attributes - this routine is the top level dispatcher.
3796   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3797   // Helper for delayed processing of attributes.
3798   void ProcessDeclAttributeDelayed(Decl *D,
3799                                    const ParsedAttributesView &AttrList);
3800   void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
3801                              bool IncludeCXX11Attributes = true);
3802   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3803                                    const ParsedAttributesView &AttrList);
3804 
3805   void checkUnusedDeclAttributes(Declarator &D);
3806 
3807   /// Determine if type T is a valid subject for a nonnull and similar
3808   /// attributes. By default, we look through references (the behavior used by
3809   /// nonnull), but if the second parameter is true, then we treat a reference
3810   /// type as valid.
3811   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3812 
3813   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
3814   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
3815                             const FunctionDecl *FD = nullptr);
3816   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
3817   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
3818   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
3819                                       StringRef &Str,
3820                                       SourceLocation *ArgLocation = nullptr);
3821   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3822   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3823   bool checkMSInheritanceAttrOnDefinition(
3824       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3825       MSInheritanceModel SemanticSpelling);
3826 
3827   void CheckAlignasUnderalignment(Decl *D);
3828 
3829   /// Adjust the calling convention of a method to be the ABI default if it
3830   /// wasn't specified explicitly.  This handles method types formed from
3831   /// function type typedefs and typename template arguments.
3832   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3833                               SourceLocation Loc);
3834 
3835   // Check if there is an explicit attribute, but only look through parens.
3836   // The intent is to look for an attribute on the current declarator, but not
3837   // one that came from a typedef.
3838   bool hasExplicitCallingConv(QualType T);
3839 
3840   /// Get the outermost AttributedType node that sets a calling convention.
3841   /// Valid types should not have multiple attributes with different CCs.
3842   const AttributedType *getCallingConvAttributedType(QualType T) const;
3843 
3844   /// Stmt attributes - this routine is the top level dispatcher.
3845   StmtResult ProcessStmtAttributes(Stmt *Stmt,
3846                                    const ParsedAttributesView &Attrs,
3847                                    SourceRange Range);
3848 
3849   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3850                                    ObjCMethodDecl *MethodDecl,
3851                                    bool IsProtocolMethodDecl);
3852 
3853   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3854                                    ObjCMethodDecl *Overridden,
3855                                    bool IsProtocolMethodDecl);
3856 
3857   /// WarnExactTypedMethods - This routine issues a warning if method
3858   /// implementation declaration matches exactly that of its declaration.
3859   void WarnExactTypedMethods(ObjCMethodDecl *Method,
3860                              ObjCMethodDecl *MethodDecl,
3861                              bool IsProtocolMethodDecl);
3862 
3863   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3864 
3865   /// CheckImplementationIvars - This routine checks if the instance variables
3866   /// listed in the implelementation match those listed in the interface.
3867   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3868                                 ObjCIvarDecl **Fields, unsigned nIvars,
3869                                 SourceLocation Loc);
3870 
3871   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3872   /// remains unimplemented in the class or category \@implementation.
3873   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3874                                  ObjCContainerDecl* IDecl,
3875                                  bool IncompleteImpl = false);
3876 
3877   /// DiagnoseUnimplementedProperties - This routine warns on those properties
3878   /// which must be implemented by this implementation.
3879   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3880                                        ObjCContainerDecl *CDecl,
3881                                        bool SynthesizeProperties);
3882 
3883   /// Diagnose any null-resettable synthesized setters.
3884   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3885 
3886   /// DefaultSynthesizeProperties - This routine default synthesizes all
3887   /// properties which must be synthesized in the class's \@implementation.
3888   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3889                                    ObjCInterfaceDecl *IDecl,
3890                                    SourceLocation AtEnd);
3891   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3892 
3893   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3894   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3895   /// declared in class 'IFace'.
3896   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3897                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3898 
3899   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3900   /// backs the property is not used in the property's accessor.
3901   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3902                                            const ObjCImplementationDecl *ImplD);
3903 
3904   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3905   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3906   /// It also returns ivar's property on success.
3907   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3908                                                const ObjCPropertyDecl *&PDecl) const;
3909 
3910   /// Called by ActOnProperty to handle \@property declarations in
3911   /// class extensions.
3912   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3913                       SourceLocation AtLoc,
3914                       SourceLocation LParenLoc,
3915                       FieldDeclarator &FD,
3916                       Selector GetterSel,
3917                       SourceLocation GetterNameLoc,
3918                       Selector SetterSel,
3919                       SourceLocation SetterNameLoc,
3920                       const bool isReadWrite,
3921                       unsigned &Attributes,
3922                       const unsigned AttributesAsWritten,
3923                       QualType T,
3924                       TypeSourceInfo *TSI,
3925                       tok::ObjCKeywordKind MethodImplKind);
3926 
3927   /// Called by ActOnProperty and HandlePropertyInClassExtension to
3928   /// handle creating the ObjcPropertyDecl for a category or \@interface.
3929   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3930                                        ObjCContainerDecl *CDecl,
3931                                        SourceLocation AtLoc,
3932                                        SourceLocation LParenLoc,
3933                                        FieldDeclarator &FD,
3934                                        Selector GetterSel,
3935                                        SourceLocation GetterNameLoc,
3936                                        Selector SetterSel,
3937                                        SourceLocation SetterNameLoc,
3938                                        const bool isReadWrite,
3939                                        const unsigned Attributes,
3940                                        const unsigned AttributesAsWritten,
3941                                        QualType T,
3942                                        TypeSourceInfo *TSI,
3943                                        tok::ObjCKeywordKind MethodImplKind,
3944                                        DeclContext *lexicalDC = nullptr);
3945 
3946   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3947   /// warning) when atomic property has one but not the other user-declared
3948   /// setter or getter.
3949   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3950                                        ObjCInterfaceDecl* IDecl);
3951 
3952   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3953 
3954   void DiagnoseMissingDesignatedInitOverrides(
3955                                           const ObjCImplementationDecl *ImplD,
3956                                           const ObjCInterfaceDecl *IFD);
3957 
3958   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3959 
3960   enum MethodMatchStrategy {
3961     MMS_loose,
3962     MMS_strict
3963   };
3964 
3965   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3966   /// true, or false, accordingly.
3967   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3968                                   const ObjCMethodDecl *PrevMethod,
3969                                   MethodMatchStrategy strategy = MMS_strict);
3970 
3971   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3972   /// or protocol against those declared in their implementations.
3973   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3974                                   const SelectorSet &ClsMap,
3975                                   SelectorSet &InsMapSeen,
3976                                   SelectorSet &ClsMapSeen,
3977                                   ObjCImplDecl* IMPDecl,
3978                                   ObjCContainerDecl* IDecl,
3979                                   bool &IncompleteImpl,
3980                                   bool ImmediateClass,
3981                                   bool WarnCategoryMethodImpl=false);
3982 
3983   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3984   /// category matches with those implemented in its primary class and
3985   /// warns each time an exact match is found.
3986   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3987 
3988   /// Add the given method to the list of globally-known methods.
3989   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3990 
3991   /// Returns default addr space for method qualifiers.
3992   LangAS getDefaultCXXMethodAddrSpace() const;
3993 
3994 private:
3995   /// AddMethodToGlobalPool - Add an instance or factory method to the global
3996   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3997   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3998 
3999   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4000   /// optionally warns if there are multiple signatures.
4001   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4002                                            bool receiverIdOrClass,
4003                                            bool instance);
4004 
4005 public:
4006   /// - Returns instance or factory methods in global method pool for
4007   /// given selector. It checks the desired kind first, if none is found, and
4008   /// parameter checkTheOther is set, it then checks the other kind. If no such
4009   /// method or only one method is found, function returns false; otherwise, it
4010   /// returns true.
4011   bool
4012   CollectMultipleMethodsInGlobalPool(Selector Sel,
4013                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4014                                      bool InstanceFirst, bool CheckTheOther,
4015                                      const ObjCObjectType *TypeBound = nullptr);
4016 
4017   bool
4018   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4019                                  SourceRange R, bool receiverIdOrClass,
4020                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4021 
4022   void
4023   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4024                                      Selector Sel, SourceRange R,
4025                                      bool receiverIdOrClass);
4026 
4027 private:
4028   /// - Returns a selector which best matches given argument list or
4029   /// nullptr if none could be found
4030   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4031                                    bool IsInstance,
4032                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4033 
4034 
4035   /// Record the typo correction failure and return an empty correction.
4036   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4037                                   bool RecordFailure = true) {
4038     if (RecordFailure)
4039       TypoCorrectionFailures[Typo].insert(TypoLoc);
4040     return TypoCorrection();
4041   }
4042 
4043 public:
4044   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4045   /// unit are added to a global pool. This allows us to efficiently associate
4046   /// a selector with a method declaraation for purposes of typechecking
4047   /// messages sent to "id" (where the class of the object is unknown).
4048   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4049     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4050   }
4051 
4052   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4053   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4054     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4055   }
4056 
4057   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4058   /// pool.
4059   void AddAnyMethodToGlobalPool(Decl *D);
4060 
4061   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4062   /// there are multiple signatures.
4063   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4064                                                    bool receiverIdOrClass=false) {
4065     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4066                                     /*instance*/true);
4067   }
4068 
4069   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4070   /// there are multiple signatures.
4071   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4072                                                   bool receiverIdOrClass=false) {
4073     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4074                                     /*instance*/false);
4075   }
4076 
4077   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4078                               QualType ObjectType=QualType());
4079   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4080   /// implementation.
4081   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4082 
4083   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4084   /// initialization.
4085   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4086                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4087 
4088   //===--------------------------------------------------------------------===//
4089   // Statement Parsing Callbacks: SemaStmt.cpp.
4090 public:
4091   class FullExprArg {
4092   public:
4093     FullExprArg() : E(nullptr) { }
4094     FullExprArg(Sema &actions) : E(nullptr) { }
4095 
4096     ExprResult release() {
4097       return E;
4098     }
4099 
4100     Expr *get() const { return E; }
4101 
4102     Expr *operator->() {
4103       return E;
4104     }
4105 
4106   private:
4107     // FIXME: No need to make the entire Sema class a friend when it's just
4108     // Sema::MakeFullExpr that needs access to the constructor below.
4109     friend class Sema;
4110 
4111     explicit FullExprArg(Expr *expr) : E(expr) {}
4112 
4113     Expr *E;
4114   };
4115 
4116   FullExprArg MakeFullExpr(Expr *Arg) {
4117     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4118   }
4119   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4120     return FullExprArg(
4121         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4122   }
4123   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4124     ExprResult FE =
4125         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4126                             /*DiscardedValue*/ true);
4127     return FullExprArg(FE.get());
4128   }
4129 
4130   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4131   StmtResult ActOnExprStmtError();
4132 
4133   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4134                            bool HasLeadingEmptyMacro = false);
4135 
4136   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4137   void ActOnFinishOfCompoundStmt();
4138   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4139                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4140 
4141   /// A RAII object to enter scope of a compound statement.
4142   class CompoundScopeRAII {
4143   public:
4144     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4145       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4146     }
4147 
4148     ~CompoundScopeRAII() {
4149       S.ActOnFinishOfCompoundStmt();
4150     }
4151 
4152   private:
4153     Sema &S;
4154   };
4155 
4156   /// An RAII helper that pops function a function scope on exit.
4157   struct FunctionScopeRAII {
4158     Sema &S;
4159     bool Active;
4160     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4161     ~FunctionScopeRAII() {
4162       if (Active)
4163         S.PopFunctionScopeInfo();
4164     }
4165     void disable() { Active = false; }
4166   };
4167 
4168   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4169                                    SourceLocation StartLoc,
4170                                    SourceLocation EndLoc);
4171   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4172   StmtResult ActOnForEachLValueExpr(Expr *E);
4173   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4174   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4175                            SourceLocation DotDotDotLoc, ExprResult RHS,
4176                            SourceLocation ColonLoc);
4177   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4178 
4179   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4180                                       SourceLocation ColonLoc,
4181                                       Stmt *SubStmt, Scope *CurScope);
4182   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4183                             SourceLocation ColonLoc, Stmt *SubStmt);
4184 
4185   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4186                                  ArrayRef<const Attr*> Attrs,
4187                                  Stmt *SubStmt);
4188 
4189   class ConditionResult;
4190   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4191                          Stmt *InitStmt,
4192                          ConditionResult Cond, Stmt *ThenVal,
4193                          SourceLocation ElseLoc, Stmt *ElseVal);
4194   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4195                          Stmt *InitStmt,
4196                          ConditionResult Cond, Stmt *ThenVal,
4197                          SourceLocation ElseLoc, Stmt *ElseVal);
4198   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4199                                     Stmt *InitStmt,
4200                                     ConditionResult Cond);
4201   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4202                                            Stmt *Switch, Stmt *Body);
4203   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
4204                             Stmt *Body);
4205   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4206                          SourceLocation WhileLoc, SourceLocation CondLParen,
4207                          Expr *Cond, SourceLocation CondRParen);
4208 
4209   StmtResult ActOnForStmt(SourceLocation ForLoc,
4210                           SourceLocation LParenLoc,
4211                           Stmt *First,
4212                           ConditionResult Second,
4213                           FullExprArg Third,
4214                           SourceLocation RParenLoc,
4215                           Stmt *Body);
4216   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4217                                            Expr *collection);
4218   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4219                                         Stmt *First, Expr *collection,
4220                                         SourceLocation RParenLoc);
4221   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4222 
4223   enum BuildForRangeKind {
4224     /// Initial building of a for-range statement.
4225     BFRK_Build,
4226     /// Instantiation or recovery rebuild of a for-range statement. Don't
4227     /// attempt any typo-correction.
4228     BFRK_Rebuild,
4229     /// Determining whether a for-range statement could be built. Avoid any
4230     /// unnecessary or irreversible actions.
4231     BFRK_Check
4232   };
4233 
4234   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4235                                   SourceLocation CoawaitLoc,
4236                                   Stmt *InitStmt,
4237                                   Stmt *LoopVar,
4238                                   SourceLocation ColonLoc, Expr *Collection,
4239                                   SourceLocation RParenLoc,
4240                                   BuildForRangeKind Kind);
4241   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4242                                   SourceLocation CoawaitLoc,
4243                                   Stmt *InitStmt,
4244                                   SourceLocation ColonLoc,
4245                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4246                                   Expr *Cond, Expr *Inc,
4247                                   Stmt *LoopVarDecl,
4248                                   SourceLocation RParenLoc,
4249                                   BuildForRangeKind Kind);
4250   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4251 
4252   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4253                            SourceLocation LabelLoc,
4254                            LabelDecl *TheDecl);
4255   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4256                                    SourceLocation StarLoc,
4257                                    Expr *DestExp);
4258   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4259   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4260 
4261   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4262                                 CapturedRegionKind Kind, unsigned NumParams);
4263   typedef std::pair<StringRef, QualType> CapturedParamNameType;
4264   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4265                                 CapturedRegionKind Kind,
4266                                 ArrayRef<CapturedParamNameType> Params,
4267                                 unsigned OpenMPCaptureLevel = 0);
4268   StmtResult ActOnCapturedRegionEnd(Stmt *S);
4269   void ActOnCapturedRegionError();
4270   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4271                                            SourceLocation Loc,
4272                                            unsigned NumParams);
4273 
4274   enum CopyElisionSemanticsKind {
4275     CES_Strict = 0,
4276     CES_AllowParameters = 1,
4277     CES_AllowDifferentTypes = 2,
4278     CES_AllowExceptionVariables = 4,
4279     CES_FormerDefault = (CES_AllowParameters),
4280     CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4281     CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4282                          CES_AllowExceptionVariables),
4283   };
4284 
4285   VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4286                                    CopyElisionSemanticsKind CESK);
4287   bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4288                               CopyElisionSemanticsKind CESK);
4289 
4290   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4291                              Scope *CurScope);
4292   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4293   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4294 
4295   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4296                              bool IsVolatile, unsigned NumOutputs,
4297                              unsigned NumInputs, IdentifierInfo **Names,
4298                              MultiExprArg Constraints, MultiExprArg Exprs,
4299                              Expr *AsmString, MultiExprArg Clobbers,
4300                              unsigned NumLabels,
4301                              SourceLocation RParenLoc);
4302 
4303   void FillInlineAsmIdentifierInfo(Expr *Res,
4304                                    llvm::InlineAsmIdentifierInfo &Info);
4305   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4306                                        SourceLocation TemplateKWLoc,
4307                                        UnqualifiedId &Id,
4308                                        bool IsUnevaluatedContext);
4309   bool LookupInlineAsmField(StringRef Base, StringRef Member,
4310                             unsigned &Offset, SourceLocation AsmLoc);
4311   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4312                                          SourceLocation AsmLoc);
4313   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4314                             ArrayRef<Token> AsmToks,
4315                             StringRef AsmString,
4316                             unsigned NumOutputs, unsigned NumInputs,
4317                             ArrayRef<StringRef> Constraints,
4318                             ArrayRef<StringRef> Clobbers,
4319                             ArrayRef<Expr*> Exprs,
4320                             SourceLocation EndLoc);
4321   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4322                                    SourceLocation Location,
4323                                    bool AlwaysCreate);
4324 
4325   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4326                                   SourceLocation StartLoc,
4327                                   SourceLocation IdLoc, IdentifierInfo *Id,
4328                                   bool Invalid = false);
4329 
4330   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4331 
4332   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4333                                   Decl *Parm, Stmt *Body);
4334 
4335   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4336 
4337   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4338                                 MultiStmtArg Catch, Stmt *Finally);
4339 
4340   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4341   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4342                                   Scope *CurScope);
4343   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4344                                             Expr *operand);
4345   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4346                                          Expr *SynchExpr,
4347                                          Stmt *SynchBody);
4348 
4349   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4350 
4351   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4352                                      SourceLocation StartLoc,
4353                                      SourceLocation IdLoc,
4354                                      IdentifierInfo *Id);
4355 
4356   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4357 
4358   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4359                                 Decl *ExDecl, Stmt *HandlerBlock);
4360   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4361                               ArrayRef<Stmt *> Handlers);
4362 
4363   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4364                               SourceLocation TryLoc, Stmt *TryBlock,
4365                               Stmt *Handler);
4366   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4367                                  Expr *FilterExpr,
4368                                  Stmt *Block);
4369   void ActOnStartSEHFinallyBlock();
4370   void ActOnAbortSEHFinallyBlock();
4371   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4372   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4373 
4374   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4375 
4376   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4377 
4378   /// If it's a file scoped decl that must warn if not used, keep track
4379   /// of it.
4380   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4381 
4382   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4383   /// whose result is unused, warn.
4384   void DiagnoseUnusedExprResult(const Stmt *S);
4385   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4386   void DiagnoseUnusedDecl(const NamedDecl *ND);
4387 
4388   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4389   /// statement as a \p Body, and it is located on the same line.
4390   ///
4391   /// This helps prevent bugs due to typos, such as:
4392   ///     if (condition);
4393   ///       do_stuff();
4394   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4395                              const Stmt *Body,
4396                              unsigned DiagID);
4397 
4398   /// Warn if a for/while loop statement \p S, which is followed by
4399   /// \p PossibleBody, has a suspicious null statement as a body.
4400   void DiagnoseEmptyLoopBody(const Stmt *S,
4401                              const Stmt *PossibleBody);
4402 
4403   /// Warn if a value is moved to itself.
4404   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4405                         SourceLocation OpLoc);
4406 
4407   /// Warn if we're implicitly casting from a _Nullable pointer type to a
4408   /// _Nonnull one.
4409   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4410                                            SourceLocation Loc);
4411 
4412   /// Warn when implicitly casting 0 to nullptr.
4413   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4414 
4415   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4416     return DelayedDiagnostics.push(pool);
4417   }
4418   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4419 
4420   typedef ProcessingContextState ParsingClassState;
4421   ParsingClassState PushParsingClass() {
4422     ParsingClassDepth++;
4423     return DelayedDiagnostics.pushUndelayed();
4424   }
4425   void PopParsingClass(ParsingClassState state) {
4426     ParsingClassDepth--;
4427     DelayedDiagnostics.popUndelayed(state);
4428   }
4429 
4430   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4431 
4432   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4433                                   const ObjCInterfaceDecl *UnknownObjCClass,
4434                                   bool ObjCPropertyAccess,
4435                                   bool AvoidPartialAvailabilityChecks = false,
4436                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
4437 
4438   bool makeUnavailableInSystemHeader(SourceLocation loc,
4439                                      UnavailableAttr::ImplicitReason reason);
4440 
4441   /// Issue any -Wunguarded-availability warnings in \c FD
4442   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4443 
4444   //===--------------------------------------------------------------------===//
4445   // Expression Parsing Callbacks: SemaExpr.cpp.
4446 
4447   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4448   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4449                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4450                          bool ObjCPropertyAccess = false,
4451                          bool AvoidPartialAvailabilityChecks = false,
4452                          ObjCInterfaceDecl *ClassReciever = nullptr);
4453   void NoteDeletedFunction(FunctionDecl *FD);
4454   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4455   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4456                                         ObjCMethodDecl *Getter,
4457                                         SourceLocation Loc);
4458   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4459                              ArrayRef<Expr *> Args);
4460 
4461   void PushExpressionEvaluationContext(
4462       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4463       ExpressionEvaluationContextRecord::ExpressionKind Type =
4464           ExpressionEvaluationContextRecord::EK_Other);
4465   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4466   void PushExpressionEvaluationContext(
4467       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4468       ExpressionEvaluationContextRecord::ExpressionKind Type =
4469           ExpressionEvaluationContextRecord::EK_Other);
4470   void PopExpressionEvaluationContext();
4471 
4472   void DiscardCleanupsInEvaluationContext();
4473 
4474   ExprResult TransformToPotentiallyEvaluated(Expr *E);
4475   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4476 
4477   ExprResult CheckUnevaluatedOperand(Expr *E);
4478   void CheckUnusedVolatileAssignment(Expr *E);
4479 
4480   ExprResult ActOnConstantExpression(ExprResult Res);
4481 
4482   // Functions for marking a declaration referenced.  These functions also
4483   // contain the relevant logic for marking if a reference to a function or
4484   // variable is an odr-use (in the C++11 sense).  There are separate variants
4485   // for expressions referring to a decl; these exist because odr-use marking
4486   // needs to be delayed for some constant variables when we build one of the
4487   // named expressions.
4488   //
4489   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4490   // should usually be true. This only needs to be set to false if the lack of
4491   // odr-use cannot be determined from the current context (for instance,
4492   // because the name denotes a virtual function and was written without an
4493   // explicit nested-name-specifier).
4494   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4495   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4496                               bool MightBeOdrUse = true);
4497   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4498   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4499   void MarkMemberReferenced(MemberExpr *E);
4500   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4501   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4502                                          unsigned CapturingScopeIndex);
4503 
4504   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4505   void CleanupVarDeclMarking();
4506 
4507   enum TryCaptureKind {
4508     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4509   };
4510 
4511   /// Try to capture the given variable.
4512   ///
4513   /// \param Var The variable to capture.
4514   ///
4515   /// \param Loc The location at which the capture occurs.
4516   ///
4517   /// \param Kind The kind of capture, which may be implicit (for either a
4518   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4519   ///
4520   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4521   /// an explicit lambda capture.
4522   ///
4523   /// \param BuildAndDiagnose Whether we are actually supposed to add the
4524   /// captures or diagnose errors. If false, this routine merely check whether
4525   /// the capture can occur without performing the capture itself or complaining
4526   /// if the variable cannot be captured.
4527   ///
4528   /// \param CaptureType Will be set to the type of the field used to capture
4529   /// this variable in the innermost block or lambda. Only valid when the
4530   /// variable can be captured.
4531   ///
4532   /// \param DeclRefType Will be set to the type of a reference to the capture
4533   /// from within the current scope. Only valid when the variable can be
4534   /// captured.
4535   ///
4536   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4537   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4538   /// This is useful when enclosing lambdas must speculatively capture
4539   /// variables that may or may not be used in certain specializations of
4540   /// a nested generic lambda.
4541   ///
4542   /// \returns true if an error occurred (i.e., the variable cannot be
4543   /// captured) and false if the capture succeeded.
4544   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4545                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4546                           QualType &CaptureType,
4547                           QualType &DeclRefType,
4548                           const unsigned *const FunctionScopeIndexToStopAt);
4549 
4550   /// Try to capture the given variable.
4551   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4552                           TryCaptureKind Kind = TryCapture_Implicit,
4553                           SourceLocation EllipsisLoc = SourceLocation());
4554 
4555   /// Checks if the variable must be captured.
4556   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4557 
4558   /// Given a variable, determine the type that a reference to that
4559   /// variable will have in the given scope.
4560   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4561 
4562   /// Mark all of the declarations referenced within a particular AST node as
4563   /// referenced. Used when template instantiation instantiates a non-dependent
4564   /// type -- entities referenced by the type are now referenced.
4565   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4566   void MarkDeclarationsReferencedInExpr(Expr *E,
4567                                         bool SkipLocalVariables = false);
4568 
4569   /// Try to recover by turning the given expression into a
4570   /// call.  Returns true if recovery was attempted or an error was
4571   /// emitted; this may also leave the ExprResult invalid.
4572   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4573                             bool ForceComplain = false,
4574                             bool (*IsPlausibleResult)(QualType) = nullptr);
4575 
4576   /// Figure out if an expression could be turned into a call.
4577   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4578                      UnresolvedSetImpl &NonTemplateOverloads);
4579 
4580   /// Conditionally issue a diagnostic based on the current
4581   /// evaluation context.
4582   ///
4583   /// \param Statement If Statement is non-null, delay reporting the
4584   /// diagnostic until the function body is parsed, and then do a basic
4585   /// reachability analysis to determine if the statement is reachable.
4586   /// If it is unreachable, the diagnostic will not be emitted.
4587   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4588                            const PartialDiagnostic &PD);
4589   /// Similar, but diagnostic is only produced if all the specified statements
4590   /// are reachable.
4591   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4592                            const PartialDiagnostic &PD);
4593 
4594   // Primary Expressions.
4595   SourceRange getExprRange(Expr *E) const;
4596 
4597   ExprResult ActOnIdExpression(
4598       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4599       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4600       CorrectionCandidateCallback *CCC = nullptr,
4601       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4602 
4603   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4604                               TemplateArgumentListInfo &Buffer,
4605                               DeclarationNameInfo &NameInfo,
4606                               const TemplateArgumentListInfo *&TemplateArgs);
4607 
4608   bool
4609   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4610                       CorrectionCandidateCallback &CCC,
4611                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4612                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4613 
4614   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4615                                     IdentifierInfo *II);
4616   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4617 
4618   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4619                                 IdentifierInfo *II,
4620                                 bool AllowBuiltinCreation=false);
4621 
4622   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4623                                         SourceLocation TemplateKWLoc,
4624                                         const DeclarationNameInfo &NameInfo,
4625                                         bool isAddressOfOperand,
4626                                 const TemplateArgumentListInfo *TemplateArgs);
4627 
4628   /// If \p D cannot be odr-used in the current expression evaluation context,
4629   /// return a reason explaining why. Otherwise, return NOUR_None.
4630   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4631 
4632   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4633                                 SourceLocation Loc,
4634                                 const CXXScopeSpec *SS = nullptr);
4635   DeclRefExpr *
4636   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4637                    const DeclarationNameInfo &NameInfo,
4638                    const CXXScopeSpec *SS = nullptr,
4639                    NamedDecl *FoundD = nullptr,
4640                    SourceLocation TemplateKWLoc = SourceLocation(),
4641                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4642   DeclRefExpr *
4643   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4644                    const DeclarationNameInfo &NameInfo,
4645                    NestedNameSpecifierLoc NNS,
4646                    NamedDecl *FoundD = nullptr,
4647                    SourceLocation TemplateKWLoc = SourceLocation(),
4648                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4649 
4650   ExprResult
4651   BuildAnonymousStructUnionMemberReference(
4652       const CXXScopeSpec &SS,
4653       SourceLocation nameLoc,
4654       IndirectFieldDecl *indirectField,
4655       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4656       Expr *baseObjectExpr = nullptr,
4657       SourceLocation opLoc = SourceLocation());
4658 
4659   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4660                                              SourceLocation TemplateKWLoc,
4661                                              LookupResult &R,
4662                                 const TemplateArgumentListInfo *TemplateArgs,
4663                                              const Scope *S);
4664   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4665                                      SourceLocation TemplateKWLoc,
4666                                      LookupResult &R,
4667                                 const TemplateArgumentListInfo *TemplateArgs,
4668                                      bool IsDefiniteInstance,
4669                                      const Scope *S);
4670   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4671                                   const LookupResult &R,
4672                                   bool HasTrailingLParen);
4673 
4674   ExprResult
4675   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4676                                     const DeclarationNameInfo &NameInfo,
4677                                     bool IsAddressOfOperand, const Scope *S,
4678                                     TypeSourceInfo **RecoveryTSI = nullptr);
4679 
4680   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4681                                        SourceLocation TemplateKWLoc,
4682                                 const DeclarationNameInfo &NameInfo,
4683                                 const TemplateArgumentListInfo *TemplateArgs);
4684 
4685   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4686                                       LookupResult &R,
4687                                       bool NeedsADL,
4688                                       bool AcceptInvalidDecl = false);
4689   ExprResult BuildDeclarationNameExpr(
4690       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4691       NamedDecl *FoundD = nullptr,
4692       const TemplateArgumentListInfo *TemplateArgs = nullptr,
4693       bool AcceptInvalidDecl = false);
4694 
4695   ExprResult BuildLiteralOperatorCall(LookupResult &R,
4696                       DeclarationNameInfo &SuffixInfo,
4697                       ArrayRef<Expr *> Args,
4698                       SourceLocation LitEndLoc,
4699                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4700 
4701   ExprResult BuildPredefinedExpr(SourceLocation Loc,
4702                                  PredefinedExpr::IdentKind IK);
4703   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4704   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4705 
4706   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4707 
4708   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4709   ExprResult ActOnCharacterConstant(const Token &Tok,
4710                                     Scope *UDLScope = nullptr);
4711   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4712   ExprResult ActOnParenListExpr(SourceLocation L,
4713                                 SourceLocation R,
4714                                 MultiExprArg Val);
4715 
4716   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4717   /// fragments (e.g. "foo" "bar" L"baz").
4718   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4719                                 Scope *UDLScope = nullptr);
4720 
4721   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4722                                        SourceLocation DefaultLoc,
4723                                        SourceLocation RParenLoc,
4724                                        Expr *ControllingExpr,
4725                                        ArrayRef<ParsedType> ArgTypes,
4726                                        ArrayRef<Expr *> ArgExprs);
4727   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4728                                         SourceLocation DefaultLoc,
4729                                         SourceLocation RParenLoc,
4730                                         Expr *ControllingExpr,
4731                                         ArrayRef<TypeSourceInfo *> Types,
4732                                         ArrayRef<Expr *> Exprs);
4733 
4734   // Binary/Unary Operators.  'Tok' is the token for the operator.
4735   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4736                                   Expr *InputExpr);
4737   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4738                           UnaryOperatorKind Opc, Expr *Input);
4739   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4740                           tok::TokenKind Op, Expr *Input);
4741 
4742   bool isQualifiedMemberAccess(Expr *E);
4743   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4744 
4745   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4746                                             SourceLocation OpLoc,
4747                                             UnaryExprOrTypeTrait ExprKind,
4748                                             SourceRange R);
4749   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4750                                             UnaryExprOrTypeTrait ExprKind);
4751   ExprResult
4752     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4753                                   UnaryExprOrTypeTrait ExprKind,
4754                                   bool IsType, void *TyOrEx,
4755                                   SourceRange ArgRange);
4756 
4757   ExprResult CheckPlaceholderExpr(Expr *E);
4758   bool CheckVecStepExpr(Expr *E);
4759 
4760   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4761   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4762                                         SourceRange ExprRange,
4763                                         UnaryExprOrTypeTrait ExprKind);
4764   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4765                                           SourceLocation OpLoc,
4766                                           IdentifierInfo &Name,
4767                                           SourceLocation NameLoc,
4768                                           SourceLocation RParenLoc);
4769   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4770                                  tok::TokenKind Kind, Expr *Input);
4771 
4772   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4773                                      Expr *Idx, SourceLocation RLoc);
4774   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4775                                              Expr *Idx, SourceLocation RLoc);
4776   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4777                                       Expr *LowerBound, SourceLocation ColonLoc,
4778                                       Expr *Length, SourceLocation RBLoc);
4779 
4780   // This struct is for use by ActOnMemberAccess to allow
4781   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4782   // changing the access operator from a '.' to a '->' (to see if that is the
4783   // change needed to fix an error about an unknown member, e.g. when the class
4784   // defines a custom operator->).
4785   struct ActOnMemberAccessExtraArgs {
4786     Scope *S;
4787     UnqualifiedId &Id;
4788     Decl *ObjCImpDecl;
4789   };
4790 
4791   ExprResult BuildMemberReferenceExpr(
4792       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4793       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4794       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4795       const TemplateArgumentListInfo *TemplateArgs,
4796       const Scope *S,
4797       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4798 
4799   ExprResult
4800   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4801                            bool IsArrow, const CXXScopeSpec &SS,
4802                            SourceLocation TemplateKWLoc,
4803                            NamedDecl *FirstQualifierInScope, LookupResult &R,
4804                            const TemplateArgumentListInfo *TemplateArgs,
4805                            const Scope *S,
4806                            bool SuppressQualifierCheck = false,
4807                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4808 
4809   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4810                                      SourceLocation OpLoc,
4811                                      const CXXScopeSpec &SS, FieldDecl *Field,
4812                                      DeclAccessPair FoundDecl,
4813                                      const DeclarationNameInfo &MemberNameInfo);
4814 
4815   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4816 
4817   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4818                                      const CXXScopeSpec &SS,
4819                                      const LookupResult &R);
4820 
4821   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4822                                       bool IsArrow, SourceLocation OpLoc,
4823                                       const CXXScopeSpec &SS,
4824                                       SourceLocation TemplateKWLoc,
4825                                       NamedDecl *FirstQualifierInScope,
4826                                const DeclarationNameInfo &NameInfo,
4827                                const TemplateArgumentListInfo *TemplateArgs);
4828 
4829   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4830                                    SourceLocation OpLoc,
4831                                    tok::TokenKind OpKind,
4832                                    CXXScopeSpec &SS,
4833                                    SourceLocation TemplateKWLoc,
4834                                    UnqualifiedId &Member,
4835                                    Decl *ObjCImpDecl);
4836 
4837   MemberExpr *
4838   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4839                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
4840                   ValueDecl *Member, DeclAccessPair FoundDecl,
4841                   bool HadMultipleCandidates,
4842                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4843                   ExprValueKind VK, ExprObjectKind OK,
4844                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
4845   MemberExpr *
4846   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
4847                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
4848                   ValueDecl *Member, DeclAccessPair FoundDecl,
4849                   bool HadMultipleCandidates,
4850                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
4851                   ExprValueKind VK, ExprObjectKind OK,
4852                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
4853 
4854   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4855   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4856                                FunctionDecl *FDecl,
4857                                const FunctionProtoType *Proto,
4858                                ArrayRef<Expr *> Args,
4859                                SourceLocation RParenLoc,
4860                                bool ExecConfig = false);
4861   void CheckStaticArrayArgument(SourceLocation CallLoc,
4862                                 ParmVarDecl *Param,
4863                                 const Expr *ArgExpr);
4864 
4865   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4866   /// This provides the location of the left/right parens and a list of comma
4867   /// locations.
4868   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4869                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
4870                            Expr *ExecConfig = nullptr);
4871   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4872                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
4873                            Expr *ExecConfig = nullptr,
4874                            bool IsExecConfig = false);
4875   enum class AtomicArgumentOrder { API, AST };
4876   ExprResult
4877   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4878                   SourceLocation RParenLoc, MultiExprArg Args,
4879                   AtomicExpr::AtomicOp Op,
4880                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
4881   ExprResult
4882   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
4883                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
4884                         Expr *Config = nullptr, bool IsExecConfig = false,
4885                         ADLCallKind UsesADL = ADLCallKind::NotADL);
4886 
4887   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4888                                      MultiExprArg ExecConfig,
4889                                      SourceLocation GGGLoc);
4890 
4891   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4892                            Declarator &D, ParsedType &Ty,
4893                            SourceLocation RParenLoc, Expr *CastExpr);
4894   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4895                                  TypeSourceInfo *Ty,
4896                                  SourceLocation RParenLoc,
4897                                  Expr *Op);
4898   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4899 
4900   /// Build an altivec or OpenCL literal.
4901   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4902                                 SourceLocation RParenLoc, Expr *E,
4903                                 TypeSourceInfo *TInfo);
4904 
4905   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4906 
4907   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4908                                   ParsedType Ty,
4909                                   SourceLocation RParenLoc,
4910                                   Expr *InitExpr);
4911 
4912   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4913                                       TypeSourceInfo *TInfo,
4914                                       SourceLocation RParenLoc,
4915                                       Expr *LiteralExpr);
4916 
4917   ExprResult ActOnInitList(SourceLocation LBraceLoc,
4918                            MultiExprArg InitArgList,
4919                            SourceLocation RBraceLoc);
4920 
4921   ExprResult BuildInitList(SourceLocation LBraceLoc,
4922                            MultiExprArg InitArgList,
4923                            SourceLocation RBraceLoc);
4924 
4925   ExprResult ActOnDesignatedInitializer(Designation &Desig,
4926                                         SourceLocation EqualOrColonLoc,
4927                                         bool GNUSyntax,
4928                                         ExprResult Init);
4929 
4930 private:
4931   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4932 
4933 public:
4934   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4935                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4936   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4937                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4938   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4939                                 Expr *LHSExpr, Expr *RHSExpr);
4940 
4941   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4942 
4943   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4944   /// in the case of a the GNU conditional expr extension.
4945   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4946                                 SourceLocation ColonLoc,
4947                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4948 
4949   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4950   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4951                             LabelDecl *TheDecl);
4952 
4953   void ActOnStartStmtExpr();
4954   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
4955                            SourceLocation RPLoc);
4956   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4957                            SourceLocation RPLoc, unsigned TemplateDepth);
4958   // Handle the final expression in a statement expression.
4959   ExprResult ActOnStmtExprResult(ExprResult E);
4960   void ActOnStmtExprError();
4961 
4962   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4963   struct OffsetOfComponent {
4964     SourceLocation LocStart, LocEnd;
4965     bool isBrackets;  // true if [expr], false if .ident
4966     union {
4967       IdentifierInfo *IdentInfo;
4968       Expr *E;
4969     } U;
4970   };
4971 
4972   /// __builtin_offsetof(type, a.b[123][456].c)
4973   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4974                                   TypeSourceInfo *TInfo,
4975                                   ArrayRef<OffsetOfComponent> Components,
4976                                   SourceLocation RParenLoc);
4977   ExprResult ActOnBuiltinOffsetOf(Scope *S,
4978                                   SourceLocation BuiltinLoc,
4979                                   SourceLocation TypeLoc,
4980                                   ParsedType ParsedArgTy,
4981                                   ArrayRef<OffsetOfComponent> Components,
4982                                   SourceLocation RParenLoc);
4983 
4984   // __builtin_choose_expr(constExpr, expr1, expr2)
4985   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4986                              Expr *CondExpr, Expr *LHSExpr,
4987                              Expr *RHSExpr, SourceLocation RPLoc);
4988 
4989   // __builtin_va_arg(expr, type)
4990   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4991                         SourceLocation RPLoc);
4992   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4993                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
4994 
4995   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
4996   // __builtin_COLUMN()
4997   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
4998                                 SourceLocation BuiltinLoc,
4999                                 SourceLocation RPLoc);
5000 
5001   // Build a potentially resolved SourceLocExpr.
5002   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5003                                 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5004                                 DeclContext *ParentContext);
5005 
5006   // __null
5007   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5008 
5009   bool CheckCaseExpression(Expr *E);
5010 
5011   /// Describes the result of an "if-exists" condition check.
5012   enum IfExistsResult {
5013     /// The symbol exists.
5014     IER_Exists,
5015 
5016     /// The symbol does not exist.
5017     IER_DoesNotExist,
5018 
5019     /// The name is a dependent name, so the results will differ
5020     /// from one instantiation to the next.
5021     IER_Dependent,
5022 
5023     /// An error occurred.
5024     IER_Error
5025   };
5026 
5027   IfExistsResult
5028   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5029                                const DeclarationNameInfo &TargetNameInfo);
5030 
5031   IfExistsResult
5032   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5033                                bool IsIfExists, CXXScopeSpec &SS,
5034                                UnqualifiedId &Name);
5035 
5036   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5037                                         bool IsIfExists,
5038                                         NestedNameSpecifierLoc QualifierLoc,
5039                                         DeclarationNameInfo NameInfo,
5040                                         Stmt *Nested);
5041   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5042                                         bool IsIfExists,
5043                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5044                                         Stmt *Nested);
5045 
5046   //===------------------------- "Block" Extension ------------------------===//
5047 
5048   /// ActOnBlockStart - This callback is invoked when a block literal is
5049   /// started.
5050   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5051 
5052   /// ActOnBlockArguments - This callback allows processing of block arguments.
5053   /// If there are no arguments, this is still invoked.
5054   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5055                            Scope *CurScope);
5056 
5057   /// ActOnBlockError - If there is an error parsing a block, this callback
5058   /// is invoked to pop the information about the block from the action impl.
5059   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5060 
5061   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5062   /// literal was successfully completed.  ^(int x){...}
5063   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5064                                 Scope *CurScope);
5065 
5066   //===---------------------------- Clang Extensions ----------------------===//
5067 
5068   /// __builtin_convertvector(...)
5069   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5070                                     SourceLocation BuiltinLoc,
5071                                     SourceLocation RParenLoc);
5072 
5073   //===---------------------------- OpenCL Features -----------------------===//
5074 
5075   /// __builtin_astype(...)
5076   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5077                              SourceLocation BuiltinLoc,
5078                              SourceLocation RParenLoc);
5079 
5080   //===---------------------------- C++ Features --------------------------===//
5081 
5082   // Act on C++ namespaces
5083   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5084                                SourceLocation NamespaceLoc,
5085                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5086                                SourceLocation LBrace,
5087                                const ParsedAttributesView &AttrList,
5088                                UsingDirectiveDecl *&UsingDecl);
5089   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5090 
5091   NamespaceDecl *getStdNamespace() const;
5092   NamespaceDecl *getOrCreateStdNamespace();
5093 
5094   NamespaceDecl *lookupStdExperimentalNamespace();
5095 
5096   CXXRecordDecl *getStdBadAlloc() const;
5097   EnumDecl *getStdAlignValT() const;
5098 
5099 private:
5100   // A cache representing if we've fully checked the various comparison category
5101   // types stored in ASTContext. The bit-index corresponds to the integer value
5102   // of a ComparisonCategoryType enumerator.
5103   llvm::SmallBitVector FullyCheckedComparisonCategories;
5104 
5105   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5106                                          CXXScopeSpec &SS,
5107                                          ParsedType TemplateTypeTy,
5108                                          IdentifierInfo *MemberOrBase);
5109 
5110 public:
5111   enum class ComparisonCategoryUsage {
5112     /// The '<=>' operator was used in an expression and a builtin operator
5113     /// was selected.
5114     OperatorInExpression,
5115     /// A defaulted 'operator<=>' needed the comparison category. This
5116     /// typically only applies to 'std::strong_ordering', due to the implicit
5117     /// fallback return value.
5118     DefaultedOperator,
5119   };
5120 
5121   /// Lookup the specified comparison category types in the standard
5122   ///   library, an check the VarDecls possibly returned by the operator<=>
5123   ///   builtins for that type.
5124   ///
5125   /// \return The type of the comparison category type corresponding to the
5126   ///   specified Kind, or a null type if an error occurs
5127   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5128                                        SourceLocation Loc,
5129                                        ComparisonCategoryUsage Usage);
5130 
5131   /// Tests whether Ty is an instance of std::initializer_list and, if
5132   /// it is and Element is not NULL, assigns the element type to Element.
5133   bool isStdInitializerList(QualType Ty, QualType *Element);
5134 
5135   /// Looks for the std::initializer_list template and instantiates it
5136   /// with Element, or emits an error if it's not found.
5137   ///
5138   /// \returns The instantiated template, or null on error.
5139   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5140 
5141   /// Determine whether Ctor is an initializer-list constructor, as
5142   /// defined in [dcl.init.list]p2.
5143   bool isInitListConstructor(const FunctionDecl *Ctor);
5144 
5145   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5146                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5147                             SourceLocation IdentLoc,
5148                             IdentifierInfo *NamespcName,
5149                             const ParsedAttributesView &AttrList);
5150 
5151   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5152 
5153   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5154                                SourceLocation NamespaceLoc,
5155                                SourceLocation AliasLoc,
5156                                IdentifierInfo *Alias,
5157                                CXXScopeSpec &SS,
5158                                SourceLocation IdentLoc,
5159                                IdentifierInfo *Ident);
5160 
5161   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5162   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5163                             const LookupResult &PreviousDecls,
5164                             UsingShadowDecl *&PrevShadow);
5165   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5166                                         NamedDecl *Target,
5167                                         UsingShadowDecl *PrevDecl);
5168 
5169   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5170                                    bool HasTypenameKeyword,
5171                                    const CXXScopeSpec &SS,
5172                                    SourceLocation NameLoc,
5173                                    const LookupResult &Previous);
5174   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5175                                bool HasTypename,
5176                                const CXXScopeSpec &SS,
5177                                const DeclarationNameInfo &NameInfo,
5178                                SourceLocation NameLoc);
5179 
5180   NamedDecl *BuildUsingDeclaration(
5181       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5182       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5183       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5184       const ParsedAttributesView &AttrList, bool IsInstantiation);
5185   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5186                                 ArrayRef<NamedDecl *> Expansions);
5187 
5188   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5189 
5190   /// Given a derived-class using shadow declaration for a constructor and the
5191   /// correspnding base class constructor, find or create the implicit
5192   /// synthesized derived class constructor to use for this initialization.
5193   CXXConstructorDecl *
5194   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5195                             ConstructorUsingShadowDecl *DerivedShadow);
5196 
5197   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5198                               SourceLocation UsingLoc,
5199                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
5200                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
5201                               const ParsedAttributesView &AttrList);
5202   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5203                               MultiTemplateParamsArg TemplateParams,
5204                               SourceLocation UsingLoc, UnqualifiedId &Name,
5205                               const ParsedAttributesView &AttrList,
5206                               TypeResult Type, Decl *DeclFromDeclSpec);
5207 
5208   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5209   /// including handling of its default argument expressions.
5210   ///
5211   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5212   ExprResult
5213   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5214                         NamedDecl *FoundDecl,
5215                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5216                         bool HadMultipleCandidates, bool IsListInitialization,
5217                         bool IsStdInitListInitialization,
5218                         bool RequiresZeroInit, unsigned ConstructKind,
5219                         SourceRange ParenRange);
5220 
5221   /// Build a CXXConstructExpr whose constructor has already been resolved if
5222   /// it denotes an inherited constructor.
5223   ExprResult
5224   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5225                         CXXConstructorDecl *Constructor, bool Elidable,
5226                         MultiExprArg Exprs,
5227                         bool HadMultipleCandidates, bool IsListInitialization,
5228                         bool IsStdInitListInitialization,
5229                         bool RequiresZeroInit, unsigned ConstructKind,
5230                         SourceRange ParenRange);
5231 
5232   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5233   // the constructor can be elidable?
5234   ExprResult
5235   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5236                         NamedDecl *FoundDecl,
5237                         CXXConstructorDecl *Constructor, bool Elidable,
5238                         MultiExprArg Exprs, bool HadMultipleCandidates,
5239                         bool IsListInitialization,
5240                         bool IsStdInitListInitialization, bool RequiresZeroInit,
5241                         unsigned ConstructKind, SourceRange ParenRange);
5242 
5243   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5244 
5245 
5246   /// Instantiate or parse a C++ default argument expression as necessary.
5247   /// Return true on error.
5248   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5249                               ParmVarDecl *Param);
5250 
5251   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5252   /// the default expr if needed.
5253   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5254                                     FunctionDecl *FD,
5255                                     ParmVarDecl *Param);
5256 
5257   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5258   /// constructed variable.
5259   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5260 
5261   /// Helper class that collects exception specifications for
5262   /// implicitly-declared special member functions.
5263   class ImplicitExceptionSpecification {
5264     // Pointer to allow copying
5265     Sema *Self;
5266     // We order exception specifications thus:
5267     // noexcept is the most restrictive, but is only used in C++11.
5268     // throw() comes next.
5269     // Then a throw(collected exceptions)
5270     // Finally no specification, which is expressed as noexcept(false).
5271     // throw(...) is used instead if any called function uses it.
5272     ExceptionSpecificationType ComputedEST;
5273     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5274     SmallVector<QualType, 4> Exceptions;
5275 
5276     void ClearExceptions() {
5277       ExceptionsSeen.clear();
5278       Exceptions.clear();
5279     }
5280 
5281   public:
5282     explicit ImplicitExceptionSpecification(Sema &Self)
5283       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5284       if (!Self.getLangOpts().CPlusPlus11)
5285         ComputedEST = EST_DynamicNone;
5286     }
5287 
5288     /// Get the computed exception specification type.
5289     ExceptionSpecificationType getExceptionSpecType() const {
5290       assert(!isComputedNoexcept(ComputedEST) &&
5291              "noexcept(expr) should not be a possible result");
5292       return ComputedEST;
5293     }
5294 
5295     /// The number of exceptions in the exception specification.
5296     unsigned size() const { return Exceptions.size(); }
5297 
5298     /// The set of exceptions in the exception specification.
5299     const QualType *data() const { return Exceptions.data(); }
5300 
5301     /// Integrate another called method into the collected data.
5302     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5303 
5304     /// Integrate an invoked expression into the collected data.
5305     void CalledExpr(Expr *E) { CalledStmt(E); }
5306 
5307     /// Integrate an invoked statement into the collected data.
5308     void CalledStmt(Stmt *S);
5309 
5310     /// Overwrite an EPI's exception specification with this
5311     /// computed exception specification.
5312     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5313       FunctionProtoType::ExceptionSpecInfo ESI;
5314       ESI.Type = getExceptionSpecType();
5315       if (ESI.Type == EST_Dynamic) {
5316         ESI.Exceptions = Exceptions;
5317       } else if (ESI.Type == EST_None) {
5318         /// C++11 [except.spec]p14:
5319         ///   The exception-specification is noexcept(false) if the set of
5320         ///   potential exceptions of the special member function contains "any"
5321         ESI.Type = EST_NoexceptFalse;
5322         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5323                                                      tok::kw_false).get();
5324       }
5325       return ESI;
5326     }
5327   };
5328 
5329   /// Determine what sort of exception specification a defaulted
5330   /// copy constructor of a class will have.
5331   ImplicitExceptionSpecification
5332   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5333                                            CXXMethodDecl *MD);
5334 
5335   /// Determine what sort of exception specification a defaulted
5336   /// default constructor of a class will have, and whether the parameter
5337   /// will be const.
5338   ImplicitExceptionSpecification
5339   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5340 
5341   /// Determine what sort of exception specification a defaulted
5342   /// copy assignment operator of a class will have, and whether the
5343   /// parameter will be const.
5344   ImplicitExceptionSpecification
5345   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5346 
5347   /// Determine what sort of exception specification a defaulted move
5348   /// constructor of a class will have.
5349   ImplicitExceptionSpecification
5350   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5351 
5352   /// Determine what sort of exception specification a defaulted move
5353   /// assignment operator of a class will have.
5354   ImplicitExceptionSpecification
5355   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5356 
5357   /// Determine what sort of exception specification a defaulted
5358   /// destructor of a class will have.
5359   ImplicitExceptionSpecification
5360   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5361 
5362   /// Determine what sort of exception specification an inheriting
5363   /// constructor of a class will have.
5364   ImplicitExceptionSpecification
5365   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5366                                      CXXConstructorDecl *CD);
5367 
5368   /// Evaluate the implicit exception specification for a defaulted
5369   /// special member function.
5370   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5371 
5372   /// Check the given noexcept-specifier, convert its expression, and compute
5373   /// the appropriate ExceptionSpecificationType.
5374   ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5375                                ExceptionSpecificationType &EST);
5376 
5377   /// Check the given exception-specification and update the
5378   /// exception specification information with the results.
5379   void checkExceptionSpecification(bool IsTopLevel,
5380                                    ExceptionSpecificationType EST,
5381                                    ArrayRef<ParsedType> DynamicExceptions,
5382                                    ArrayRef<SourceRange> DynamicExceptionRanges,
5383                                    Expr *NoexceptExpr,
5384                                    SmallVectorImpl<QualType> &Exceptions,
5385                                    FunctionProtoType::ExceptionSpecInfo &ESI);
5386 
5387   /// Determine if we're in a case where we need to (incorrectly) eagerly
5388   /// parse an exception specification to work around a libstdc++ bug.
5389   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5390 
5391   /// Add an exception-specification to the given member function
5392   /// (or member function template). The exception-specification was parsed
5393   /// after the method itself was declared.
5394   void actOnDelayedExceptionSpecification(Decl *Method,
5395          ExceptionSpecificationType EST,
5396          SourceRange SpecificationRange,
5397          ArrayRef<ParsedType> DynamicExceptions,
5398          ArrayRef<SourceRange> DynamicExceptionRanges,
5399          Expr *NoexceptExpr);
5400 
5401   class InheritedConstructorInfo;
5402 
5403   /// Determine if a special member function should have a deleted
5404   /// definition when it is defaulted.
5405   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5406                                  InheritedConstructorInfo *ICI = nullptr,
5407                                  bool Diagnose = false);
5408 
5409   /// Produce notes explaining why a defaulted function was defined as deleted.
5410   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5411 
5412   /// Declare the implicit default constructor for the given class.
5413   ///
5414   /// \param ClassDecl The class declaration into which the implicit
5415   /// default constructor will be added.
5416   ///
5417   /// \returns The implicitly-declared default constructor.
5418   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5419                                                      CXXRecordDecl *ClassDecl);
5420 
5421   /// DefineImplicitDefaultConstructor - Checks for feasibility of
5422   /// defining this constructor as the default constructor.
5423   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5424                                         CXXConstructorDecl *Constructor);
5425 
5426   /// Declare the implicit destructor for the given class.
5427   ///
5428   /// \param ClassDecl The class declaration into which the implicit
5429   /// destructor will be added.
5430   ///
5431   /// \returns The implicitly-declared destructor.
5432   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5433 
5434   /// DefineImplicitDestructor - Checks for feasibility of
5435   /// defining this destructor as the default destructor.
5436   void DefineImplicitDestructor(SourceLocation CurrentLocation,
5437                                 CXXDestructorDecl *Destructor);
5438 
5439   /// Build an exception spec for destructors that don't have one.
5440   ///
5441   /// C++11 says that user-defined destructors with no exception spec get one
5442   /// that looks as if the destructor was implicitly declared.
5443   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5444 
5445   /// Define the specified inheriting constructor.
5446   void DefineInheritingConstructor(SourceLocation UseLoc,
5447                                    CXXConstructorDecl *Constructor);
5448 
5449   /// Declare the implicit copy constructor for the given class.
5450   ///
5451   /// \param ClassDecl The class declaration into which the implicit
5452   /// copy constructor will be added.
5453   ///
5454   /// \returns The implicitly-declared copy constructor.
5455   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5456 
5457   /// DefineImplicitCopyConstructor - Checks for feasibility of
5458   /// defining this constructor as the copy constructor.
5459   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5460                                      CXXConstructorDecl *Constructor);
5461 
5462   /// Declare the implicit move constructor for the given class.
5463   ///
5464   /// \param ClassDecl The Class declaration into which the implicit
5465   /// move constructor will be added.
5466   ///
5467   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5468   /// declared.
5469   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5470 
5471   /// DefineImplicitMoveConstructor - Checks for feasibility of
5472   /// defining this constructor as the move constructor.
5473   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5474                                      CXXConstructorDecl *Constructor);
5475 
5476   /// Declare the implicit copy assignment operator for the given class.
5477   ///
5478   /// \param ClassDecl The class declaration into which the implicit
5479   /// copy assignment operator will be added.
5480   ///
5481   /// \returns The implicitly-declared copy assignment operator.
5482   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5483 
5484   /// Defines an implicitly-declared copy assignment operator.
5485   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5486                                     CXXMethodDecl *MethodDecl);
5487 
5488   /// Declare the implicit move assignment operator for the given class.
5489   ///
5490   /// \param ClassDecl The Class declaration into which the implicit
5491   /// move assignment operator will be added.
5492   ///
5493   /// \returns The implicitly-declared move assignment operator, or NULL if it
5494   /// wasn't declared.
5495   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5496 
5497   /// Defines an implicitly-declared move assignment operator.
5498   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5499                                     CXXMethodDecl *MethodDecl);
5500 
5501   /// Force the declaration of any implicitly-declared members of this
5502   /// class.
5503   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5504 
5505   /// Check a completed declaration of an implicit special member.
5506   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5507 
5508   /// Determine whether the given function is an implicitly-deleted
5509   /// special member function.
5510   bool isImplicitlyDeleted(FunctionDecl *FD);
5511 
5512   /// Check whether 'this' shows up in the type of a static member
5513   /// function after the (naturally empty) cv-qualifier-seq would be.
5514   ///
5515   /// \returns true if an error occurred.
5516   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5517 
5518   /// Whether this' shows up in the exception specification of a static
5519   /// member function.
5520   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5521 
5522   /// Check whether 'this' shows up in the attributes of the given
5523   /// static member function.
5524   ///
5525   /// \returns true if an error occurred.
5526   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5527 
5528   /// MaybeBindToTemporary - If the passed in expression has a record type with
5529   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5530   /// it simply returns the passed in expression.
5531   ExprResult MaybeBindToTemporary(Expr *E);
5532 
5533   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5534                                MultiExprArg ArgsPtr,
5535                                SourceLocation Loc,
5536                                SmallVectorImpl<Expr*> &ConvertedArgs,
5537                                bool AllowExplicit = false,
5538                                bool IsListInitialization = false);
5539 
5540   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5541                                           SourceLocation NameLoc,
5542                                           IdentifierInfo &Name);
5543 
5544   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5545                                 Scope *S, CXXScopeSpec &SS,
5546                                 bool EnteringContext);
5547   ParsedType getDestructorName(SourceLocation TildeLoc,
5548                                IdentifierInfo &II, SourceLocation NameLoc,
5549                                Scope *S, CXXScopeSpec &SS,
5550                                ParsedType ObjectType,
5551                                bool EnteringContext);
5552 
5553   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5554                                           ParsedType ObjectType);
5555 
5556   // Checks that reinterpret casts don't have undefined behavior.
5557   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5558                                       bool IsDereference, SourceRange Range);
5559 
5560   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
5561   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5562                                tok::TokenKind Kind,
5563                                SourceLocation LAngleBracketLoc,
5564                                Declarator &D,
5565                                SourceLocation RAngleBracketLoc,
5566                                SourceLocation LParenLoc,
5567                                Expr *E,
5568                                SourceLocation RParenLoc);
5569 
5570   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5571                                tok::TokenKind Kind,
5572                                TypeSourceInfo *Ty,
5573                                Expr *E,
5574                                SourceRange AngleBrackets,
5575                                SourceRange Parens);
5576 
5577   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5578                                      ExprResult Operand,
5579                                      SourceLocation RParenLoc);
5580 
5581   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5582                                      Expr *Operand, SourceLocation RParenLoc);
5583 
5584   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5585                             SourceLocation TypeidLoc,
5586                             TypeSourceInfo *Operand,
5587                             SourceLocation RParenLoc);
5588   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5589                             SourceLocation TypeidLoc,
5590                             Expr *Operand,
5591                             SourceLocation RParenLoc);
5592 
5593   /// ActOnCXXTypeid - Parse typeid( something ).
5594   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5595                             SourceLocation LParenLoc, bool isType,
5596                             void *TyOrExpr,
5597                             SourceLocation RParenLoc);
5598 
5599   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5600                             SourceLocation TypeidLoc,
5601                             TypeSourceInfo *Operand,
5602                             SourceLocation RParenLoc);
5603   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5604                             SourceLocation TypeidLoc,
5605                             Expr *Operand,
5606                             SourceLocation RParenLoc);
5607 
5608   /// ActOnCXXUuidof - Parse __uuidof( something ).
5609   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5610                             SourceLocation LParenLoc, bool isType,
5611                             void *TyOrExpr,
5612                             SourceLocation RParenLoc);
5613 
5614   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
5615   ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5616                               tok::TokenKind Operator,
5617                               SourceLocation EllipsisLoc, Expr *RHS,
5618                               SourceLocation RParenLoc);
5619   ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5620                               BinaryOperatorKind Operator,
5621                               SourceLocation EllipsisLoc, Expr *RHS,
5622                               SourceLocation RParenLoc,
5623                               Optional<unsigned> NumExpansions);
5624   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5625                                    BinaryOperatorKind Operator);
5626 
5627   //// ActOnCXXThis -  Parse 'this' pointer.
5628   ExprResult ActOnCXXThis(SourceLocation loc);
5629 
5630   /// Build a CXXThisExpr and mark it referenced in the current context.
5631   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
5632   void MarkThisReferenced(CXXThisExpr *This);
5633 
5634   /// Try to retrieve the type of the 'this' pointer.
5635   ///
5636   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5637   QualType getCurrentThisType();
5638 
5639   /// When non-NULL, the C++ 'this' expression is allowed despite the
5640   /// current context not being a non-static member function. In such cases,
5641   /// this provides the type used for 'this'.
5642   QualType CXXThisTypeOverride;
5643 
5644   /// RAII object used to temporarily allow the C++ 'this' expression
5645   /// to be used, with the given qualifiers on the current class type.
5646   class CXXThisScopeRAII {
5647     Sema &S;
5648     QualType OldCXXThisTypeOverride;
5649     bool Enabled;
5650 
5651   public:
5652     /// Introduce a new scope where 'this' may be allowed (when enabled),
5653     /// using the given declaration (which is either a class template or a
5654     /// class) along with the given qualifiers.
5655     /// along with the qualifiers placed on '*this'.
5656     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
5657                      bool Enabled = true);
5658 
5659     ~CXXThisScopeRAII();
5660   };
5661 
5662   /// Make sure the value of 'this' is actually available in the current
5663   /// context, if it is a potentially evaluated context.
5664   ///
5665   /// \param Loc The location at which the capture of 'this' occurs.
5666   ///
5667   /// \param Explicit Whether 'this' is explicitly captured in a lambda
5668   /// capture list.
5669   ///
5670   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5671   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5672   /// This is useful when enclosing lambdas must speculatively capture
5673   /// 'this' that may or may not be used in certain specializations of
5674   /// a nested generic lambda (depending on whether the name resolves to
5675   /// a non-static member function or a static function).
5676   /// \return returns 'true' if failed, 'false' if success.
5677   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5678       bool BuildAndDiagnose = true,
5679       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5680       bool ByCopy = false);
5681 
5682   /// Determine whether the given type is the type of *this that is used
5683   /// outside of the body of a member function for a type that is currently
5684   /// being defined.
5685   bool isThisOutsideMemberFunctionBody(QualType BaseType);
5686 
5687   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5688   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5689 
5690 
5691   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5692   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5693 
5694   ExprResult
5695   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5696                                  SourceLocation AtLoc, SourceLocation RParen);
5697 
5698   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5699   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5700 
5701   //// ActOnCXXThrow -  Parse throw expressions.
5702   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5703   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5704                            bool IsThrownVarInScope);
5705   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5706 
5707   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5708   /// Can be interpreted either as function-style casting ("int(x)")
5709   /// or class type construction ("ClassType(x,y,z)")
5710   /// or creation of a value-initialized type ("int()").
5711   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5712                                        SourceLocation LParenOrBraceLoc,
5713                                        MultiExprArg Exprs,
5714                                        SourceLocation RParenOrBraceLoc,
5715                                        bool ListInitialization);
5716 
5717   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5718                                        SourceLocation LParenLoc,
5719                                        MultiExprArg Exprs,
5720                                        SourceLocation RParenLoc,
5721                                        bool ListInitialization);
5722 
5723   /// ActOnCXXNew - Parsed a C++ 'new' expression.
5724   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5725                          SourceLocation PlacementLParen,
5726                          MultiExprArg PlacementArgs,
5727                          SourceLocation PlacementRParen,
5728                          SourceRange TypeIdParens, Declarator &D,
5729                          Expr *Initializer);
5730   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5731                          SourceLocation PlacementLParen,
5732                          MultiExprArg PlacementArgs,
5733                          SourceLocation PlacementRParen,
5734                          SourceRange TypeIdParens,
5735                          QualType AllocType,
5736                          TypeSourceInfo *AllocTypeInfo,
5737                          Optional<Expr *> ArraySize,
5738                          SourceRange DirectInitRange,
5739                          Expr *Initializer);
5740 
5741   /// Determine whether \p FD is an aligned allocation or deallocation
5742   /// function that is unavailable.
5743   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
5744 
5745   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
5746   /// function that is unavailable.
5747   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
5748                                             SourceLocation Loc);
5749 
5750   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5751                           SourceRange R);
5752 
5753   /// The scope in which to find allocation functions.
5754   enum AllocationFunctionScope {
5755     /// Only look for allocation functions in the global scope.
5756     AFS_Global,
5757     /// Only look for allocation functions in the scope of the
5758     /// allocated class.
5759     AFS_Class,
5760     /// Look for allocation functions in both the global scope
5761     /// and in the scope of the allocated class.
5762     AFS_Both
5763   };
5764 
5765   /// Finds the overloads of operator new and delete that are appropriate
5766   /// for the allocation.
5767   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5768                                AllocationFunctionScope NewScope,
5769                                AllocationFunctionScope DeleteScope,
5770                                QualType AllocType, bool IsArray,
5771                                bool &PassAlignment, MultiExprArg PlaceArgs,
5772                                FunctionDecl *&OperatorNew,
5773                                FunctionDecl *&OperatorDelete,
5774                                bool Diagnose = true);
5775   void DeclareGlobalNewDelete();
5776   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5777                                        ArrayRef<QualType> Params);
5778 
5779   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5780                                 DeclarationName Name, FunctionDecl* &Operator,
5781                                 bool Diagnose = true);
5782   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5783                                               bool CanProvideSize,
5784                                               bool Overaligned,
5785                                               DeclarationName Name);
5786   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5787                                                       CXXRecordDecl *RD);
5788 
5789   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5790   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5791                             bool UseGlobal, bool ArrayForm,
5792                             Expr *Operand);
5793   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5794                             bool IsDelete, bool CallCanBeVirtual,
5795                             bool WarnOnNonAbstractTypes,
5796                             SourceLocation DtorLoc);
5797 
5798   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5799                                Expr *Operand, SourceLocation RParen);
5800   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5801                                   SourceLocation RParen);
5802 
5803   /// Parsed one of the type trait support pseudo-functions.
5804   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5805                             ArrayRef<ParsedType> Args,
5806                             SourceLocation RParenLoc);
5807   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5808                             ArrayRef<TypeSourceInfo *> Args,
5809                             SourceLocation RParenLoc);
5810 
5811   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5812   /// pseudo-functions.
5813   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5814                                  SourceLocation KWLoc,
5815                                  ParsedType LhsTy,
5816                                  Expr *DimExpr,
5817                                  SourceLocation RParen);
5818 
5819   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5820                                  SourceLocation KWLoc,
5821                                  TypeSourceInfo *TSInfo,
5822                                  Expr *DimExpr,
5823                                  SourceLocation RParen);
5824 
5825   /// ActOnExpressionTrait - Parsed one of the unary type trait support
5826   /// pseudo-functions.
5827   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5828                                   SourceLocation KWLoc,
5829                                   Expr *Queried,
5830                                   SourceLocation RParen);
5831 
5832   ExprResult BuildExpressionTrait(ExpressionTrait OET,
5833                                   SourceLocation KWLoc,
5834                                   Expr *Queried,
5835                                   SourceLocation RParen);
5836 
5837   ExprResult ActOnStartCXXMemberReference(Scope *S,
5838                                           Expr *Base,
5839                                           SourceLocation OpLoc,
5840                                           tok::TokenKind OpKind,
5841                                           ParsedType &ObjectType,
5842                                           bool &MayBePseudoDestructor);
5843 
5844   ExprResult BuildPseudoDestructorExpr(Expr *Base,
5845                                        SourceLocation OpLoc,
5846                                        tok::TokenKind OpKind,
5847                                        const CXXScopeSpec &SS,
5848                                        TypeSourceInfo *ScopeType,
5849                                        SourceLocation CCLoc,
5850                                        SourceLocation TildeLoc,
5851                                      PseudoDestructorTypeStorage DestroyedType);
5852 
5853   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5854                                        SourceLocation OpLoc,
5855                                        tok::TokenKind OpKind,
5856                                        CXXScopeSpec &SS,
5857                                        UnqualifiedId &FirstTypeName,
5858                                        SourceLocation CCLoc,
5859                                        SourceLocation TildeLoc,
5860                                        UnqualifiedId &SecondTypeName);
5861 
5862   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5863                                        SourceLocation OpLoc,
5864                                        tok::TokenKind OpKind,
5865                                        SourceLocation TildeLoc,
5866                                        const DeclSpec& DS);
5867 
5868   /// MaybeCreateExprWithCleanups - If the current full-expression
5869   /// requires any cleanups, surround it with a ExprWithCleanups node.
5870   /// Otherwise, just returns the passed-in expression.
5871   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5872   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5873   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5874 
5875   MaterializeTemporaryExpr *
5876   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5877                                  bool BoundToLvalueReference);
5878 
5879   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
5880     return ActOnFinishFullExpr(
5881         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
5882   }
5883   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5884                                  bool DiscardedValue, bool IsConstexpr = false);
5885   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5886 
5887   // Marks SS invalid if it represents an incomplete type.
5888   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5889 
5890   DeclContext *computeDeclContext(QualType T);
5891   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5892                                   bool EnteringContext = false);
5893   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5894   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5895 
5896   /// The parser has parsed a global nested-name-specifier '::'.
5897   ///
5898   /// \param CCLoc The location of the '::'.
5899   ///
5900   /// \param SS The nested-name-specifier, which will be updated in-place
5901   /// to reflect the parsed nested-name-specifier.
5902   ///
5903   /// \returns true if an error occurred, false otherwise.
5904   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5905 
5906   /// The parser has parsed a '__super' nested-name-specifier.
5907   ///
5908   /// \param SuperLoc The location of the '__super' keyword.
5909   ///
5910   /// \param ColonColonLoc The location of the '::'.
5911   ///
5912   /// \param SS The nested-name-specifier, which will be updated in-place
5913   /// to reflect the parsed nested-name-specifier.
5914   ///
5915   /// \returns true if an error occurred, false otherwise.
5916   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5917                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5918 
5919   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5920                                        bool *CanCorrect = nullptr);
5921   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5922 
5923   /// Keeps information about an identifier in a nested-name-spec.
5924   ///
5925   struct NestedNameSpecInfo {
5926     /// The type of the object, if we're parsing nested-name-specifier in
5927     /// a member access expression.
5928     ParsedType ObjectType;
5929 
5930     /// The identifier preceding the '::'.
5931     IdentifierInfo *Identifier;
5932 
5933     /// The location of the identifier.
5934     SourceLocation IdentifierLoc;
5935 
5936     /// The location of the '::'.
5937     SourceLocation CCLoc;
5938 
5939     /// Creates info object for the most typical case.
5940     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5941              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5942       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5943         CCLoc(ColonColonLoc) {
5944     }
5945 
5946     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5947                        SourceLocation ColonColonLoc, QualType ObjectType)
5948       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5949         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5950     }
5951   };
5952 
5953   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5954                                     NestedNameSpecInfo &IdInfo);
5955 
5956   bool BuildCXXNestedNameSpecifier(Scope *S,
5957                                    NestedNameSpecInfo &IdInfo,
5958                                    bool EnteringContext,
5959                                    CXXScopeSpec &SS,
5960                                    NamedDecl *ScopeLookupResult,
5961                                    bool ErrorRecoveryLookup,
5962                                    bool *IsCorrectedToColon = nullptr,
5963                                    bool OnlyNamespace = false);
5964 
5965   /// The parser has parsed a nested-name-specifier 'identifier::'.
5966   ///
5967   /// \param S The scope in which this nested-name-specifier occurs.
5968   ///
5969   /// \param IdInfo Parser information about an identifier in the
5970   /// nested-name-spec.
5971   ///
5972   /// \param EnteringContext Whether we're entering the context nominated by
5973   /// this nested-name-specifier.
5974   ///
5975   /// \param SS The nested-name-specifier, which is both an input
5976   /// parameter (the nested-name-specifier before this type) and an
5977   /// output parameter (containing the full nested-name-specifier,
5978   /// including this new type).
5979   ///
5980   /// \param ErrorRecoveryLookup If true, then this method is called to improve
5981   /// error recovery. In this case do not emit error message.
5982   ///
5983   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5984   /// are allowed.  The bool value pointed by this parameter is set to 'true'
5985   /// if the identifier is treated as if it was followed by ':', not '::'.
5986   ///
5987   /// \param OnlyNamespace If true, only considers namespaces in lookup.
5988   ///
5989   /// \returns true if an error occurred, false otherwise.
5990   bool ActOnCXXNestedNameSpecifier(Scope *S,
5991                                    NestedNameSpecInfo &IdInfo,
5992                                    bool EnteringContext,
5993                                    CXXScopeSpec &SS,
5994                                    bool ErrorRecoveryLookup = false,
5995                                    bool *IsCorrectedToColon = nullptr,
5996                                    bool OnlyNamespace = false);
5997 
5998   ExprResult ActOnDecltypeExpression(Expr *E);
5999 
6000   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6001                                            const DeclSpec &DS,
6002                                            SourceLocation ColonColonLoc);
6003 
6004   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6005                                  NestedNameSpecInfo &IdInfo,
6006                                  bool EnteringContext);
6007 
6008   /// The parser has parsed a nested-name-specifier
6009   /// 'template[opt] template-name < template-args >::'.
6010   ///
6011   /// \param S The scope in which this nested-name-specifier occurs.
6012   ///
6013   /// \param SS The nested-name-specifier, which is both an input
6014   /// parameter (the nested-name-specifier before this type) and an
6015   /// output parameter (containing the full nested-name-specifier,
6016   /// including this new type).
6017   ///
6018   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6019   /// \param TemplateName the template name.
6020   /// \param TemplateNameLoc The location of the template name.
6021   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6022   /// \param TemplateArgs The template arguments.
6023   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6024   /// \param CCLoc The location of the '::'.
6025   ///
6026   /// \param EnteringContext Whether we're entering the context of the
6027   /// nested-name-specifier.
6028   ///
6029   ///
6030   /// \returns true if an error occurred, false otherwise.
6031   bool ActOnCXXNestedNameSpecifier(Scope *S,
6032                                    CXXScopeSpec &SS,
6033                                    SourceLocation TemplateKWLoc,
6034                                    TemplateTy TemplateName,
6035                                    SourceLocation TemplateNameLoc,
6036                                    SourceLocation LAngleLoc,
6037                                    ASTTemplateArgsPtr TemplateArgs,
6038                                    SourceLocation RAngleLoc,
6039                                    SourceLocation CCLoc,
6040                                    bool EnteringContext);
6041 
6042   /// Given a C++ nested-name-specifier, produce an annotation value
6043   /// that the parser can use later to reconstruct the given
6044   /// nested-name-specifier.
6045   ///
6046   /// \param SS A nested-name-specifier.
6047   ///
6048   /// \returns A pointer containing all of the information in the
6049   /// nested-name-specifier \p SS.
6050   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6051 
6052   /// Given an annotation pointer for a nested-name-specifier, restore
6053   /// the nested-name-specifier structure.
6054   ///
6055   /// \param Annotation The annotation pointer, produced by
6056   /// \c SaveNestedNameSpecifierAnnotation().
6057   ///
6058   /// \param AnnotationRange The source range corresponding to the annotation.
6059   ///
6060   /// \param SS The nested-name-specifier that will be updated with the contents
6061   /// of the annotation pointer.
6062   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6063                                             SourceRange AnnotationRange,
6064                                             CXXScopeSpec &SS);
6065 
6066   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6067 
6068   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6069   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6070   /// After this method is called, according to [C++ 3.4.3p3], names should be
6071   /// looked up in the declarator-id's scope, until the declarator is parsed and
6072   /// ActOnCXXExitDeclaratorScope is called.
6073   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6074   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6075 
6076   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6077   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6078   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6079   /// Used to indicate that names should revert to being looked up in the
6080   /// defining scope.
6081   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6082 
6083   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6084   /// initializer for the declaration 'Dcl'.
6085   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6086   /// static data member of class X, names should be looked up in the scope of
6087   /// class X.
6088   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6089 
6090   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6091   /// initializer for the declaration 'Dcl'.
6092   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6093 
6094   /// Create a new lambda closure type.
6095   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6096                                          TypeSourceInfo *Info,
6097                                          bool KnownDependent,
6098                                          LambdaCaptureDefault CaptureDefault);
6099 
6100   /// Start the definition of a lambda expression.
6101   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6102                                        SourceRange IntroducerRange,
6103                                        TypeSourceInfo *MethodType,
6104                                        SourceLocation EndLoc,
6105                                        ArrayRef<ParmVarDecl *> Params,
6106                                        ConstexprSpecKind ConstexprKind,
6107                                        Expr *TrailingRequiresClause);
6108 
6109   /// Number lambda for linkage purposes if necessary.
6110   void handleLambdaNumbering(
6111       CXXRecordDecl *Class, CXXMethodDecl *Method,
6112       Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6113 
6114   /// Endow the lambda scope info with the relevant properties.
6115   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6116                         CXXMethodDecl *CallOperator,
6117                         SourceRange IntroducerRange,
6118                         LambdaCaptureDefault CaptureDefault,
6119                         SourceLocation CaptureDefaultLoc,
6120                         bool ExplicitParams,
6121                         bool ExplicitResultType,
6122                         bool Mutable);
6123 
6124   /// Perform initialization analysis of the init-capture and perform
6125   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6126   /// not being used to initialize a reference.
6127   ParsedType actOnLambdaInitCaptureInitialization(
6128       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6129       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6130     return ParsedType::make(buildLambdaInitCaptureInitialization(
6131         Loc, ByRef, EllipsisLoc, None, Id,
6132         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6133   }
6134   QualType buildLambdaInitCaptureInitialization(
6135       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6136       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6137       Expr *&Init);
6138 
6139   /// Create a dummy variable within the declcontext of the lambda's
6140   ///  call operator, for name lookup purposes for a lambda init capture.
6141   ///
6142   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6143   ///  variables appropriately.
6144   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6145                                           QualType InitCaptureType,
6146                                           SourceLocation EllipsisLoc,
6147                                           IdentifierInfo *Id,
6148                                           unsigned InitStyle, Expr *Init);
6149 
6150   /// Add an init-capture to a lambda scope.
6151   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6152 
6153   /// Note that we have finished the explicit captures for the
6154   /// given lambda.
6155   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6156 
6157   /// \brief This is called after parsing the explicit template parameter list
6158   /// on a lambda (if it exists) in C++2a.
6159   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6160                                                 ArrayRef<NamedDecl *> TParams,
6161                                                 SourceLocation RAngleLoc);
6162 
6163   /// Introduce the lambda parameters into scope.
6164   void addLambdaParameters(
6165       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6166       CXXMethodDecl *CallOperator, Scope *CurScope);
6167 
6168   /// Deduce a block or lambda's return type based on the return
6169   /// statements present in the body.
6170   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6171 
6172   /// ActOnStartOfLambdaDefinition - This is called just before we start
6173   /// parsing the body of a lambda; it analyzes the explicit captures and
6174   /// arguments, and sets up various data-structures for the body of the
6175   /// lambda.
6176   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6177                                     Declarator &ParamInfo, Scope *CurScope);
6178 
6179   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6180   /// is invoked to pop the information about the lambda.
6181   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6182                         bool IsInstantiation = false);
6183 
6184   /// ActOnLambdaExpr - This is called when the body of a lambda expression
6185   /// was successfully completed.
6186   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6187                              Scope *CurScope);
6188 
6189   /// Does copying/destroying the captured variable have side effects?
6190   bool CaptureHasSideEffects(const sema::Capture &From);
6191 
6192   /// Diagnose if an explicit lambda capture is unused. Returns true if a
6193   /// diagnostic is emitted.
6194   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6195                                    const sema::Capture &From);
6196 
6197   /// Build a FieldDecl suitable to hold the given capture.
6198   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6199 
6200   /// Initialize the given capture with a suitable expression.
6201   ExprResult BuildCaptureInit(const sema::Capture &Capture,
6202                               SourceLocation ImplicitCaptureLoc,
6203                               bool IsOpenMPMapping = false);
6204 
6205   /// Complete a lambda-expression having processed and attached the
6206   /// lambda body.
6207   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6208                              sema::LambdaScopeInfo *LSI);
6209 
6210   /// Get the return type to use for a lambda's conversion function(s) to
6211   /// function pointer type, given the type of the call operator.
6212   QualType
6213   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
6214 
6215   /// Define the "body" of the conversion from a lambda object to a
6216   /// function pointer.
6217   ///
6218   /// This routine doesn't actually define a sensible body; rather, it fills
6219   /// in the initialization expression needed to copy the lambda object into
6220   /// the block, and IR generation actually generates the real body of the
6221   /// block pointer conversion.
6222   void DefineImplicitLambdaToFunctionPointerConversion(
6223          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6224 
6225   /// Define the "body" of the conversion from a lambda object to a
6226   /// block pointer.
6227   ///
6228   /// This routine doesn't actually define a sensible body; rather, it fills
6229   /// in the initialization expression needed to copy the lambda object into
6230   /// the block, and IR generation actually generates the real body of the
6231   /// block pointer conversion.
6232   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6233                                                     CXXConversionDecl *Conv);
6234 
6235   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6236                                            SourceLocation ConvLocation,
6237                                            CXXConversionDecl *Conv,
6238                                            Expr *Src);
6239 
6240   /// Check whether the given expression is a valid constraint expression.
6241   /// A diagnostic is emitted if it is not, false is returned, and
6242   /// PossibleNonPrimary will be set to true if the failure might be due to a
6243   /// non-primary expression being used as an atomic constraint.
6244   bool CheckConstraintExpression(Expr *CE, Token NextToken = Token(),
6245                                  bool *PossibleNonPrimary = nullptr,
6246                                  bool IsTrailingRequiresClause = false);
6247 
6248   /// Check whether the given type-dependent expression will be the name of a
6249   /// function or another callable function-like entity (e.g. a function
6250   // template or overload set) for any substitution.
6251   bool IsDependentFunctionNameExpr(Expr *E);
6252 
6253 private:
6254   /// Caches pairs of template-like decls whose associated constraints were
6255   /// checked for subsumption and whether or not the first's constraints did in
6256   /// fact subsume the second's.
6257   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6258   /// Caches the normalized associated constraints of declarations (concepts or
6259   /// constrained declarations). If an error occurred while normalizing the
6260   /// associated constraints of the template or concept, nullptr will be cached
6261   /// here.
6262   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6263       NormalizationCache;
6264 
6265   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6266       SatisfactionCache;
6267 
6268 public:
6269   const NormalizedConstraint *
6270   getNormalizedAssociatedConstraints(
6271       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6272 
6273   /// \brief Check whether the given declaration's associated constraints are
6274   /// at least as constrained than another declaration's according to the
6275   /// partial ordering of constraints.
6276   ///
6277   /// \param Result If no error occurred, receives the result of true if D1 is
6278   /// at least constrained than D2, and false otherwise.
6279   ///
6280   /// \returns true if an error occurred, false otherwise.
6281   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6282                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
6283                               bool &Result);
6284 
6285   /// If D1 was not at least as constrained as D2, but would've been if a pair
6286   /// of atomic constraints involved had been declared in a concept and not
6287   /// repeated in two separate places in code.
6288   /// \returns true if such a diagnostic was emitted, false otherwise.
6289   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6290       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6291 
6292   /// \brief Check whether the given list of constraint expressions are
6293   /// satisfied (as if in a 'conjunction') given template arguments.
6294   /// \param Template the template-like entity that triggered the constraints
6295   /// check (either a concept or a constrained entity).
6296   /// \param ConstraintExprs a list of constraint expressions, treated as if
6297   /// they were 'AND'ed together.
6298   /// \param TemplateArgs the list of template arguments to substitute into the
6299   /// constraint expression.
6300   /// \param TemplateIDRange The source range of the template id that
6301   /// caused the constraints check.
6302   /// \param Satisfaction if true is returned, will contain details of the
6303   /// satisfaction, with enough information to diagnose an unsatisfied
6304   /// expression.
6305   /// \returns true if an error occurred and satisfaction could not be checked,
6306   /// false otherwise.
6307   bool CheckConstraintSatisfaction(
6308       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6309       ArrayRef<TemplateArgument> TemplateArgs,
6310       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6311 
6312   /// \brief Check whether the given non-dependent constraint expression is
6313   /// satisfied. Returns false and updates Satisfaction with the satisfaction
6314   /// verdict if successful, emits a diagnostic and returns true if an error
6315   /// occured and satisfaction could not be determined.
6316   ///
6317   /// \returns true if an error occurred, false otherwise.
6318   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6319                                    ConstraintSatisfaction &Satisfaction);
6320 
6321   /// Check whether the given function decl's trailing requires clause is
6322   /// satisfied, if any. Returns false and updates Satisfaction with the
6323   /// satisfaction verdict if successful, emits a diagnostic and returns true if
6324   /// an error occured and satisfaction could not be determined.
6325   ///
6326   /// \returns true if an error occurred, false otherwise.
6327   bool CheckFunctionConstraints(const FunctionDecl *FD,
6328                                 ConstraintSatisfaction &Satisfaction,
6329                                 SourceLocation UsageLoc = SourceLocation());
6330 
6331 
6332   /// \brief Ensure that the given template arguments satisfy the constraints
6333   /// associated with the given template, emitting a diagnostic if they do not.
6334   ///
6335   /// \param Template The template to which the template arguments are being
6336   /// provided.
6337   ///
6338   /// \param TemplateArgs The converted, canonicalized template arguments.
6339   ///
6340   /// \param TemplateIDRange The source range of the template id that
6341   /// caused the constraints check.
6342   ///
6343   /// \returns true if the constrains are not satisfied or could not be checked
6344   /// for satisfaction, false if the constraints are satisfied.
6345   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6346                                        ArrayRef<TemplateArgument> TemplateArgs,
6347                                              SourceRange TemplateIDRange);
6348 
6349   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6350   /// unsatisfied.
6351   /// \param First whether this is the first time an unsatisfied constraint is
6352   /// diagnosed for this error.
6353   void
6354   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6355                                 bool First = true);
6356 
6357   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6358   /// unsatisfied.
6359   void
6360   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6361                                 bool First = true);
6362 
6363   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6364   /// unsatisfied because it was ill-formed.
6365   void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
6366                                               StringRef Diagnostic);
6367 
6368   void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old,
6369                                                SourceLocation New);
6370 
6371   // ParseObjCStringLiteral - Parse Objective-C string literals.
6372   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6373                                     ArrayRef<Expr *> Strings);
6374 
6375   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6376 
6377   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6378   /// numeric literal expression. Type of the expression will be "NSNumber *"
6379   /// or "id" if NSNumber is unavailable.
6380   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6381   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6382                                   bool Value);
6383   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6384 
6385   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6386   /// '@' prefixed parenthesized expression. The type of the expression will
6387   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6388   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6389   /// "const char *" or C structure with attribute 'objc_boxable'.
6390   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6391 
6392   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6393                                           Expr *IndexExpr,
6394                                           ObjCMethodDecl *getterMethod,
6395                                           ObjCMethodDecl *setterMethod);
6396 
6397   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6398                                MutableArrayRef<ObjCDictionaryElement> Elements);
6399 
6400   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6401                                   TypeSourceInfo *EncodedTypeInfo,
6402                                   SourceLocation RParenLoc);
6403   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6404                                     CXXConversionDecl *Method,
6405                                     bool HadMultipleCandidates);
6406 
6407   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6408                                        SourceLocation EncodeLoc,
6409                                        SourceLocation LParenLoc,
6410                                        ParsedType Ty,
6411                                        SourceLocation RParenLoc);
6412 
6413   /// ParseObjCSelectorExpression - Build selector expression for \@selector
6414   ExprResult ParseObjCSelectorExpression(Selector Sel,
6415                                          SourceLocation AtLoc,
6416                                          SourceLocation SelLoc,
6417                                          SourceLocation LParenLoc,
6418                                          SourceLocation RParenLoc,
6419                                          bool WarnMultipleSelectors);
6420 
6421   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6422   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6423                                          SourceLocation AtLoc,
6424                                          SourceLocation ProtoLoc,
6425                                          SourceLocation LParenLoc,
6426                                          SourceLocation ProtoIdLoc,
6427                                          SourceLocation RParenLoc);
6428 
6429   //===--------------------------------------------------------------------===//
6430   // C++ Declarations
6431   //
6432   Decl *ActOnStartLinkageSpecification(Scope *S,
6433                                        SourceLocation ExternLoc,
6434                                        Expr *LangStr,
6435                                        SourceLocation LBraceLoc);
6436   Decl *ActOnFinishLinkageSpecification(Scope *S,
6437                                         Decl *LinkageSpec,
6438                                         SourceLocation RBraceLoc);
6439 
6440 
6441   //===--------------------------------------------------------------------===//
6442   // C++ Classes
6443   //
6444   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6445   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6446                           const CXXScopeSpec *SS = nullptr);
6447   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6448 
6449   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6450                             SourceLocation ColonLoc,
6451                             const ParsedAttributesView &Attrs);
6452 
6453   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6454                                  Declarator &D,
6455                                  MultiTemplateParamsArg TemplateParameterLists,
6456                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
6457                                  InClassInitStyle InitStyle);
6458 
6459   void ActOnStartCXXInClassMemberInitializer();
6460   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6461                                               SourceLocation EqualLoc,
6462                                               Expr *Init);
6463 
6464   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6465                                     Scope *S,
6466                                     CXXScopeSpec &SS,
6467                                     IdentifierInfo *MemberOrBase,
6468                                     ParsedType TemplateTypeTy,
6469                                     const DeclSpec &DS,
6470                                     SourceLocation IdLoc,
6471                                     SourceLocation LParenLoc,
6472                                     ArrayRef<Expr *> Args,
6473                                     SourceLocation RParenLoc,
6474                                     SourceLocation EllipsisLoc);
6475 
6476   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6477                                     Scope *S,
6478                                     CXXScopeSpec &SS,
6479                                     IdentifierInfo *MemberOrBase,
6480                                     ParsedType TemplateTypeTy,
6481                                     const DeclSpec &DS,
6482                                     SourceLocation IdLoc,
6483                                     Expr *InitList,
6484                                     SourceLocation EllipsisLoc);
6485 
6486   MemInitResult BuildMemInitializer(Decl *ConstructorD,
6487                                     Scope *S,
6488                                     CXXScopeSpec &SS,
6489                                     IdentifierInfo *MemberOrBase,
6490                                     ParsedType TemplateTypeTy,
6491                                     const DeclSpec &DS,
6492                                     SourceLocation IdLoc,
6493                                     Expr *Init,
6494                                     SourceLocation EllipsisLoc);
6495 
6496   MemInitResult BuildMemberInitializer(ValueDecl *Member,
6497                                        Expr *Init,
6498                                        SourceLocation IdLoc);
6499 
6500   MemInitResult BuildBaseInitializer(QualType BaseType,
6501                                      TypeSourceInfo *BaseTInfo,
6502                                      Expr *Init,
6503                                      CXXRecordDecl *ClassDecl,
6504                                      SourceLocation EllipsisLoc);
6505 
6506   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6507                                            Expr *Init,
6508                                            CXXRecordDecl *ClassDecl);
6509 
6510   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6511                                 CXXCtorInitializer *Initializer);
6512 
6513   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6514                            ArrayRef<CXXCtorInitializer *> Initializers = None);
6515 
6516   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6517 
6518 
6519   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6520   /// mark all the non-trivial destructors of its members and bases as
6521   /// referenced.
6522   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6523                                               CXXRecordDecl *Record);
6524 
6525   /// The list of classes whose vtables have been used within
6526   /// this translation unit, and the source locations at which the
6527   /// first use occurred.
6528   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6529 
6530   /// The list of vtables that are required but have not yet been
6531   /// materialized.
6532   SmallVector<VTableUse, 16> VTableUses;
6533 
6534   /// The set of classes whose vtables have been used within
6535   /// this translation unit, and a bit that will be true if the vtable is
6536   /// required to be emitted (otherwise, it should be emitted only if needed
6537   /// by code generation).
6538   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6539 
6540   /// Load any externally-stored vtable uses.
6541   void LoadExternalVTableUses();
6542 
6543   /// Note that the vtable for the given class was used at the
6544   /// given location.
6545   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6546                       bool DefinitionRequired = false);
6547 
6548   /// Mark the exception specifications of all virtual member functions
6549   /// in the given class as needed.
6550   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6551                                              const CXXRecordDecl *RD);
6552 
6553   /// MarkVirtualMembersReferenced - Will mark all members of the given
6554   /// CXXRecordDecl referenced.
6555   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6556                                     bool ConstexprOnly = false);
6557 
6558   /// Define all of the vtables that have been used in this
6559   /// translation unit and reference any virtual members used by those
6560   /// vtables.
6561   ///
6562   /// \returns true if any work was done, false otherwise.
6563   bool DefineUsedVTables();
6564 
6565   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6566 
6567   void ActOnMemInitializers(Decl *ConstructorDecl,
6568                             SourceLocation ColonLoc,
6569                             ArrayRef<CXXCtorInitializer*> MemInits,
6570                             bool AnyErrors);
6571 
6572   /// Check class-level dllimport/dllexport attribute. The caller must
6573   /// ensure that referenceDLLExportedClassMethods is called some point later
6574   /// when all outer classes of Class are complete.
6575   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6576   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6577 
6578   void referenceDLLExportedClassMethods();
6579 
6580   void propagateDLLAttrToBaseClassTemplate(
6581       CXXRecordDecl *Class, Attr *ClassAttr,
6582       ClassTemplateSpecializationDecl *BaseTemplateSpec,
6583       SourceLocation BaseLoc);
6584 
6585   /// Add gsl::Pointer attribute to std::container::iterator
6586   /// \param ND The declaration that introduces the name
6587   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6588   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6589 
6590   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6591   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6592 
6593   /// Add [[gsl::Pointer]] attributes for std:: types.
6594   void inferGslPointerAttribute(TypedefNameDecl *TD);
6595 
6596   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6597 
6598   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6599   /// conditions that are needed for the attribute to have an effect.
6600   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6601 
6602   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6603                                          Decl *TagDecl, SourceLocation LBrac,
6604                                          SourceLocation RBrac,
6605                                          const ParsedAttributesView &AttrList);
6606   void ActOnFinishCXXMemberDecls();
6607   void ActOnFinishCXXNonNestedClass();
6608 
6609   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6610   unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
6611   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6612   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6613   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6614   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6615   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6616   void ActOnFinishDelayedMemberInitializers(Decl *Record);
6617   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
6618                                 CachedTokens &Toks);
6619   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
6620   bool IsInsideALocalClassWithinATemplateFunction();
6621 
6622   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6623                                      Expr *AssertExpr,
6624                                      Expr *AssertMessageExpr,
6625                                      SourceLocation RParenLoc);
6626   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6627                                      Expr *AssertExpr,
6628                                      StringLiteral *AssertMessageExpr,
6629                                      SourceLocation RParenLoc,
6630                                      bool Failed);
6631 
6632   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
6633                                   SourceLocation FriendLoc,
6634                                   TypeSourceInfo *TSInfo);
6635   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6636                             MultiTemplateParamsArg TemplateParams);
6637   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6638                                      MultiTemplateParamsArg TemplateParams);
6639 
6640   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6641                                       StorageClass& SC);
6642   void CheckConstructor(CXXConstructorDecl *Constructor);
6643   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6644                                      StorageClass& SC);
6645   bool CheckDestructor(CXXDestructorDecl *Destructor);
6646   void CheckConversionDeclarator(Declarator &D, QualType &R,
6647                                  StorageClass& SC);
6648   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6649   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6650                                      StorageClass &SC);
6651   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
6652 
6653   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6654 
6655   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6656                                              CXXSpecialMember CSM);
6657   void CheckDelayedMemberExceptionSpecs();
6658 
6659   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6660                                           DefaultedComparisonKind DCK);
6661   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6662                                          FunctionDecl *Spaceship);
6663   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6664                                  DefaultedComparisonKind DCK);
6665 
6666   //===--------------------------------------------------------------------===//
6667   // C++ Derived Classes
6668   //
6669 
6670   /// ActOnBaseSpecifier - Parsed a base specifier
6671   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6672                                        SourceRange SpecifierRange,
6673                                        bool Virtual, AccessSpecifier Access,
6674                                        TypeSourceInfo *TInfo,
6675                                        SourceLocation EllipsisLoc);
6676 
6677   BaseResult ActOnBaseSpecifier(Decl *classdecl,
6678                                 SourceRange SpecifierRange,
6679                                 ParsedAttributes &Attrs,
6680                                 bool Virtual, AccessSpecifier Access,
6681                                 ParsedType basetype,
6682                                 SourceLocation BaseLoc,
6683                                 SourceLocation EllipsisLoc);
6684 
6685   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6686                             MutableArrayRef<CXXBaseSpecifier *> Bases);
6687   void ActOnBaseSpecifiers(Decl *ClassDecl,
6688                            MutableArrayRef<CXXBaseSpecifier *> Bases);
6689 
6690   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6691   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6692                      CXXBasePaths &Paths);
6693 
6694   // FIXME: I don't like this name.
6695   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6696 
6697   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6698                                     SourceLocation Loc, SourceRange Range,
6699                                     CXXCastPath *BasePath = nullptr,
6700                                     bool IgnoreAccess = false);
6701   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6702                                     unsigned InaccessibleBaseID,
6703                                     unsigned AmbigiousBaseConvID,
6704                                     SourceLocation Loc, SourceRange Range,
6705                                     DeclarationName Name,
6706                                     CXXCastPath *BasePath,
6707                                     bool IgnoreAccess = false);
6708 
6709   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6710 
6711   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6712                                          const CXXMethodDecl *Old);
6713 
6714   /// CheckOverridingFunctionReturnType - Checks whether the return types are
6715   /// covariant, according to C++ [class.virtual]p5.
6716   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6717                                          const CXXMethodDecl *Old);
6718 
6719   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6720   /// spec is a subset of base spec.
6721   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6722                                             const CXXMethodDecl *Old);
6723 
6724   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6725 
6726   /// CheckOverrideControl - Check C++11 override control semantics.
6727   void CheckOverrideControl(NamedDecl *D);
6728 
6729   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6730   /// not used in the declaration of an overriding method.
6731   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
6732 
6733   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
6734   /// overrides a virtual member function marked 'final', according to
6735   /// C++11 [class.virtual]p4.
6736   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6737                                               const CXXMethodDecl *Old);
6738 
6739 
6740   //===--------------------------------------------------------------------===//
6741   // C++ Access Control
6742   //
6743 
6744   enum AccessResult {
6745     AR_accessible,
6746     AR_inaccessible,
6747     AR_dependent,
6748     AR_delayed
6749   };
6750 
6751   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
6752                                 NamedDecl *PrevMemberDecl,
6753                                 AccessSpecifier LexicalAS);
6754 
6755   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
6756                                            DeclAccessPair FoundDecl);
6757   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
6758                                            DeclAccessPair FoundDecl);
6759   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
6760                                      SourceRange PlacementRange,
6761                                      CXXRecordDecl *NamingClass,
6762                                      DeclAccessPair FoundDecl,
6763                                      bool Diagnose = true);
6764   AccessResult CheckConstructorAccess(SourceLocation Loc,
6765                                       CXXConstructorDecl *D,
6766                                       DeclAccessPair FoundDecl,
6767                                       const InitializedEntity &Entity,
6768                                       bool IsCopyBindingRefToTemp = false);
6769   AccessResult CheckConstructorAccess(SourceLocation Loc,
6770                                       CXXConstructorDecl *D,
6771                                       DeclAccessPair FoundDecl,
6772                                       const InitializedEntity &Entity,
6773                                       const PartialDiagnostic &PDiag);
6774   AccessResult CheckDestructorAccess(SourceLocation Loc,
6775                                      CXXDestructorDecl *Dtor,
6776                                      const PartialDiagnostic &PDiag,
6777                                      QualType objectType = QualType());
6778   AccessResult CheckFriendAccess(NamedDecl *D);
6779   AccessResult CheckMemberAccess(SourceLocation UseLoc,
6780                                  CXXRecordDecl *NamingClass,
6781                                  DeclAccessPair Found);
6782   AccessResult
6783   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
6784                                      CXXRecordDecl *DecomposedClass,
6785                                      DeclAccessPair Field);
6786   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
6787                                          Expr *ObjectExpr,
6788                                          Expr *ArgExpr,
6789                                          DeclAccessPair FoundDecl);
6790   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
6791                                           DeclAccessPair FoundDecl);
6792   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
6793                                     QualType Base, QualType Derived,
6794                                     const CXXBasePath &Path,
6795                                     unsigned DiagID,
6796                                     bool ForceCheck = false,
6797                                     bool ForceUnprivileged = false);
6798   void CheckLookupAccess(const LookupResult &R);
6799   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
6800                           QualType BaseType);
6801   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
6802                                      DeclAccessPair Found, QualType ObjectType,
6803                                      SourceLocation Loc,
6804                                      const PartialDiagnostic &Diag);
6805   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
6806                                      DeclAccessPair Found,
6807                                      QualType ObjectType) {
6808     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
6809                                          SourceLocation(), PDiag());
6810   }
6811 
6812   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
6813                          const MultiLevelTemplateArgumentList &TemplateArgs);
6814   void PerformDependentDiagnostics(const DeclContext *Pattern,
6815                         const MultiLevelTemplateArgumentList &TemplateArgs);
6816 
6817   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
6818 
6819   /// When true, access checking violations are treated as SFINAE
6820   /// failures rather than hard errors.
6821   bool AccessCheckingSFINAE;
6822 
6823   enum AbstractDiagSelID {
6824     AbstractNone = -1,
6825     AbstractReturnType,
6826     AbstractParamType,
6827     AbstractVariableType,
6828     AbstractFieldType,
6829     AbstractIvarType,
6830     AbstractSynthesizedIvarType,
6831     AbstractArrayType
6832   };
6833 
6834   bool isAbstractType(SourceLocation Loc, QualType T);
6835   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6836                               TypeDiagnoser &Diagnoser);
6837   template <typename... Ts>
6838   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6839                               const Ts &...Args) {
6840     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6841     return RequireNonAbstractType(Loc, T, Diagnoser);
6842   }
6843 
6844   void DiagnoseAbstractType(const CXXRecordDecl *RD);
6845 
6846   //===--------------------------------------------------------------------===//
6847   // C++ Overloaded Operators [C++ 13.5]
6848   //
6849 
6850   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6851 
6852   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6853 
6854   //===--------------------------------------------------------------------===//
6855   // C++ Templates [C++ 14]
6856   //
6857   void FilterAcceptableTemplateNames(LookupResult &R,
6858                                      bool AllowFunctionTemplates = true,
6859                                      bool AllowDependent = true);
6860   bool hasAnyAcceptableTemplateNames(LookupResult &R,
6861                                      bool AllowFunctionTemplates = true,
6862                                      bool AllowDependent = true,
6863                                      bool AllowNonTemplateFunctions = false);
6864   /// Try to interpret the lookup result D as a template-name.
6865   ///
6866   /// \param D A declaration found by name lookup.
6867   /// \param AllowFunctionTemplates Whether function templates should be
6868   ///        considered valid results.
6869   /// \param AllowDependent Whether unresolved using declarations (that might
6870   ///        name templates) should be considered valid results.
6871   NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
6872                                    bool AllowFunctionTemplates = true,
6873                                    bool AllowDependent = true);
6874 
6875   enum class AssumedTemplateKind {
6876     /// This is not assumed to be a template name.
6877     None,
6878     /// This is assumed to be a template name because lookup found nothing.
6879     FoundNothing,
6880     /// This is assumed to be a template name because lookup found one or more
6881     /// functions (but no function templates).
6882     FoundFunctions,
6883   };
6884   bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
6885                           QualType ObjectType, bool EnteringContext,
6886                           bool &MemberOfUnknownSpecialization,
6887                           SourceLocation TemplateKWLoc = SourceLocation(),
6888                           AssumedTemplateKind *ATK = nullptr);
6889 
6890   TemplateNameKind isTemplateName(Scope *S,
6891                                   CXXScopeSpec &SS,
6892                                   bool hasTemplateKeyword,
6893                                   const UnqualifiedId &Name,
6894                                   ParsedType ObjectType,
6895                                   bool EnteringContext,
6896                                   TemplateTy &Template,
6897                                   bool &MemberOfUnknownSpecialization);
6898 
6899   /// Try to resolve an undeclared template name as a type template.
6900   ///
6901   /// Sets II to the identifier corresponding to the template name, and updates
6902   /// Name to a corresponding (typo-corrected) type template name and TNK to
6903   /// the corresponding kind, if possible.
6904   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
6905                                        TemplateNameKind &TNK,
6906                                        SourceLocation NameLoc,
6907                                        IdentifierInfo *&II);
6908 
6909   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
6910                                         SourceLocation NameLoc,
6911                                         bool Diagnose = true);
6912 
6913   /// Determine whether a particular identifier might be the name in a C++1z
6914   /// deduction-guide declaration.
6915   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
6916                             SourceLocation NameLoc,
6917                             ParsedTemplateTy *Template = nullptr);
6918 
6919   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
6920                                    SourceLocation IILoc,
6921                                    Scope *S,
6922                                    const CXXScopeSpec *SS,
6923                                    TemplateTy &SuggestedTemplate,
6924                                    TemplateNameKind &SuggestedKind);
6925 
6926   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6927                                       NamedDecl *Instantiation,
6928                                       bool InstantiatedFromMember,
6929                                       const NamedDecl *Pattern,
6930                                       const NamedDecl *PatternDef,
6931                                       TemplateSpecializationKind TSK,
6932                                       bool Complain = true);
6933 
6934   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6935   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6936 
6937   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
6938                                 SourceLocation EllipsisLoc,
6939                                 SourceLocation KeyLoc,
6940                                 IdentifierInfo *ParamName,
6941                                 SourceLocation ParamNameLoc,
6942                                 unsigned Depth, unsigned Position,
6943                                 SourceLocation EqualLoc,
6944                                 ParsedType DefaultArg, bool HasTypeConstraint);
6945 
6946   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
6947                            TemplateIdAnnotation *TypeConstraint,
6948                            TemplateTypeParmDecl *ConstrainedParameter,
6949                            SourceLocation EllipsisLoc);
6950 
6951   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
6952                             DeclarationNameInfo NameInfo,
6953                             ConceptDecl *NamedConcept,
6954                             const TemplateArgumentListInfo *TemplateArgs,
6955                             TemplateTypeParmDecl *ConstrainedParameter,
6956                             SourceLocation EllipsisLoc);
6957 
6958   bool AttachTypeConstraint(AutoTypeLoc TL,
6959                             NonTypeTemplateParmDecl *ConstrainedParameter,
6960                             SourceLocation EllipsisLoc);
6961 
6962   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6963                                              SourceLocation Loc);
6964   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6965 
6966   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6967                                       unsigned Depth,
6968                                       unsigned Position,
6969                                       SourceLocation EqualLoc,
6970                                       Expr *DefaultArg);
6971   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
6972                                        SourceLocation TmpLoc,
6973                                        TemplateParameterList *Params,
6974                                        SourceLocation EllipsisLoc,
6975                                        IdentifierInfo *ParamName,
6976                                        SourceLocation ParamNameLoc,
6977                                        unsigned Depth,
6978                                        unsigned Position,
6979                                        SourceLocation EqualLoc,
6980                                        ParsedTemplateArgument DefaultArg);
6981 
6982   TemplateParameterList *
6983   ActOnTemplateParameterList(unsigned Depth,
6984                              SourceLocation ExportLoc,
6985                              SourceLocation TemplateLoc,
6986                              SourceLocation LAngleLoc,
6987                              ArrayRef<NamedDecl *> Params,
6988                              SourceLocation RAngleLoc,
6989                              Expr *RequiresClause);
6990 
6991   /// The context in which we are checking a template parameter list.
6992   enum TemplateParamListContext {
6993     TPC_ClassTemplate,
6994     TPC_VarTemplate,
6995     TPC_FunctionTemplate,
6996     TPC_ClassTemplateMember,
6997     TPC_FriendClassTemplate,
6998     TPC_FriendFunctionTemplate,
6999     TPC_FriendFunctionTemplateDefinition,
7000     TPC_TypeAliasTemplate
7001   };
7002 
7003   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7004                                   TemplateParameterList *OldParams,
7005                                   TemplateParamListContext TPC,
7006                                   SkipBodyInfo *SkipBody = nullptr);
7007   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7008       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7009       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7010       ArrayRef<TemplateParameterList *> ParamLists,
7011       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7012       bool SuppressDiagnostic = false);
7013 
7014   DeclResult CheckClassTemplate(
7015       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7016       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7017       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7018       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7019       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7020       TemplateParameterList **OuterTemplateParamLists,
7021       SkipBodyInfo *SkipBody = nullptr);
7022 
7023   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7024                                                     QualType NTTPType,
7025                                                     SourceLocation Loc);
7026 
7027   /// Get a template argument mapping the given template parameter to itself,
7028   /// e.g. for X in \c template<int X>, this would return an expression template
7029   /// argument referencing X.
7030   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7031                                                      SourceLocation Location);
7032 
7033   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7034                                   TemplateArgumentListInfo &Out);
7035 
7036   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7037 
7038   void NoteAllFoundTemplates(TemplateName Name);
7039 
7040   QualType CheckTemplateIdType(TemplateName Template,
7041                                SourceLocation TemplateLoc,
7042                               TemplateArgumentListInfo &TemplateArgs);
7043 
7044   TypeResult
7045   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7046                       TemplateTy Template, IdentifierInfo *TemplateII,
7047                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7048                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7049                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7050 
7051   /// Parsed an elaborated-type-specifier that refers to a template-id,
7052   /// such as \c class T::template apply<U>.
7053   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7054                                     TypeSpecifierType TagSpec,
7055                                     SourceLocation TagLoc,
7056                                     CXXScopeSpec &SS,
7057                                     SourceLocation TemplateKWLoc,
7058                                     TemplateTy TemplateD,
7059                                     SourceLocation TemplateLoc,
7060                                     SourceLocation LAngleLoc,
7061                                     ASTTemplateArgsPtr TemplateArgsIn,
7062                                     SourceLocation RAngleLoc);
7063 
7064   DeclResult ActOnVarTemplateSpecialization(
7065       Scope *S, Declarator &D, TypeSourceInfo *DI,
7066       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7067       StorageClass SC, bool IsPartialSpecialization);
7068 
7069   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7070                                 SourceLocation TemplateLoc,
7071                                 SourceLocation TemplateNameLoc,
7072                                 const TemplateArgumentListInfo &TemplateArgs);
7073 
7074   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7075                                 const DeclarationNameInfo &NameInfo,
7076                                 VarTemplateDecl *Template,
7077                                 SourceLocation TemplateLoc,
7078                                 const TemplateArgumentListInfo *TemplateArgs);
7079 
7080   ExprResult
7081   CheckConceptTemplateId(const CXXScopeSpec &SS,
7082                          SourceLocation TemplateKWLoc,
7083                          const DeclarationNameInfo &ConceptNameInfo,
7084                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7085                          const TemplateArgumentListInfo *TemplateArgs);
7086 
7087   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7088 
7089   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7090                                  SourceLocation TemplateKWLoc,
7091                                  LookupResult &R,
7092                                  bool RequiresADL,
7093                                const TemplateArgumentListInfo *TemplateArgs);
7094 
7095   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7096                                           SourceLocation TemplateKWLoc,
7097                                const DeclarationNameInfo &NameInfo,
7098                                const TemplateArgumentListInfo *TemplateArgs);
7099 
7100   TemplateNameKind ActOnDependentTemplateName(
7101       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7102       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7103       TemplateTy &Template, bool AllowInjectedClassName = false);
7104 
7105   DeclResult ActOnClassTemplateSpecialization(
7106       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7107       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7108       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7109       MultiTemplateParamsArg TemplateParameterLists,
7110       SkipBodyInfo *SkipBody = nullptr);
7111 
7112   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7113                                               TemplateDecl *PrimaryTemplate,
7114                                               unsigned NumExplicitArgs,
7115                                               ArrayRef<TemplateArgument> Args);
7116   void CheckTemplatePartialSpecialization(
7117       ClassTemplatePartialSpecializationDecl *Partial);
7118   void CheckTemplatePartialSpecialization(
7119       VarTemplatePartialSpecializationDecl *Partial);
7120 
7121   Decl *ActOnTemplateDeclarator(Scope *S,
7122                                 MultiTemplateParamsArg TemplateParameterLists,
7123                                 Declarator &D);
7124 
7125   bool
7126   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7127                                          TemplateSpecializationKind NewTSK,
7128                                          NamedDecl *PrevDecl,
7129                                          TemplateSpecializationKind PrevTSK,
7130                                          SourceLocation PrevPtOfInstantiation,
7131                                          bool &SuppressNew);
7132 
7133   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7134                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
7135                                                     LookupResult &Previous);
7136 
7137   bool CheckFunctionTemplateSpecialization(
7138       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7139       LookupResult &Previous, bool QualifiedFriend = false);
7140   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7141   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7142 
7143   DeclResult ActOnExplicitInstantiation(
7144       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7145       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7146       TemplateTy Template, SourceLocation TemplateNameLoc,
7147       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7148       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7149 
7150   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7151                                         SourceLocation TemplateLoc,
7152                                         unsigned TagSpec, SourceLocation KWLoc,
7153                                         CXXScopeSpec &SS, IdentifierInfo *Name,
7154                                         SourceLocation NameLoc,
7155                                         const ParsedAttributesView &Attr);
7156 
7157   DeclResult ActOnExplicitInstantiation(Scope *S,
7158                                         SourceLocation ExternLoc,
7159                                         SourceLocation TemplateLoc,
7160                                         Declarator &D);
7161 
7162   TemplateArgumentLoc
7163   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7164                                           SourceLocation TemplateLoc,
7165                                           SourceLocation RAngleLoc,
7166                                           Decl *Param,
7167                                           SmallVectorImpl<TemplateArgument>
7168                                             &Converted,
7169                                           bool &HasDefaultArg);
7170 
7171   /// Specifies the context in which a particular template
7172   /// argument is being checked.
7173   enum CheckTemplateArgumentKind {
7174     /// The template argument was specified in the code or was
7175     /// instantiated with some deduced template arguments.
7176     CTAK_Specified,
7177 
7178     /// The template argument was deduced via template argument
7179     /// deduction.
7180     CTAK_Deduced,
7181 
7182     /// The template argument was deduced from an array bound
7183     /// via template argument deduction.
7184     CTAK_DeducedFromArrayBound
7185   };
7186 
7187   bool CheckTemplateArgument(NamedDecl *Param,
7188                              TemplateArgumentLoc &Arg,
7189                              NamedDecl *Template,
7190                              SourceLocation TemplateLoc,
7191                              SourceLocation RAngleLoc,
7192                              unsigned ArgumentPackIndex,
7193                            SmallVectorImpl<TemplateArgument> &Converted,
7194                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
7195 
7196   /// Check that the given template arguments can be be provided to
7197   /// the given template, converting the arguments along the way.
7198   ///
7199   /// \param Template The template to which the template arguments are being
7200   /// provided.
7201   ///
7202   /// \param TemplateLoc The location of the template name in the source.
7203   ///
7204   /// \param TemplateArgs The list of template arguments. If the template is
7205   /// a template template parameter, this function may extend the set of
7206   /// template arguments to also include substituted, defaulted template
7207   /// arguments.
7208   ///
7209   /// \param PartialTemplateArgs True if the list of template arguments is
7210   /// intentionally partial, e.g., because we're checking just the initial
7211   /// set of template arguments.
7212   ///
7213   /// \param Converted Will receive the converted, canonicalized template
7214   /// arguments.
7215   ///
7216   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7217   /// contain the converted forms of the template arguments as written.
7218   /// Otherwise, \p TemplateArgs will not be modified.
7219   ///
7220   /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7221   /// receive true if the cause for the error is the associated constraints of
7222   /// the template not being satisfied by the template arguments.
7223   ///
7224   /// \returns true if an error occurred, false otherwise.
7225   bool CheckTemplateArgumentList(TemplateDecl *Template,
7226                                  SourceLocation TemplateLoc,
7227                                  TemplateArgumentListInfo &TemplateArgs,
7228                                  bool PartialTemplateArgs,
7229                                  SmallVectorImpl<TemplateArgument> &Converted,
7230                                  bool UpdateArgsWithConversions = true,
7231                                  bool *ConstraintsNotSatisfied = nullptr);
7232 
7233   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7234                                  TemplateArgumentLoc &Arg,
7235                            SmallVectorImpl<TemplateArgument> &Converted);
7236 
7237   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
7238                              TypeSourceInfo *Arg);
7239   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7240                                    QualType InstantiatedParamType, Expr *Arg,
7241                                    TemplateArgument &Converted,
7242                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
7243   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7244                                      TemplateParameterList *Params,
7245                                      TemplateArgumentLoc &Arg);
7246 
7247   ExprResult
7248   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7249                                           QualType ParamType,
7250                                           SourceLocation Loc);
7251   ExprResult
7252   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7253                                               SourceLocation Loc);
7254 
7255   /// Enumeration describing how template parameter lists are compared
7256   /// for equality.
7257   enum TemplateParameterListEqualKind {
7258     /// We are matching the template parameter lists of two templates
7259     /// that might be redeclarations.
7260     ///
7261     /// \code
7262     /// template<typename T> struct X;
7263     /// template<typename T> struct X;
7264     /// \endcode
7265     TPL_TemplateMatch,
7266 
7267     /// We are matching the template parameter lists of two template
7268     /// template parameters as part of matching the template parameter lists
7269     /// of two templates that might be redeclarations.
7270     ///
7271     /// \code
7272     /// template<template<int I> class TT> struct X;
7273     /// template<template<int Value> class Other> struct X;
7274     /// \endcode
7275     TPL_TemplateTemplateParmMatch,
7276 
7277     /// We are matching the template parameter lists of a template
7278     /// template argument against the template parameter lists of a template
7279     /// template parameter.
7280     ///
7281     /// \code
7282     /// template<template<int Value> class Metafun> struct X;
7283     /// template<int Value> struct integer_c;
7284     /// X<integer_c> xic;
7285     /// \endcode
7286     TPL_TemplateTemplateArgumentMatch
7287   };
7288 
7289   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7290                                       TemplateParameterList *Old,
7291                                       bool Complain,
7292                                       TemplateParameterListEqualKind Kind,
7293                                       SourceLocation TemplateArgLoc
7294                                         = SourceLocation());
7295 
7296   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7297 
7298   /// Called when the parser has parsed a C++ typename
7299   /// specifier, e.g., "typename T::type".
7300   ///
7301   /// \param S The scope in which this typename type occurs.
7302   /// \param TypenameLoc the location of the 'typename' keyword
7303   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7304   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7305   /// \param IdLoc the location of the identifier.
7306   TypeResult
7307   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7308                     const CXXScopeSpec &SS, const IdentifierInfo &II,
7309                     SourceLocation IdLoc);
7310 
7311   /// Called when the parser has parsed a C++ typename
7312   /// specifier that ends in a template-id, e.g.,
7313   /// "typename MetaFun::template apply<T1, T2>".
7314   ///
7315   /// \param S The scope in which this typename type occurs.
7316   /// \param TypenameLoc the location of the 'typename' keyword
7317   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7318   /// \param TemplateLoc the location of the 'template' keyword, if any.
7319   /// \param TemplateName The template name.
7320   /// \param TemplateII The identifier used to name the template.
7321   /// \param TemplateIILoc The location of the template name.
7322   /// \param LAngleLoc The location of the opening angle bracket  ('<').
7323   /// \param TemplateArgs The template arguments.
7324   /// \param RAngleLoc The location of the closing angle bracket  ('>').
7325   TypeResult
7326   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7327                     const CXXScopeSpec &SS,
7328                     SourceLocation TemplateLoc,
7329                     TemplateTy TemplateName,
7330                     IdentifierInfo *TemplateII,
7331                     SourceLocation TemplateIILoc,
7332                     SourceLocation LAngleLoc,
7333                     ASTTemplateArgsPtr TemplateArgs,
7334                     SourceLocation RAngleLoc);
7335 
7336   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7337                              SourceLocation KeywordLoc,
7338                              NestedNameSpecifierLoc QualifierLoc,
7339                              const IdentifierInfo &II,
7340                              SourceLocation IILoc,
7341                              TypeSourceInfo **TSI,
7342                              bool DeducedTSTContext);
7343 
7344   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7345                              SourceLocation KeywordLoc,
7346                              NestedNameSpecifierLoc QualifierLoc,
7347                              const IdentifierInfo &II,
7348                              SourceLocation IILoc,
7349                              bool DeducedTSTContext = true);
7350 
7351 
7352   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7353                                                     SourceLocation Loc,
7354                                                     DeclarationName Name);
7355   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7356 
7357   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7358   bool RebuildTemplateParamsInCurrentInstantiation(
7359                                                 TemplateParameterList *Params);
7360 
7361   std::string
7362   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7363                                   const TemplateArgumentList &Args);
7364 
7365   std::string
7366   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7367                                   const TemplateArgument *Args,
7368                                   unsigned NumArgs);
7369 
7370   //===--------------------------------------------------------------------===//
7371   // C++ Concepts
7372   //===--------------------------------------------------------------------===//
7373   Decl *ActOnConceptDefinition(
7374       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7375       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7376 
7377   RequiresExprBodyDecl *
7378   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
7379                          ArrayRef<ParmVarDecl *> LocalParameters,
7380                          Scope *BodyScope);
7381   void ActOnFinishRequiresExpr();
7382   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
7383   concepts::Requirement *ActOnTypeRequirement(
7384       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7385       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
7386   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
7387                                                   SourceLocation NoexceptLoc);
7388   concepts::Requirement *
7389   ActOnCompoundRequirement(
7390       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7391       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
7392   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
7393   concepts::ExprRequirement *
7394   BuildExprRequirement(
7395       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
7396       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7397   concepts::ExprRequirement *
7398   BuildExprRequirement(
7399       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
7400       bool IsSatisfied, SourceLocation NoexceptLoc,
7401       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7402   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
7403   concepts::TypeRequirement *
7404   BuildTypeRequirement(
7405       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7406   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
7407   concepts::NestedRequirement *
7408   BuildNestedRequirement(
7409       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7410   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
7411                                RequiresExprBodyDecl *Body,
7412                                ArrayRef<ParmVarDecl *> LocalParameters,
7413                                ArrayRef<concepts::Requirement *> Requirements,
7414                                SourceLocation ClosingBraceLoc);
7415 
7416   //===--------------------------------------------------------------------===//
7417   // C++ Variadic Templates (C++0x [temp.variadic])
7418   //===--------------------------------------------------------------------===//
7419 
7420   /// Determine whether an unexpanded parameter pack might be permitted in this
7421   /// location. Useful for error recovery.
7422   bool isUnexpandedParameterPackPermitted();
7423 
7424   /// The context in which an unexpanded parameter pack is
7425   /// being diagnosed.
7426   ///
7427   /// Note that the values of this enumeration line up with the first
7428   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7429   enum UnexpandedParameterPackContext {
7430     /// An arbitrary expression.
7431     UPPC_Expression = 0,
7432 
7433     /// The base type of a class type.
7434     UPPC_BaseType,
7435 
7436     /// The type of an arbitrary declaration.
7437     UPPC_DeclarationType,
7438 
7439     /// The type of a data member.
7440     UPPC_DataMemberType,
7441 
7442     /// The size of a bit-field.
7443     UPPC_BitFieldWidth,
7444 
7445     /// The expression in a static assertion.
7446     UPPC_StaticAssertExpression,
7447 
7448     /// The fixed underlying type of an enumeration.
7449     UPPC_FixedUnderlyingType,
7450 
7451     /// The enumerator value.
7452     UPPC_EnumeratorValue,
7453 
7454     /// A using declaration.
7455     UPPC_UsingDeclaration,
7456 
7457     /// A friend declaration.
7458     UPPC_FriendDeclaration,
7459 
7460     /// A declaration qualifier.
7461     UPPC_DeclarationQualifier,
7462 
7463     /// An initializer.
7464     UPPC_Initializer,
7465 
7466     /// A default argument.
7467     UPPC_DefaultArgument,
7468 
7469     /// The type of a non-type template parameter.
7470     UPPC_NonTypeTemplateParameterType,
7471 
7472     /// The type of an exception.
7473     UPPC_ExceptionType,
7474 
7475     /// Partial specialization.
7476     UPPC_PartialSpecialization,
7477 
7478     /// Microsoft __if_exists.
7479     UPPC_IfExists,
7480 
7481     /// Microsoft __if_not_exists.
7482     UPPC_IfNotExists,
7483 
7484     /// Lambda expression.
7485     UPPC_Lambda,
7486 
7487     /// Block expression,
7488     UPPC_Block,
7489 
7490     /// A type constraint,
7491     UPPC_TypeConstraint
7492   };
7493 
7494   /// Diagnose unexpanded parameter packs.
7495   ///
7496   /// \param Loc The location at which we should emit the diagnostic.
7497   ///
7498   /// \param UPPC The context in which we are diagnosing unexpanded
7499   /// parameter packs.
7500   ///
7501   /// \param Unexpanded the set of unexpanded parameter packs.
7502   ///
7503   /// \returns true if an error occurred, false otherwise.
7504   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7505                                         UnexpandedParameterPackContext UPPC,
7506                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
7507 
7508   /// If the given type contains an unexpanded parameter pack,
7509   /// diagnose the error.
7510   ///
7511   /// \param Loc The source location where a diagnostc should be emitted.
7512   ///
7513   /// \param T The type that is being checked for unexpanded parameter
7514   /// packs.
7515   ///
7516   /// \returns true if an error occurred, false otherwise.
7517   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7518                                        UnexpandedParameterPackContext UPPC);
7519 
7520   /// If the given expression contains an unexpanded parameter
7521   /// pack, diagnose the error.
7522   ///
7523   /// \param E The expression that is being checked for unexpanded
7524   /// parameter packs.
7525   ///
7526   /// \returns true if an error occurred, false otherwise.
7527   bool DiagnoseUnexpandedParameterPack(Expr *E,
7528                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
7529 
7530   /// If the given nested-name-specifier contains an unexpanded
7531   /// parameter pack, diagnose the error.
7532   ///
7533   /// \param SS The nested-name-specifier that is being checked for
7534   /// unexpanded parameter packs.
7535   ///
7536   /// \returns true if an error occurred, false otherwise.
7537   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7538                                        UnexpandedParameterPackContext UPPC);
7539 
7540   /// If the given name contains an unexpanded parameter pack,
7541   /// diagnose the error.
7542   ///
7543   /// \param NameInfo The name (with source location information) that
7544   /// is being checked for unexpanded parameter packs.
7545   ///
7546   /// \returns true if an error occurred, false otherwise.
7547   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7548                                        UnexpandedParameterPackContext UPPC);
7549 
7550   /// If the given template name contains an unexpanded parameter pack,
7551   /// diagnose the error.
7552   ///
7553   /// \param Loc The location of the template name.
7554   ///
7555   /// \param Template The template name that is being checked for unexpanded
7556   /// parameter packs.
7557   ///
7558   /// \returns true if an error occurred, false otherwise.
7559   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
7560                                        TemplateName Template,
7561                                        UnexpandedParameterPackContext UPPC);
7562 
7563   /// If the given template argument contains an unexpanded parameter
7564   /// pack, diagnose the error.
7565   ///
7566   /// \param Arg The template argument that is being checked for unexpanded
7567   /// parameter packs.
7568   ///
7569   /// \returns true if an error occurred, false otherwise.
7570   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
7571                                        UnexpandedParameterPackContext UPPC);
7572 
7573   /// Collect the set of unexpanded parameter packs within the given
7574   /// template argument.
7575   ///
7576   /// \param Arg The template argument that will be traversed to find
7577   /// unexpanded parameter packs.
7578   void collectUnexpandedParameterPacks(TemplateArgument Arg,
7579                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7580 
7581   /// Collect the set of unexpanded parameter packs within the given
7582   /// template argument.
7583   ///
7584   /// \param Arg The template argument that will be traversed to find
7585   /// unexpanded parameter packs.
7586   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
7587                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7588 
7589   /// Collect the set of unexpanded parameter packs within the given
7590   /// type.
7591   ///
7592   /// \param T The type that will be traversed to find
7593   /// unexpanded parameter packs.
7594   void collectUnexpandedParameterPacks(QualType T,
7595                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7596 
7597   /// Collect the set of unexpanded parameter packs within the given
7598   /// type.
7599   ///
7600   /// \param TL The type that will be traversed to find
7601   /// unexpanded parameter packs.
7602   void collectUnexpandedParameterPacks(TypeLoc TL,
7603                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7604 
7605   /// Collect the set of unexpanded parameter packs within the given
7606   /// nested-name-specifier.
7607   ///
7608   /// \param NNS The nested-name-specifier that will be traversed to find
7609   /// unexpanded parameter packs.
7610   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
7611                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7612 
7613   /// Collect the set of unexpanded parameter packs within the given
7614   /// name.
7615   ///
7616   /// \param NameInfo The name that will be traversed to find
7617   /// unexpanded parameter packs.
7618   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
7619                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
7620 
7621   /// Invoked when parsing a template argument followed by an
7622   /// ellipsis, which creates a pack expansion.
7623   ///
7624   /// \param Arg The template argument preceding the ellipsis, which
7625   /// may already be invalid.
7626   ///
7627   /// \param EllipsisLoc The location of the ellipsis.
7628   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
7629                                             SourceLocation EllipsisLoc);
7630 
7631   /// Invoked when parsing a type followed by an ellipsis, which
7632   /// creates a pack expansion.
7633   ///
7634   /// \param Type The type preceding the ellipsis, which will become
7635   /// the pattern of the pack expansion.
7636   ///
7637   /// \param EllipsisLoc The location of the ellipsis.
7638   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
7639 
7640   /// Construct a pack expansion type from the pattern of the pack
7641   /// expansion.
7642   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
7643                                      SourceLocation EllipsisLoc,
7644                                      Optional<unsigned> NumExpansions);
7645 
7646   /// Construct a pack expansion type from the pattern of the pack
7647   /// expansion.
7648   QualType CheckPackExpansion(QualType Pattern,
7649                               SourceRange PatternRange,
7650                               SourceLocation EllipsisLoc,
7651                               Optional<unsigned> NumExpansions);
7652 
7653   /// Invoked when parsing an expression followed by an ellipsis, which
7654   /// creates a pack expansion.
7655   ///
7656   /// \param Pattern The expression preceding the ellipsis, which will become
7657   /// the pattern of the pack expansion.
7658   ///
7659   /// \param EllipsisLoc The location of the ellipsis.
7660   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
7661 
7662   /// Invoked when parsing an expression followed by an ellipsis, which
7663   /// creates a pack expansion.
7664   ///
7665   /// \param Pattern The expression preceding the ellipsis, which will become
7666   /// the pattern of the pack expansion.
7667   ///
7668   /// \param EllipsisLoc The location of the ellipsis.
7669   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
7670                                 Optional<unsigned> NumExpansions);
7671 
7672   /// Determine whether we could expand a pack expansion with the
7673   /// given set of parameter packs into separate arguments by repeatedly
7674   /// transforming the pattern.
7675   ///
7676   /// \param EllipsisLoc The location of the ellipsis that identifies the
7677   /// pack expansion.
7678   ///
7679   /// \param PatternRange The source range that covers the entire pattern of
7680   /// the pack expansion.
7681   ///
7682   /// \param Unexpanded The set of unexpanded parameter packs within the
7683   /// pattern.
7684   ///
7685   /// \param ShouldExpand Will be set to \c true if the transformer should
7686   /// expand the corresponding pack expansions into separate arguments. When
7687   /// set, \c NumExpansions must also be set.
7688   ///
7689   /// \param RetainExpansion Whether the caller should add an unexpanded
7690   /// pack expansion after all of the expanded arguments. This is used
7691   /// when extending explicitly-specified template argument packs per
7692   /// C++0x [temp.arg.explicit]p9.
7693   ///
7694   /// \param NumExpansions The number of separate arguments that will be in
7695   /// the expanded form of the corresponding pack expansion. This is both an
7696   /// input and an output parameter, which can be set by the caller if the
7697   /// number of expansions is known a priori (e.g., due to a prior substitution)
7698   /// and will be set by the callee when the number of expansions is known.
7699   /// The callee must set this value when \c ShouldExpand is \c true; it may
7700   /// set this value in other cases.
7701   ///
7702   /// \returns true if an error occurred (e.g., because the parameter packs
7703   /// are to be instantiated with arguments of different lengths), false
7704   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
7705   /// must be set.
7706   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
7707                                        SourceRange PatternRange,
7708                              ArrayRef<UnexpandedParameterPack> Unexpanded,
7709                              const MultiLevelTemplateArgumentList &TemplateArgs,
7710                                        bool &ShouldExpand,
7711                                        bool &RetainExpansion,
7712                                        Optional<unsigned> &NumExpansions);
7713 
7714   /// Determine the number of arguments in the given pack expansion
7715   /// type.
7716   ///
7717   /// This routine assumes that the number of arguments in the expansion is
7718   /// consistent across all of the unexpanded parameter packs in its pattern.
7719   ///
7720   /// Returns an empty Optional if the type can't be expanded.
7721   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
7722       const MultiLevelTemplateArgumentList &TemplateArgs);
7723 
7724   /// Determine whether the given declarator contains any unexpanded
7725   /// parameter packs.
7726   ///
7727   /// This routine is used by the parser to disambiguate function declarators
7728   /// with an ellipsis prior to the ')', e.g.,
7729   ///
7730   /// \code
7731   ///   void f(T...);
7732   /// \endcode
7733   ///
7734   /// To determine whether we have an (unnamed) function parameter pack or
7735   /// a variadic function.
7736   ///
7737   /// \returns true if the declarator contains any unexpanded parameter packs,
7738   /// false otherwise.
7739   bool containsUnexpandedParameterPacks(Declarator &D);
7740 
7741   /// Returns the pattern of the pack expansion for a template argument.
7742   ///
7743   /// \param OrigLoc The template argument to expand.
7744   ///
7745   /// \param Ellipsis Will be set to the location of the ellipsis.
7746   ///
7747   /// \param NumExpansions Will be set to the number of expansions that will
7748   /// be generated from this pack expansion, if known a priori.
7749   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
7750       TemplateArgumentLoc OrigLoc,
7751       SourceLocation &Ellipsis,
7752       Optional<unsigned> &NumExpansions) const;
7753 
7754   /// Given a template argument that contains an unexpanded parameter pack, but
7755   /// which has already been substituted, attempt to determine the number of
7756   /// elements that will be produced once this argument is fully-expanded.
7757   ///
7758   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
7759   /// avoid actually expanding the pack where possible.
7760   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
7761 
7762   //===--------------------------------------------------------------------===//
7763   // C++ Template Argument Deduction (C++ [temp.deduct])
7764   //===--------------------------------------------------------------------===//
7765 
7766   /// Adjust the type \p ArgFunctionType to match the calling convention,
7767   /// noreturn, and optionally the exception specification of \p FunctionType.
7768   /// Deduction often wants to ignore these properties when matching function
7769   /// types.
7770   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
7771                                bool AdjustExceptionSpec = false);
7772 
7773   /// Describes the result of template argument deduction.
7774   ///
7775   /// The TemplateDeductionResult enumeration describes the result of
7776   /// template argument deduction, as returned from
7777   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
7778   /// structure provides additional information about the results of
7779   /// template argument deduction, e.g., the deduced template argument
7780   /// list (if successful) or the specific template parameters or
7781   /// deduced arguments that were involved in the failure.
7782   enum TemplateDeductionResult {
7783     /// Template argument deduction was successful.
7784     TDK_Success = 0,
7785     /// The declaration was invalid; do nothing.
7786     TDK_Invalid,
7787     /// Template argument deduction exceeded the maximum template
7788     /// instantiation depth (which has already been diagnosed).
7789     TDK_InstantiationDepth,
7790     /// Template argument deduction did not deduce a value
7791     /// for every template parameter.
7792     TDK_Incomplete,
7793     /// Template argument deduction did not deduce a value for every
7794     /// expansion of an expanded template parameter pack.
7795     TDK_IncompletePack,
7796     /// Template argument deduction produced inconsistent
7797     /// deduced values for the given template parameter.
7798     TDK_Inconsistent,
7799     /// Template argument deduction failed due to inconsistent
7800     /// cv-qualifiers on a template parameter type that would
7801     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
7802     /// but were given a non-const "X".
7803     TDK_Underqualified,
7804     /// Substitution of the deduced template argument values
7805     /// resulted in an error.
7806     TDK_SubstitutionFailure,
7807     /// After substituting deduced template arguments, a dependent
7808     /// parameter type did not match the corresponding argument.
7809     TDK_DeducedMismatch,
7810     /// After substituting deduced template arguments, an element of
7811     /// a dependent parameter type did not match the corresponding element
7812     /// of the corresponding argument (when deducing from an initializer list).
7813     TDK_DeducedMismatchNested,
7814     /// A non-depnedent component of the parameter did not match the
7815     /// corresponding component of the argument.
7816     TDK_NonDeducedMismatch,
7817     /// When performing template argument deduction for a function
7818     /// template, there were too many call arguments.
7819     TDK_TooManyArguments,
7820     /// When performing template argument deduction for a function
7821     /// template, there were too few call arguments.
7822     TDK_TooFewArguments,
7823     /// The explicitly-specified template arguments were not valid
7824     /// template arguments for the given template.
7825     TDK_InvalidExplicitArguments,
7826     /// Checking non-dependent argument conversions failed.
7827     TDK_NonDependentConversionFailure,
7828     /// The deduced arguments did not satisfy the constraints associated
7829     /// with the template.
7830     TDK_ConstraintsNotSatisfied,
7831     /// Deduction failed; that's all we know.
7832     TDK_MiscellaneousDeductionFailure,
7833     /// CUDA Target attributes do not match.
7834     TDK_CUDATargetMismatch
7835   };
7836 
7837   TemplateDeductionResult
7838   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
7839                           const TemplateArgumentList &TemplateArgs,
7840                           sema::TemplateDeductionInfo &Info);
7841 
7842   TemplateDeductionResult
7843   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
7844                           const TemplateArgumentList &TemplateArgs,
7845                           sema::TemplateDeductionInfo &Info);
7846 
7847   TemplateDeductionResult SubstituteExplicitTemplateArguments(
7848       FunctionTemplateDecl *FunctionTemplate,
7849       TemplateArgumentListInfo &ExplicitTemplateArgs,
7850       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7851       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
7852       sema::TemplateDeductionInfo &Info);
7853 
7854   /// brief A function argument from which we performed template argument
7855   // deduction for a call.
7856   struct OriginalCallArg {
7857     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
7858                     unsigned ArgIdx, QualType OriginalArgType)
7859         : OriginalParamType(OriginalParamType),
7860           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
7861           OriginalArgType(OriginalArgType) {}
7862 
7863     QualType OriginalParamType;
7864     bool DecomposedParam;
7865     unsigned ArgIdx;
7866     QualType OriginalArgType;
7867   };
7868 
7869   TemplateDeductionResult FinishTemplateArgumentDeduction(
7870       FunctionTemplateDecl *FunctionTemplate,
7871       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
7872       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
7873       sema::TemplateDeductionInfo &Info,
7874       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
7875       bool PartialOverloading = false,
7876       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
7877 
7878   TemplateDeductionResult DeduceTemplateArguments(
7879       FunctionTemplateDecl *FunctionTemplate,
7880       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7881       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
7882       bool PartialOverloading,
7883       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
7884 
7885   TemplateDeductionResult
7886   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7887                           TemplateArgumentListInfo *ExplicitTemplateArgs,
7888                           QualType ArgFunctionType,
7889                           FunctionDecl *&Specialization,
7890                           sema::TemplateDeductionInfo &Info,
7891                           bool IsAddressOfFunction = false);
7892 
7893   TemplateDeductionResult
7894   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7895                           QualType ToType,
7896                           CXXConversionDecl *&Specialization,
7897                           sema::TemplateDeductionInfo &Info);
7898 
7899   TemplateDeductionResult
7900   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
7901                           TemplateArgumentListInfo *ExplicitTemplateArgs,
7902                           FunctionDecl *&Specialization,
7903                           sema::TemplateDeductionInfo &Info,
7904                           bool IsAddressOfFunction = false);
7905 
7906   /// Substitute Replacement for \p auto in \p TypeWithAuto
7907   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
7908   /// Substitute Replacement for auto in TypeWithAuto
7909   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
7910                                           QualType Replacement);
7911   /// Completely replace the \c auto in \p TypeWithAuto by
7912   /// \p Replacement. This does not retain any \c auto type sugar.
7913   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
7914 
7915   /// Result type of DeduceAutoType.
7916   enum DeduceAutoResult {
7917     DAR_Succeeded,
7918     DAR_Failed,
7919     DAR_FailedAlreadyDiagnosed
7920   };
7921 
7922   DeduceAutoResult
7923   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
7924                  Optional<unsigned> DependentDeductionDepth = None,
7925                  bool IgnoreConstraints = false);
7926   DeduceAutoResult
7927   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
7928                  Optional<unsigned> DependentDeductionDepth = None,
7929                  bool IgnoreConstraints = false);
7930   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
7931   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
7932                         bool Diagnose = true);
7933 
7934   /// Declare implicit deduction guides for a class template if we've
7935   /// not already done so.
7936   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
7937                                       SourceLocation Loc);
7938 
7939   QualType DeduceTemplateSpecializationFromInitializer(
7940       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
7941       const InitializationKind &Kind, MultiExprArg Init);
7942 
7943   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
7944                                         QualType Type, TypeSourceInfo *TSI,
7945                                         SourceRange Range, bool DirectInit,
7946                                         Expr *Init);
7947 
7948   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
7949 
7950   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
7951                                         SourceLocation ReturnLoc,
7952                                         Expr *&RetExpr, AutoType *AT);
7953 
7954   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
7955                                                    FunctionTemplateDecl *FT2,
7956                                                    SourceLocation Loc,
7957                                            TemplatePartialOrderingContext TPOC,
7958                                                    unsigned NumCallArguments1,
7959                                                    unsigned NumCallArguments2);
7960   UnresolvedSetIterator
7961   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
7962                      TemplateSpecCandidateSet &FailedCandidates,
7963                      SourceLocation Loc,
7964                      const PartialDiagnostic &NoneDiag,
7965                      const PartialDiagnostic &AmbigDiag,
7966                      const PartialDiagnostic &CandidateDiag,
7967                      bool Complain = true, QualType TargetType = QualType());
7968 
7969   ClassTemplatePartialSpecializationDecl *
7970   getMoreSpecializedPartialSpecialization(
7971                                   ClassTemplatePartialSpecializationDecl *PS1,
7972                                   ClassTemplatePartialSpecializationDecl *PS2,
7973                                   SourceLocation Loc);
7974 
7975   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
7976                                     sema::TemplateDeductionInfo &Info);
7977 
7978   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
7979       VarTemplatePartialSpecializationDecl *PS1,
7980       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
7981 
7982   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
7983                                     sema::TemplateDeductionInfo &Info);
7984 
7985   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
7986       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
7987 
7988   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7989                                   unsigned Depth, llvm::SmallBitVector &Used);
7990 
7991   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
7992                                   bool OnlyDeduced,
7993                                   unsigned Depth,
7994                                   llvm::SmallBitVector &Used);
7995   void MarkDeducedTemplateParameters(
7996                                   const FunctionTemplateDecl *FunctionTemplate,
7997                                   llvm::SmallBitVector &Deduced) {
7998     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
7999   }
8000   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8001                                   const FunctionTemplateDecl *FunctionTemplate,
8002                                   llvm::SmallBitVector &Deduced);
8003 
8004   //===--------------------------------------------------------------------===//
8005   // C++ Template Instantiation
8006   //
8007 
8008   MultiLevelTemplateArgumentList
8009   getTemplateInstantiationArgs(NamedDecl *D,
8010                                const TemplateArgumentList *Innermost = nullptr,
8011                                bool RelativeToPrimary = false,
8012                                const FunctionDecl *Pattern = nullptr);
8013 
8014   /// A context in which code is being synthesized (where a source location
8015   /// alone is not sufficient to identify the context). This covers template
8016   /// instantiation and various forms of implicitly-generated functions.
8017   struct CodeSynthesisContext {
8018     /// The kind of template instantiation we are performing
8019     enum SynthesisKind {
8020       /// We are instantiating a template declaration. The entity is
8021       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8022       TemplateInstantiation,
8023 
8024       /// We are instantiating a default argument for a template
8025       /// parameter. The Entity is the template parameter whose argument is
8026       /// being instantiated, the Template is the template, and the
8027       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8028       /// specified.
8029       DefaultTemplateArgumentInstantiation,
8030 
8031       /// We are instantiating a default argument for a function.
8032       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8033       /// provides the template arguments as specified.
8034       DefaultFunctionArgumentInstantiation,
8035 
8036       /// We are substituting explicit template arguments provided for
8037       /// a function template. The entity is a FunctionTemplateDecl.
8038       ExplicitTemplateArgumentSubstitution,
8039 
8040       /// We are substituting template argument determined as part of
8041       /// template argument deduction for either a class template
8042       /// partial specialization or a function template. The
8043       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8044       /// a TemplateDecl.
8045       DeducedTemplateArgumentSubstitution,
8046 
8047       /// We are substituting prior template arguments into a new
8048       /// template parameter. The template parameter itself is either a
8049       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8050       PriorTemplateArgumentSubstitution,
8051 
8052       /// We are checking the validity of a default template argument that
8053       /// has been used when naming a template-id.
8054       DefaultTemplateArgumentChecking,
8055 
8056       /// We are computing the exception specification for a defaulted special
8057       /// member function.
8058       ExceptionSpecEvaluation,
8059 
8060       /// We are instantiating the exception specification for a function
8061       /// template which was deferred until it was needed.
8062       ExceptionSpecInstantiation,
8063 
8064       /// We are instantiating a requirement of a requires expression.
8065       RequirementInstantiation,
8066 
8067       /// We are checking the satisfaction of a nested requirement of a requires
8068       /// expression.
8069       NestedRequirementConstraintsCheck,
8070 
8071       /// We are declaring an implicit special member function.
8072       DeclaringSpecialMember,
8073 
8074       /// We are declaring an implicit 'operator==' for a defaulted
8075       /// 'operator<=>'.
8076       DeclaringImplicitEqualityComparison,
8077 
8078       /// We are defining a synthesized function (such as a defaulted special
8079       /// member).
8080       DefiningSynthesizedFunction,
8081 
8082       // We are checking the constraints associated with a constrained entity or
8083       // the constraint expression of a concept. This includes the checks that
8084       // atomic constraints have the type 'bool' and that they can be constant
8085       // evaluated.
8086       ConstraintsCheck,
8087 
8088       // We are substituting template arguments into a constraint expression.
8089       ConstraintSubstitution,
8090 
8091       // We are normalizing a constraint expression.
8092       ConstraintNormalization,
8093 
8094       // We are substituting into the parameter mapping of an atomic constraint
8095       // during normalization.
8096       ParameterMappingSubstitution,
8097 
8098       /// We are rewriting a comparison operator in terms of an operator<=>.
8099       RewritingOperatorAsSpaceship,
8100 
8101       /// Added for Template instantiation observation.
8102       /// Memoization means we are _not_ instantiating a template because
8103       /// it is already instantiated (but we entered a context where we
8104       /// would have had to if it was not already instantiated).
8105       Memoization
8106     } Kind;
8107 
8108     /// Was the enclosing context a non-instantiation SFINAE context?
8109     bool SavedInNonInstantiationSFINAEContext;
8110 
8111     /// The point of instantiation or synthesis within the source code.
8112     SourceLocation PointOfInstantiation;
8113 
8114     /// The entity that is being synthesized.
8115     Decl *Entity;
8116 
8117     /// The template (or partial specialization) in which we are
8118     /// performing the instantiation, for substitutions of prior template
8119     /// arguments.
8120     NamedDecl *Template;
8121 
8122     /// The list of template arguments we are substituting, if they
8123     /// are not part of the entity.
8124     const TemplateArgument *TemplateArgs;
8125 
8126     // FIXME: Wrap this union around more members, or perhaps store the
8127     // kind-specific members in the RAII object owning the context.
8128     union {
8129       /// The number of template arguments in TemplateArgs.
8130       unsigned NumTemplateArgs;
8131 
8132       /// The special member being declared or defined.
8133       CXXSpecialMember SpecialMember;
8134     };
8135 
8136     ArrayRef<TemplateArgument> template_arguments() const {
8137       assert(Kind != DeclaringSpecialMember);
8138       return {TemplateArgs, NumTemplateArgs};
8139     }
8140 
8141     /// The template deduction info object associated with the
8142     /// substitution or checking of explicit or deduced template arguments.
8143     sema::TemplateDeductionInfo *DeductionInfo;
8144 
8145     /// The source range that covers the construct that cause
8146     /// the instantiation, e.g., the template-id that causes a class
8147     /// template instantiation.
8148     SourceRange InstantiationRange;
8149 
8150     CodeSynthesisContext()
8151         : Kind(TemplateInstantiation),
8152           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8153           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8154           DeductionInfo(nullptr) {}
8155 
8156     /// Determines whether this template is an actual instantiation
8157     /// that should be counted toward the maximum instantiation depth.
8158     bool isInstantiationRecord() const;
8159   };
8160 
8161   /// List of active code synthesis contexts.
8162   ///
8163   /// This vector is treated as a stack. As synthesis of one entity requires
8164   /// synthesis of another, additional contexts are pushed onto the stack.
8165   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8166 
8167   /// Specializations whose definitions are currently being instantiated.
8168   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8169 
8170   /// Non-dependent types used in templates that have already been instantiated
8171   /// by some template instantiation.
8172   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8173 
8174   /// Extra modules inspected when performing a lookup during a template
8175   /// instantiation. Computed lazily.
8176   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8177 
8178   /// Cache of additional modules that should be used for name lookup
8179   /// within the current template instantiation. Computed lazily; use
8180   /// getLookupModules() to get a complete set.
8181   llvm::DenseSet<Module*> LookupModulesCache;
8182 
8183   /// Get the set of additional modules that should be checked during
8184   /// name lookup. A module and its imports become visible when instanting a
8185   /// template defined within it.
8186   llvm::DenseSet<Module*> &getLookupModules();
8187 
8188   /// Map from the most recent declaration of a namespace to the most
8189   /// recent visible declaration of that namespace.
8190   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8191 
8192   /// Whether we are in a SFINAE context that is not associated with
8193   /// template instantiation.
8194   ///
8195   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8196   /// of a template instantiation or template argument deduction.
8197   bool InNonInstantiationSFINAEContext;
8198 
8199   /// The number of \p CodeSynthesisContexts that are not template
8200   /// instantiations and, therefore, should not be counted as part of the
8201   /// instantiation depth.
8202   ///
8203   /// When the instantiation depth reaches the user-configurable limit
8204   /// \p LangOptions::InstantiationDepth we will abort instantiation.
8205   // FIXME: Should we have a similar limit for other forms of synthesis?
8206   unsigned NonInstantiationEntries;
8207 
8208   /// The depth of the context stack at the point when the most recent
8209   /// error or warning was produced.
8210   ///
8211   /// This value is used to suppress printing of redundant context stacks
8212   /// when there are multiple errors or warnings in the same instantiation.
8213   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8214   unsigned LastEmittedCodeSynthesisContextDepth = 0;
8215 
8216   /// The template instantiation callbacks to trace or track
8217   /// instantiations (objects can be chained).
8218   ///
8219   /// This callbacks is used to print, trace or track template
8220   /// instantiations as they are being constructed.
8221   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8222       TemplateInstCallbacks;
8223 
8224   /// The current index into pack expansion arguments that will be
8225   /// used for substitution of parameter packs.
8226   ///
8227   /// The pack expansion index will be -1 to indicate that parameter packs
8228   /// should be instantiated as themselves. Otherwise, the index specifies
8229   /// which argument within the parameter pack will be used for substitution.
8230   int ArgumentPackSubstitutionIndex;
8231 
8232   /// RAII object used to change the argument pack substitution index
8233   /// within a \c Sema object.
8234   ///
8235   /// See \c ArgumentPackSubstitutionIndex for more information.
8236   class ArgumentPackSubstitutionIndexRAII {
8237     Sema &Self;
8238     int OldSubstitutionIndex;
8239 
8240   public:
8241     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8242       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8243       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8244     }
8245 
8246     ~ArgumentPackSubstitutionIndexRAII() {
8247       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8248     }
8249   };
8250 
8251   friend class ArgumentPackSubstitutionRAII;
8252 
8253   /// For each declaration that involved template argument deduction, the
8254   /// set of diagnostics that were suppressed during that template argument
8255   /// deduction.
8256   ///
8257   /// FIXME: Serialize this structure to the AST file.
8258   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8259     SuppressedDiagnosticsMap;
8260   SuppressedDiagnosticsMap SuppressedDiagnostics;
8261 
8262   /// A stack object to be created when performing template
8263   /// instantiation.
8264   ///
8265   /// Construction of an object of type \c InstantiatingTemplate
8266   /// pushes the current instantiation onto the stack of active
8267   /// instantiations. If the size of this stack exceeds the maximum
8268   /// number of recursive template instantiations, construction
8269   /// produces an error and evaluates true.
8270   ///
8271   /// Destruction of this object will pop the named instantiation off
8272   /// the stack.
8273   struct InstantiatingTemplate {
8274     /// Note that we are instantiating a class template,
8275     /// function template, variable template, alias template,
8276     /// or a member thereof.
8277     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8278                           Decl *Entity,
8279                           SourceRange InstantiationRange = SourceRange());
8280 
8281     struct ExceptionSpecification {};
8282     /// Note that we are instantiating an exception specification
8283     /// of a function template.
8284     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8285                           FunctionDecl *Entity, ExceptionSpecification,
8286                           SourceRange InstantiationRange = SourceRange());
8287 
8288     /// Note that we are instantiating a default argument in a
8289     /// template-id.
8290     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8291                           TemplateParameter Param, TemplateDecl *Template,
8292                           ArrayRef<TemplateArgument> TemplateArgs,
8293                           SourceRange InstantiationRange = SourceRange());
8294 
8295     /// Note that we are substituting either explicitly-specified or
8296     /// deduced template arguments during function template argument deduction.
8297     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8298                           FunctionTemplateDecl *FunctionTemplate,
8299                           ArrayRef<TemplateArgument> TemplateArgs,
8300                           CodeSynthesisContext::SynthesisKind Kind,
8301                           sema::TemplateDeductionInfo &DeductionInfo,
8302                           SourceRange InstantiationRange = SourceRange());
8303 
8304     /// Note that we are instantiating as part of template
8305     /// argument deduction for a class template declaration.
8306     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8307                           TemplateDecl *Template,
8308                           ArrayRef<TemplateArgument> TemplateArgs,
8309                           sema::TemplateDeductionInfo &DeductionInfo,
8310                           SourceRange InstantiationRange = SourceRange());
8311 
8312     /// Note that we are instantiating as part of template
8313     /// argument deduction for a class template partial
8314     /// specialization.
8315     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8316                           ClassTemplatePartialSpecializationDecl *PartialSpec,
8317                           ArrayRef<TemplateArgument> TemplateArgs,
8318                           sema::TemplateDeductionInfo &DeductionInfo,
8319                           SourceRange InstantiationRange = SourceRange());
8320 
8321     /// Note that we are instantiating as part of template
8322     /// argument deduction for a variable template partial
8323     /// specialization.
8324     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8325                           VarTemplatePartialSpecializationDecl *PartialSpec,
8326                           ArrayRef<TemplateArgument> TemplateArgs,
8327                           sema::TemplateDeductionInfo &DeductionInfo,
8328                           SourceRange InstantiationRange = SourceRange());
8329 
8330     /// Note that we are instantiating a default argument for a function
8331     /// parameter.
8332     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8333                           ParmVarDecl *Param,
8334                           ArrayRef<TemplateArgument> TemplateArgs,
8335                           SourceRange InstantiationRange = SourceRange());
8336 
8337     /// Note that we are substituting prior template arguments into a
8338     /// non-type parameter.
8339     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8340                           NamedDecl *Template,
8341                           NonTypeTemplateParmDecl *Param,
8342                           ArrayRef<TemplateArgument> TemplateArgs,
8343                           SourceRange InstantiationRange);
8344 
8345     /// Note that we are substituting prior template arguments into a
8346     /// template template parameter.
8347     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8348                           NamedDecl *Template,
8349                           TemplateTemplateParmDecl *Param,
8350                           ArrayRef<TemplateArgument> TemplateArgs,
8351                           SourceRange InstantiationRange);
8352 
8353     /// Note that we are checking the default template argument
8354     /// against the template parameter for a given template-id.
8355     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8356                           TemplateDecl *Template,
8357                           NamedDecl *Param,
8358                           ArrayRef<TemplateArgument> TemplateArgs,
8359                           SourceRange InstantiationRange);
8360 
8361     struct ConstraintsCheck {};
8362     /// \brief Note that we are checking the constraints associated with some
8363     /// constrained entity (a concept declaration or a template with associated
8364     /// constraints).
8365     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8366                           ConstraintsCheck, NamedDecl *Template,
8367                           ArrayRef<TemplateArgument> TemplateArgs,
8368                           SourceRange InstantiationRange);
8369 
8370     struct ConstraintSubstitution {};
8371     /// \brief Note that we are checking a constraint expression associated
8372     /// with a template declaration or as part of the satisfaction check of a
8373     /// concept.
8374     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8375                           ConstraintSubstitution, NamedDecl *Template,
8376                           sema::TemplateDeductionInfo &DeductionInfo,
8377                           SourceRange InstantiationRange);
8378 
8379     struct ConstraintNormalization {};
8380     /// \brief Note that we are normalizing a constraint expression.
8381     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8382                           ConstraintNormalization, NamedDecl *Template,
8383                           SourceRange InstantiationRange);
8384 
8385     struct ParameterMappingSubstitution {};
8386     /// \brief Note that we are subtituting into the parameter mapping of an
8387     /// atomic constraint during constraint normalization.
8388     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8389                           ParameterMappingSubstitution, NamedDecl *Template,
8390                           SourceRange InstantiationRange);
8391 
8392     /// \brief Note that we are substituting template arguments into a part of
8393     /// a requirement of a requires expression.
8394     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8395                           concepts::Requirement *Req,
8396                           sema::TemplateDeductionInfo &DeductionInfo,
8397                           SourceRange InstantiationRange = SourceRange());
8398 
8399     /// \brief Note that we are checking the satisfaction of the constraint
8400     /// expression inside of a nested requirement.
8401     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8402                           concepts::NestedRequirement *Req, ConstraintsCheck,
8403                           SourceRange InstantiationRange = SourceRange());
8404 
8405     /// Note that we have finished instantiating this template.
8406     void Clear();
8407 
8408     ~InstantiatingTemplate() { Clear(); }
8409 
8410     /// Determines whether we have exceeded the maximum
8411     /// recursive template instantiations.
8412     bool isInvalid() const { return Invalid; }
8413 
8414     /// Determine whether we are already instantiating this
8415     /// specialization in some surrounding active instantiation.
8416     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8417 
8418   private:
8419     Sema &SemaRef;
8420     bool Invalid;
8421     bool AlreadyInstantiating;
8422     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8423                                  SourceRange InstantiationRange);
8424 
8425     InstantiatingTemplate(
8426         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8427         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8428         Decl *Entity, NamedDecl *Template = nullptr,
8429         ArrayRef<TemplateArgument> TemplateArgs = None,
8430         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8431 
8432     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8433 
8434     InstantiatingTemplate&
8435     operator=(const InstantiatingTemplate&) = delete;
8436   };
8437 
8438   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8439   void popCodeSynthesisContext();
8440 
8441   /// Determine whether we are currently performing template instantiation.
8442   bool inTemplateInstantiation() const {
8443     return CodeSynthesisContexts.size() > NonInstantiationEntries;
8444   }
8445 
8446   void PrintContextStack() {
8447     if (!CodeSynthesisContexts.empty() &&
8448         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8449       PrintInstantiationStack();
8450       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8451     }
8452     if (PragmaAttributeCurrentTargetDecl)
8453       PrintPragmaAttributeInstantiationPoint();
8454   }
8455   void PrintInstantiationStack();
8456 
8457   void PrintPragmaAttributeInstantiationPoint();
8458 
8459   /// Determines whether we are currently in a context where
8460   /// template argument substitution failures are not considered
8461   /// errors.
8462   ///
8463   /// \returns An empty \c Optional if we're not in a SFINAE context.
8464   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8465   /// template-deduction context object, which can be used to capture
8466   /// diagnostics that will be suppressed.
8467   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8468 
8469   /// Determines whether we are currently in a context that
8470   /// is not evaluated as per C++ [expr] p5.
8471   bool isUnevaluatedContext() const {
8472     assert(!ExprEvalContexts.empty() &&
8473            "Must be in an expression evaluation context");
8474     return ExprEvalContexts.back().isUnevaluated();
8475   }
8476 
8477   /// RAII class used to determine whether SFINAE has
8478   /// trapped any errors that occur during template argument
8479   /// deduction.
8480   class SFINAETrap {
8481     Sema &SemaRef;
8482     unsigned PrevSFINAEErrors;
8483     bool PrevInNonInstantiationSFINAEContext;
8484     bool PrevAccessCheckingSFINAE;
8485     bool PrevLastDiagnosticIgnored;
8486 
8487   public:
8488     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
8489       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8490         PrevInNonInstantiationSFINAEContext(
8491                                       SemaRef.InNonInstantiationSFINAEContext),
8492         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8493         PrevLastDiagnosticIgnored(
8494             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
8495     {
8496       if (!SemaRef.isSFINAEContext())
8497         SemaRef.InNonInstantiationSFINAEContext = true;
8498       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
8499     }
8500 
8501     ~SFINAETrap() {
8502       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8503       SemaRef.InNonInstantiationSFINAEContext
8504         = PrevInNonInstantiationSFINAEContext;
8505       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8506       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8507           PrevLastDiagnosticIgnored);
8508     }
8509 
8510     /// Determine whether any SFINAE errors have been trapped.
8511     bool hasErrorOccurred() const {
8512       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8513     }
8514   };
8515 
8516   /// RAII class used to indicate that we are performing provisional
8517   /// semantic analysis to determine the validity of a construct, so
8518   /// typo-correction and diagnostics in the immediate context (not within
8519   /// implicitly-instantiated templates) should be suppressed.
8520   class TentativeAnalysisScope {
8521     Sema &SemaRef;
8522     // FIXME: Using a SFINAETrap for this is a hack.
8523     SFINAETrap Trap;
8524     bool PrevDisableTypoCorrection;
8525   public:
8526     explicit TentativeAnalysisScope(Sema &SemaRef)
8527         : SemaRef(SemaRef), Trap(SemaRef, true),
8528           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8529       SemaRef.DisableTypoCorrection = true;
8530     }
8531     ~TentativeAnalysisScope() {
8532       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8533     }
8534   };
8535 
8536   /// The current instantiation scope used to store local
8537   /// variables.
8538   LocalInstantiationScope *CurrentInstantiationScope;
8539 
8540   /// Tracks whether we are in a context where typo correction is
8541   /// disabled.
8542   bool DisableTypoCorrection;
8543 
8544   /// The number of typos corrected by CorrectTypo.
8545   unsigned TyposCorrected;
8546 
8547   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8548   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8549 
8550   /// A cache containing identifiers for which typo correction failed and
8551   /// their locations, so that repeated attempts to correct an identifier in a
8552   /// given location are ignored if typo correction already failed for it.
8553   IdentifierSourceLocations TypoCorrectionFailures;
8554 
8555   /// Worker object for performing CFG-based warnings.
8556   sema::AnalysisBasedWarnings AnalysisWarnings;
8557   threadSafety::BeforeSet *ThreadSafetyDeclCache;
8558 
8559   /// An entity for which implicit template instantiation is required.
8560   ///
8561   /// The source location associated with the declaration is the first place in
8562   /// the source code where the declaration was "used". It is not necessarily
8563   /// the point of instantiation (which will be either before or after the
8564   /// namespace-scope declaration that triggered this implicit instantiation),
8565   /// However, it is the location that diagnostics should generally refer to,
8566   /// because users will need to know what code triggered the instantiation.
8567   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
8568 
8569   /// The queue of implicit template instantiations that are required
8570   /// but have not yet been performed.
8571   std::deque<PendingImplicitInstantiation> PendingInstantiations;
8572 
8573   /// Queue of implicit template instantiations that cannot be performed
8574   /// eagerly.
8575   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
8576 
8577   class GlobalEagerInstantiationScope {
8578   public:
8579     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
8580         : S(S), Enabled(Enabled) {
8581       if (!Enabled) return;
8582 
8583       SavedPendingInstantiations.swap(S.PendingInstantiations);
8584       SavedVTableUses.swap(S.VTableUses);
8585     }
8586 
8587     void perform() {
8588       if (Enabled) {
8589         S.DefineUsedVTables();
8590         S.PerformPendingInstantiations();
8591       }
8592     }
8593 
8594     ~GlobalEagerInstantiationScope() {
8595       if (!Enabled) return;
8596 
8597       // Restore the set of pending vtables.
8598       assert(S.VTableUses.empty() &&
8599              "VTableUses should be empty before it is discarded.");
8600       S.VTableUses.swap(SavedVTableUses);
8601 
8602       // Restore the set of pending implicit instantiations.
8603       assert(S.PendingInstantiations.empty() &&
8604              "PendingInstantiations should be empty before it is discarded.");
8605       S.PendingInstantiations.swap(SavedPendingInstantiations);
8606     }
8607 
8608   private:
8609     Sema &S;
8610     SmallVector<VTableUse, 16> SavedVTableUses;
8611     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
8612     bool Enabled;
8613   };
8614 
8615   /// The queue of implicit template instantiations that are required
8616   /// and must be performed within the current local scope.
8617   ///
8618   /// This queue is only used for member functions of local classes in
8619   /// templates, which must be instantiated in the same scope as their
8620   /// enclosing function, so that they can reference function-local
8621   /// types, static variables, enumerators, etc.
8622   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
8623 
8624   class LocalEagerInstantiationScope {
8625   public:
8626     LocalEagerInstantiationScope(Sema &S) : S(S) {
8627       SavedPendingLocalImplicitInstantiations.swap(
8628           S.PendingLocalImplicitInstantiations);
8629     }
8630 
8631     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
8632 
8633     ~LocalEagerInstantiationScope() {
8634       assert(S.PendingLocalImplicitInstantiations.empty() &&
8635              "there shouldn't be any pending local implicit instantiations");
8636       SavedPendingLocalImplicitInstantiations.swap(
8637           S.PendingLocalImplicitInstantiations);
8638     }
8639 
8640   private:
8641     Sema &S;
8642     std::deque<PendingImplicitInstantiation>
8643         SavedPendingLocalImplicitInstantiations;
8644   };
8645 
8646   /// A helper class for building up ExtParameterInfos.
8647   class ExtParameterInfoBuilder {
8648     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
8649     bool HasInteresting = false;
8650 
8651   public:
8652     /// Set the ExtParameterInfo for the parameter at the given index,
8653     ///
8654     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
8655       assert(Infos.size() <= index);
8656       Infos.resize(index);
8657       Infos.push_back(info);
8658 
8659       if (!HasInteresting)
8660         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
8661     }
8662 
8663     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
8664     /// ExtParameterInfo array we've built up.
8665     const FunctionProtoType::ExtParameterInfo *
8666     getPointerOrNull(unsigned numParams) {
8667       if (!HasInteresting) return nullptr;
8668       Infos.resize(numParams);
8669       return Infos.data();
8670     }
8671   };
8672 
8673   void PerformPendingInstantiations(bool LocalOnly = false);
8674 
8675   TypeSourceInfo *SubstType(TypeSourceInfo *T,
8676                             const MultiLevelTemplateArgumentList &TemplateArgs,
8677                             SourceLocation Loc, DeclarationName Entity,
8678                             bool AllowDeducedTST = false);
8679 
8680   QualType SubstType(QualType T,
8681                      const MultiLevelTemplateArgumentList &TemplateArgs,
8682                      SourceLocation Loc, DeclarationName Entity);
8683 
8684   TypeSourceInfo *SubstType(TypeLoc TL,
8685                             const MultiLevelTemplateArgumentList &TemplateArgs,
8686                             SourceLocation Loc, DeclarationName Entity);
8687 
8688   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
8689                             const MultiLevelTemplateArgumentList &TemplateArgs,
8690                                         SourceLocation Loc,
8691                                         DeclarationName Entity,
8692                                         CXXRecordDecl *ThisContext,
8693                                         Qualifiers ThisTypeQuals);
8694   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
8695                           const MultiLevelTemplateArgumentList &Args);
8696   bool SubstExceptionSpec(SourceLocation Loc,
8697                           FunctionProtoType::ExceptionSpecInfo &ESI,
8698                           SmallVectorImpl<QualType> &ExceptionStorage,
8699                           const MultiLevelTemplateArgumentList &Args);
8700   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
8701                             const MultiLevelTemplateArgumentList &TemplateArgs,
8702                                 int indexAdjustment,
8703                                 Optional<unsigned> NumExpansions,
8704                                 bool ExpectParameterPack);
8705   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
8706                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
8707                       const MultiLevelTemplateArgumentList &TemplateArgs,
8708                       SmallVectorImpl<QualType> &ParamTypes,
8709                       SmallVectorImpl<ParmVarDecl *> *OutParams,
8710                       ExtParameterInfoBuilder &ParamInfos);
8711   ExprResult SubstExpr(Expr *E,
8712                        const MultiLevelTemplateArgumentList &TemplateArgs);
8713 
8714   /// Substitute the given template arguments into a list of
8715   /// expressions, expanding pack expansions if required.
8716   ///
8717   /// \param Exprs The list of expressions to substitute into.
8718   ///
8719   /// \param IsCall Whether this is some form of call, in which case
8720   /// default arguments will be dropped.
8721   ///
8722   /// \param TemplateArgs The set of template arguments to substitute.
8723   ///
8724   /// \param Outputs Will receive all of the substituted arguments.
8725   ///
8726   /// \returns true if an error occurred, false otherwise.
8727   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
8728                   const MultiLevelTemplateArgumentList &TemplateArgs,
8729                   SmallVectorImpl<Expr *> &Outputs);
8730 
8731   StmtResult SubstStmt(Stmt *S,
8732                        const MultiLevelTemplateArgumentList &TemplateArgs);
8733 
8734   TemplateParameterList *
8735   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
8736                       const MultiLevelTemplateArgumentList &TemplateArgs);
8737 
8738   bool
8739   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
8740                          const MultiLevelTemplateArgumentList &TemplateArgs,
8741                          TemplateArgumentListInfo &Outputs);
8742 
8743 
8744   Decl *SubstDecl(Decl *D, DeclContext *Owner,
8745                   const MultiLevelTemplateArgumentList &TemplateArgs);
8746 
8747   /// Substitute the name and return type of a defaulted 'operator<=>' to form
8748   /// an implicit 'operator=='.
8749   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
8750                                            FunctionDecl *Spaceship);
8751 
8752   ExprResult SubstInitializer(Expr *E,
8753                        const MultiLevelTemplateArgumentList &TemplateArgs,
8754                        bool CXXDirectInit);
8755 
8756   bool
8757   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
8758                       CXXRecordDecl *Pattern,
8759                       const MultiLevelTemplateArgumentList &TemplateArgs);
8760 
8761   bool
8762   InstantiateClass(SourceLocation PointOfInstantiation,
8763                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
8764                    const MultiLevelTemplateArgumentList &TemplateArgs,
8765                    TemplateSpecializationKind TSK,
8766                    bool Complain = true);
8767 
8768   bool InstantiateEnum(SourceLocation PointOfInstantiation,
8769                        EnumDecl *Instantiation, EnumDecl *Pattern,
8770                        const MultiLevelTemplateArgumentList &TemplateArgs,
8771                        TemplateSpecializationKind TSK);
8772 
8773   bool InstantiateInClassInitializer(
8774       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
8775       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
8776 
8777   struct LateInstantiatedAttribute {
8778     const Attr *TmplAttr;
8779     LocalInstantiationScope *Scope;
8780     Decl *NewDecl;
8781 
8782     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
8783                               Decl *D)
8784       : TmplAttr(A), Scope(S), NewDecl(D)
8785     { }
8786   };
8787   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
8788 
8789   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
8790                         const Decl *Pattern, Decl *Inst,
8791                         LateInstantiatedAttrVec *LateAttrs = nullptr,
8792                         LocalInstantiationScope *OuterMostScope = nullptr);
8793 
8794   void
8795   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
8796                           const Decl *Pattern, Decl *Inst,
8797                           LateInstantiatedAttrVec *LateAttrs = nullptr,
8798                           LocalInstantiationScope *OuterMostScope = nullptr);
8799 
8800   bool usesPartialOrExplicitSpecialization(
8801       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
8802 
8803   bool
8804   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
8805                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
8806                            TemplateSpecializationKind TSK,
8807                            bool Complain = true);
8808 
8809   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
8810                                CXXRecordDecl *Instantiation,
8811                             const MultiLevelTemplateArgumentList &TemplateArgs,
8812                                TemplateSpecializationKind TSK);
8813 
8814   void InstantiateClassTemplateSpecializationMembers(
8815                                           SourceLocation PointOfInstantiation,
8816                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
8817                                                 TemplateSpecializationKind TSK);
8818 
8819   NestedNameSpecifierLoc
8820   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
8821                            const MultiLevelTemplateArgumentList &TemplateArgs);
8822 
8823   DeclarationNameInfo
8824   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
8825                            const MultiLevelTemplateArgumentList &TemplateArgs);
8826   TemplateName
8827   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
8828                     SourceLocation Loc,
8829                     const MultiLevelTemplateArgumentList &TemplateArgs);
8830   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
8831              TemplateArgumentListInfo &Result,
8832              const MultiLevelTemplateArgumentList &TemplateArgs);
8833 
8834   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
8835                                 FunctionDecl *Function);
8836   bool CheckInstantiatedFunctionTemplateConstraints(
8837       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
8838       ArrayRef<TemplateArgument> TemplateArgs,
8839       ConstraintSatisfaction &Satisfaction);
8840   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
8841                                                const TemplateArgumentList *Args,
8842                                                SourceLocation Loc);
8843   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
8844                                      FunctionDecl *Function,
8845                                      bool Recursive = false,
8846                                      bool DefinitionRequired = false,
8847                                      bool AtEndOfTU = false);
8848   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
8849       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
8850       const TemplateArgumentList &TemplateArgList,
8851       const TemplateArgumentListInfo &TemplateArgsInfo,
8852       SmallVectorImpl<TemplateArgument> &Converted,
8853       SourceLocation PointOfInstantiation, void *InsertPos,
8854       LateInstantiatedAttrVec *LateAttrs = nullptr,
8855       LocalInstantiationScope *StartingScope = nullptr);
8856   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
8857       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
8858       const MultiLevelTemplateArgumentList &TemplateArgs);
8859   void
8860   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
8861                              const MultiLevelTemplateArgumentList &TemplateArgs,
8862                              LateInstantiatedAttrVec *LateAttrs,
8863                              DeclContext *Owner,
8864                              LocalInstantiationScope *StartingScope,
8865                              bool InstantiatingVarTemplate = false,
8866                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
8867 
8868   VarDecl *getVarTemplateSpecialization(
8869       VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
8870       const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
8871 
8872   void InstantiateVariableInitializer(
8873       VarDecl *Var, VarDecl *OldVar,
8874       const MultiLevelTemplateArgumentList &TemplateArgs);
8875   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
8876                                      VarDecl *Var, bool Recursive = false,
8877                                      bool DefinitionRequired = false,
8878                                      bool AtEndOfTU = false);
8879 
8880   void InstantiateMemInitializers(CXXConstructorDecl *New,
8881                                   const CXXConstructorDecl *Tmpl,
8882                             const MultiLevelTemplateArgumentList &TemplateArgs);
8883 
8884   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
8885                           const MultiLevelTemplateArgumentList &TemplateArgs,
8886                           bool FindingInstantiatedContext = false);
8887   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
8888                           const MultiLevelTemplateArgumentList &TemplateArgs);
8889 
8890   // Objective-C declarations.
8891   enum ObjCContainerKind {
8892     OCK_None = -1,
8893     OCK_Interface = 0,
8894     OCK_Protocol,
8895     OCK_Category,
8896     OCK_ClassExtension,
8897     OCK_Implementation,
8898     OCK_CategoryImplementation
8899   };
8900   ObjCContainerKind getObjCContainerKind() const;
8901 
8902   DeclResult actOnObjCTypeParam(Scope *S,
8903                                 ObjCTypeParamVariance variance,
8904                                 SourceLocation varianceLoc,
8905                                 unsigned index,
8906                                 IdentifierInfo *paramName,
8907                                 SourceLocation paramLoc,
8908                                 SourceLocation colonLoc,
8909                                 ParsedType typeBound);
8910 
8911   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
8912                                             ArrayRef<Decl *> typeParams,
8913                                             SourceLocation rAngleLoc);
8914   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
8915 
8916   Decl *ActOnStartClassInterface(
8917       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8918       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8919       IdentifierInfo *SuperName, SourceLocation SuperLoc,
8920       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
8921       Decl *const *ProtoRefs, unsigned NumProtoRefs,
8922       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8923       const ParsedAttributesView &AttrList);
8924 
8925   void ActOnSuperClassOfClassInterface(Scope *S,
8926                                        SourceLocation AtInterfaceLoc,
8927                                        ObjCInterfaceDecl *IDecl,
8928                                        IdentifierInfo *ClassName,
8929                                        SourceLocation ClassLoc,
8930                                        IdentifierInfo *SuperName,
8931                                        SourceLocation SuperLoc,
8932                                        ArrayRef<ParsedType> SuperTypeArgs,
8933                                        SourceRange SuperTypeArgsRange);
8934 
8935   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
8936                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
8937                                IdentifierInfo *SuperName,
8938                                SourceLocation SuperLoc);
8939 
8940   Decl *ActOnCompatibilityAlias(
8941                     SourceLocation AtCompatibilityAliasLoc,
8942                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
8943                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
8944 
8945   bool CheckForwardProtocolDeclarationForCircularDependency(
8946     IdentifierInfo *PName,
8947     SourceLocation &PLoc, SourceLocation PrevLoc,
8948     const ObjCList<ObjCProtocolDecl> &PList);
8949 
8950   Decl *ActOnStartProtocolInterface(
8951       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
8952       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
8953       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
8954       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
8955 
8956   Decl *ActOnStartCategoryInterface(
8957       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
8958       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
8959       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
8960       Decl *const *ProtoRefs, unsigned NumProtoRefs,
8961       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
8962       const ParsedAttributesView &AttrList);
8963 
8964   Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
8965                                       IdentifierInfo *ClassName,
8966                                       SourceLocation ClassLoc,
8967                                       IdentifierInfo *SuperClassname,
8968                                       SourceLocation SuperClassLoc,
8969                                       const ParsedAttributesView &AttrList);
8970 
8971   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
8972                                          IdentifierInfo *ClassName,
8973                                          SourceLocation ClassLoc,
8974                                          IdentifierInfo *CatName,
8975                                          SourceLocation CatLoc,
8976                                          const ParsedAttributesView &AttrList);
8977 
8978   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
8979                                                ArrayRef<Decl *> Decls);
8980 
8981   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
8982                    IdentifierInfo **IdentList,
8983                    SourceLocation *IdentLocs,
8984                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
8985                    unsigned NumElts);
8986 
8987   DeclGroupPtrTy
8988   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
8989                                   ArrayRef<IdentifierLocPair> IdentList,
8990                                   const ParsedAttributesView &attrList);
8991 
8992   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
8993                                ArrayRef<IdentifierLocPair> ProtocolId,
8994                                SmallVectorImpl<Decl *> &Protocols);
8995 
8996   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
8997                                     SourceLocation ProtocolLoc,
8998                                     IdentifierInfo *TypeArgId,
8999                                     SourceLocation TypeArgLoc,
9000                                     bool SelectProtocolFirst = false);
9001 
9002   /// Given a list of identifiers (and their locations), resolve the
9003   /// names to either Objective-C protocol qualifiers or type
9004   /// arguments, as appropriate.
9005   void actOnObjCTypeArgsOrProtocolQualifiers(
9006          Scope *S,
9007          ParsedType baseType,
9008          SourceLocation lAngleLoc,
9009          ArrayRef<IdentifierInfo *> identifiers,
9010          ArrayRef<SourceLocation> identifierLocs,
9011          SourceLocation rAngleLoc,
9012          SourceLocation &typeArgsLAngleLoc,
9013          SmallVectorImpl<ParsedType> &typeArgs,
9014          SourceLocation &typeArgsRAngleLoc,
9015          SourceLocation &protocolLAngleLoc,
9016          SmallVectorImpl<Decl *> &protocols,
9017          SourceLocation &protocolRAngleLoc,
9018          bool warnOnIncompleteProtocols);
9019 
9020   /// Build a an Objective-C protocol-qualified 'id' type where no
9021   /// base type was specified.
9022   TypeResult actOnObjCProtocolQualifierType(
9023                SourceLocation lAngleLoc,
9024                ArrayRef<Decl *> protocols,
9025                ArrayRef<SourceLocation> protocolLocs,
9026                SourceLocation rAngleLoc);
9027 
9028   /// Build a specialized and/or protocol-qualified Objective-C type.
9029   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9030                Scope *S,
9031                SourceLocation Loc,
9032                ParsedType BaseType,
9033                SourceLocation TypeArgsLAngleLoc,
9034                ArrayRef<ParsedType> TypeArgs,
9035                SourceLocation TypeArgsRAngleLoc,
9036                SourceLocation ProtocolLAngleLoc,
9037                ArrayRef<Decl *> Protocols,
9038                ArrayRef<SourceLocation> ProtocolLocs,
9039                SourceLocation ProtocolRAngleLoc);
9040 
9041   /// Build an Objective-C type parameter type.
9042   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9043                                   SourceLocation ProtocolLAngleLoc,
9044                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9045                                   ArrayRef<SourceLocation> ProtocolLocs,
9046                                   SourceLocation ProtocolRAngleLoc,
9047                                   bool FailOnError = false);
9048 
9049   /// Build an Objective-C object pointer type.
9050   QualType BuildObjCObjectType(QualType BaseType,
9051                                SourceLocation Loc,
9052                                SourceLocation TypeArgsLAngleLoc,
9053                                ArrayRef<TypeSourceInfo *> TypeArgs,
9054                                SourceLocation TypeArgsRAngleLoc,
9055                                SourceLocation ProtocolLAngleLoc,
9056                                ArrayRef<ObjCProtocolDecl *> Protocols,
9057                                ArrayRef<SourceLocation> ProtocolLocs,
9058                                SourceLocation ProtocolRAngleLoc,
9059                                bool FailOnError = false);
9060 
9061   /// Ensure attributes are consistent with type.
9062   /// \param [in, out] Attributes The attributes to check; they will
9063   /// be modified to be consistent with \p PropertyTy.
9064   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9065                                    SourceLocation Loc,
9066                                    unsigned &Attributes,
9067                                    bool propertyInPrimaryClass);
9068 
9069   /// Process the specified property declaration and create decls for the
9070   /// setters and getters as needed.
9071   /// \param property The property declaration being processed
9072   void ProcessPropertyDecl(ObjCPropertyDecl *property);
9073 
9074 
9075   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9076                                 ObjCPropertyDecl *SuperProperty,
9077                                 const IdentifierInfo *Name,
9078                                 bool OverridingProtocolProperty);
9079 
9080   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9081                                         ObjCInterfaceDecl *ID);
9082 
9083   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9084                    ArrayRef<Decl *> allMethods = None,
9085                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
9086 
9087   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9088                       SourceLocation LParenLoc,
9089                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
9090                       Selector GetterSel, Selector SetterSel,
9091                       tok::ObjCKeywordKind MethodImplKind,
9092                       DeclContext *lexicalDC = nullptr);
9093 
9094   Decl *ActOnPropertyImplDecl(Scope *S,
9095                               SourceLocation AtLoc,
9096                               SourceLocation PropertyLoc,
9097                               bool ImplKind,
9098                               IdentifierInfo *PropertyId,
9099                               IdentifierInfo *PropertyIvar,
9100                               SourceLocation PropertyIvarLoc,
9101                               ObjCPropertyQueryKind QueryKind);
9102 
9103   enum ObjCSpecialMethodKind {
9104     OSMK_None,
9105     OSMK_Alloc,
9106     OSMK_New,
9107     OSMK_Copy,
9108     OSMK_RetainingInit,
9109     OSMK_NonRetainingInit
9110   };
9111 
9112   struct ObjCArgInfo {
9113     IdentifierInfo *Name;
9114     SourceLocation NameLoc;
9115     // The Type is null if no type was specified, and the DeclSpec is invalid
9116     // in this case.
9117     ParsedType Type;
9118     ObjCDeclSpec DeclSpec;
9119 
9120     /// ArgAttrs - Attribute list for this argument.
9121     ParsedAttributesView ArgAttrs;
9122   };
9123 
9124   Decl *ActOnMethodDeclaration(
9125       Scope *S,
9126       SourceLocation BeginLoc, // location of the + or -.
9127       SourceLocation EndLoc,   // location of the ; or {.
9128       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9129       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9130       // optional arguments. The number of types/arguments is obtained
9131       // from the Sel.getNumArgs().
9132       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9133       unsigned CNumArgs, // c-style args
9134       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9135       bool isVariadic, bool MethodDefinition);
9136 
9137   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9138                                               const ObjCObjectPointerType *OPT,
9139                                               bool IsInstance);
9140   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9141                                            bool IsInstance);
9142 
9143   bool CheckARCMethodDecl(ObjCMethodDecl *method);
9144   bool inferObjCARCLifetime(ValueDecl *decl);
9145 
9146   void deduceOpenCLAddressSpace(ValueDecl *decl);
9147 
9148   ExprResult
9149   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9150                             Expr *BaseExpr,
9151                             SourceLocation OpLoc,
9152                             DeclarationName MemberName,
9153                             SourceLocation MemberLoc,
9154                             SourceLocation SuperLoc, QualType SuperType,
9155                             bool Super);
9156 
9157   ExprResult
9158   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9159                             IdentifierInfo &propertyName,
9160                             SourceLocation receiverNameLoc,
9161                             SourceLocation propertyNameLoc);
9162 
9163   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9164 
9165   /// Describes the kind of message expression indicated by a message
9166   /// send that starts with an identifier.
9167   enum ObjCMessageKind {
9168     /// The message is sent to 'super'.
9169     ObjCSuperMessage,
9170     /// The message is an instance message.
9171     ObjCInstanceMessage,
9172     /// The message is a class message, and the identifier is a type
9173     /// name.
9174     ObjCClassMessage
9175   };
9176 
9177   ObjCMessageKind getObjCMessageKind(Scope *S,
9178                                      IdentifierInfo *Name,
9179                                      SourceLocation NameLoc,
9180                                      bool IsSuper,
9181                                      bool HasTrailingDot,
9182                                      ParsedType &ReceiverType);
9183 
9184   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9185                                Selector Sel,
9186                                SourceLocation LBracLoc,
9187                                ArrayRef<SourceLocation> SelectorLocs,
9188                                SourceLocation RBracLoc,
9189                                MultiExprArg Args);
9190 
9191   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9192                                QualType ReceiverType,
9193                                SourceLocation SuperLoc,
9194                                Selector Sel,
9195                                ObjCMethodDecl *Method,
9196                                SourceLocation LBracLoc,
9197                                ArrayRef<SourceLocation> SelectorLocs,
9198                                SourceLocation RBracLoc,
9199                                MultiExprArg Args,
9200                                bool isImplicit = false);
9201 
9202   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9203                                        bool isSuperReceiver,
9204                                        SourceLocation Loc,
9205                                        Selector Sel,
9206                                        ObjCMethodDecl *Method,
9207                                        MultiExprArg Args);
9208 
9209   ExprResult ActOnClassMessage(Scope *S,
9210                                ParsedType Receiver,
9211                                Selector Sel,
9212                                SourceLocation LBracLoc,
9213                                ArrayRef<SourceLocation> SelectorLocs,
9214                                SourceLocation RBracLoc,
9215                                MultiExprArg Args);
9216 
9217   ExprResult BuildInstanceMessage(Expr *Receiver,
9218                                   QualType ReceiverType,
9219                                   SourceLocation SuperLoc,
9220                                   Selector Sel,
9221                                   ObjCMethodDecl *Method,
9222                                   SourceLocation LBracLoc,
9223                                   ArrayRef<SourceLocation> SelectorLocs,
9224                                   SourceLocation RBracLoc,
9225                                   MultiExprArg Args,
9226                                   bool isImplicit = false);
9227 
9228   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9229                                           QualType ReceiverType,
9230                                           SourceLocation Loc,
9231                                           Selector Sel,
9232                                           ObjCMethodDecl *Method,
9233                                           MultiExprArg Args);
9234 
9235   ExprResult ActOnInstanceMessage(Scope *S,
9236                                   Expr *Receiver,
9237                                   Selector Sel,
9238                                   SourceLocation LBracLoc,
9239                                   ArrayRef<SourceLocation> SelectorLocs,
9240                                   SourceLocation RBracLoc,
9241                                   MultiExprArg Args);
9242 
9243   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9244                                   ObjCBridgeCastKind Kind,
9245                                   SourceLocation BridgeKeywordLoc,
9246                                   TypeSourceInfo *TSInfo,
9247                                   Expr *SubExpr);
9248 
9249   ExprResult ActOnObjCBridgedCast(Scope *S,
9250                                   SourceLocation LParenLoc,
9251                                   ObjCBridgeCastKind Kind,
9252                                   SourceLocation BridgeKeywordLoc,
9253                                   ParsedType Type,
9254                                   SourceLocation RParenLoc,
9255                                   Expr *SubExpr);
9256 
9257   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9258 
9259   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9260 
9261   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9262                                      CastKind &Kind);
9263 
9264   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9265                                         QualType DestType, QualType SrcType,
9266                                         ObjCInterfaceDecl *&RelatedClass,
9267                                         ObjCMethodDecl *&ClassMethod,
9268                                         ObjCMethodDecl *&InstanceMethod,
9269                                         TypedefNameDecl *&TDNDecl,
9270                                         bool CfToNs, bool Diagnose = true);
9271 
9272   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9273                                          QualType DestType, QualType SrcType,
9274                                          Expr *&SrcExpr, bool Diagnose = true);
9275 
9276   bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
9277                                           bool Diagnose = true);
9278 
9279   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9280 
9281   /// Check whether the given new method is a valid override of the
9282   /// given overridden method, and set any properties that should be inherited.
9283   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9284                                const ObjCMethodDecl *Overridden);
9285 
9286   /// Describes the compatibility of a result type with its method.
9287   enum ResultTypeCompatibilityKind {
9288     RTC_Compatible,
9289     RTC_Incompatible,
9290     RTC_Unknown
9291   };
9292 
9293   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9294                                       ObjCMethodDecl *overridden);
9295 
9296   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9297                                 ObjCInterfaceDecl *CurrentClass,
9298                                 ResultTypeCompatibilityKind RTC);
9299 
9300   enum PragmaOptionsAlignKind {
9301     POAK_Native,  // #pragma options align=native
9302     POAK_Natural, // #pragma options align=natural
9303     POAK_Packed,  // #pragma options align=packed
9304     POAK_Power,   // #pragma options align=power
9305     POAK_Mac68k,  // #pragma options align=mac68k
9306     POAK_Reset    // #pragma options align=reset
9307   };
9308 
9309   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9310   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9311                                PragmaClangSectionAction Action,
9312                                PragmaClangSectionKind SecKind, StringRef SecName);
9313 
9314   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9315   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9316                                SourceLocation PragmaLoc);
9317 
9318   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9319   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9320                        StringRef SlotLabel, Expr *Alignment);
9321 
9322   enum class PragmaPackDiagnoseKind {
9323     NonDefaultStateAtInclude,
9324     ChangedStateAtExit
9325   };
9326 
9327   void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
9328                                     SourceLocation IncludeLoc);
9329   void DiagnoseUnterminatedPragmaPack();
9330 
9331   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9332   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9333 
9334   /// ActOnPragmaMSComment - Called on well formed
9335   /// \#pragma comment(kind, "arg").
9336   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9337                             StringRef Arg);
9338 
9339   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9340   /// pointers_to_members(representation method[, general purpose
9341   /// representation]).
9342   void ActOnPragmaMSPointersToMembers(
9343       LangOptions::PragmaMSPointersToMembersKind Kind,
9344       SourceLocation PragmaLoc);
9345 
9346   /// Called on well formed \#pragma vtordisp().
9347   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9348                              SourceLocation PragmaLoc,
9349                              MSVtorDispMode Value);
9350 
9351   enum PragmaSectionKind {
9352     PSK_DataSeg,
9353     PSK_BSSSeg,
9354     PSK_ConstSeg,
9355     PSK_CodeSeg,
9356   };
9357 
9358   bool UnifySection(StringRef SectionName,
9359                     int SectionFlags,
9360                     DeclaratorDecl *TheDecl);
9361   bool UnifySection(StringRef SectionName,
9362                     int SectionFlags,
9363                     SourceLocation PragmaSectionLocation);
9364 
9365   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9366   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9367                         PragmaMsStackAction Action,
9368                         llvm::StringRef StackSlotLabel,
9369                         StringLiteral *SegmentName,
9370                         llvm::StringRef PragmaName);
9371 
9372   /// Called on well formed \#pragma section().
9373   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9374                             int SectionFlags, StringLiteral *SegmentName);
9375 
9376   /// Called on well-formed \#pragma init_seg().
9377   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
9378                             StringLiteral *SegmentName);
9379 
9380   /// Called on #pragma clang __debug dump II
9381   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9382 
9383   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
9384   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
9385                                  StringRef Value);
9386 
9387   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
9388   void ActOnPragmaUnused(const Token &Identifier,
9389                          Scope *curScope,
9390                          SourceLocation PragmaLoc);
9391 
9392   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9393   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9394                              SourceLocation PragmaLoc);
9395 
9396   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9397                                  SourceLocation Loc);
9398   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9399 
9400   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9401   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9402                          SourceLocation PragmaLoc,
9403                          SourceLocation WeakNameLoc);
9404 
9405   /// ActOnPragmaRedefineExtname - Called on well formed
9406   /// \#pragma redefine_extname oldname newname.
9407   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9408                                   IdentifierInfo* AliasName,
9409                                   SourceLocation PragmaLoc,
9410                                   SourceLocation WeakNameLoc,
9411                                   SourceLocation AliasNameLoc);
9412 
9413   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9414   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9415                             IdentifierInfo* AliasName,
9416                             SourceLocation PragmaLoc,
9417                             SourceLocation WeakNameLoc,
9418                             SourceLocation AliasNameLoc);
9419 
9420   /// ActOnPragmaFPContract - Called on well formed
9421   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9422   /// \#pragma clang fp contract
9423   void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
9424 
9425   /// ActOnPragmaFenvAccess - Called on well formed
9426   /// \#pragma STDC FENV_ACCESS
9427   void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
9428 
9429   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9430   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9431   void AddAlignmentAttributesForRecord(RecordDecl *RD);
9432 
9433   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9434   void AddMsStructLayoutForRecord(RecordDecl *RD);
9435 
9436   /// FreePackedContext - Deallocate and null out PackContext.
9437   void FreePackedContext();
9438 
9439   /// PushNamespaceVisibilityAttr - Note that we've entered a
9440   /// namespace with a visibility attribute.
9441   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9442                                    SourceLocation Loc);
9443 
9444   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9445   /// add an appropriate visibility attribute.
9446   void AddPushedVisibilityAttribute(Decl *RD);
9447 
9448   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9449   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9450   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9451 
9452   /// FreeVisContext - Deallocate and null out VisContext.
9453   void FreeVisContext();
9454 
9455   /// AddCFAuditedAttribute - Check whether we're currently within
9456   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9457   /// the appropriate attribute.
9458   void AddCFAuditedAttribute(Decl *D);
9459 
9460   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9461                                      SourceLocation PragmaLoc,
9462                                      attr::ParsedSubjectMatchRuleSet Rules);
9463   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
9464                                      const IdentifierInfo *Namespace);
9465 
9466   /// Called on well-formed '\#pragma clang attribute pop'.
9467   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
9468                                const IdentifierInfo *Namespace);
9469 
9470   /// Adds the attributes that have been specified using the
9471   /// '\#pragma clang attribute push' directives to the given declaration.
9472   void AddPragmaAttributes(Scope *S, Decl *D);
9473 
9474   void DiagnoseUnterminatedPragmaAttribute();
9475 
9476   /// Called on well formed \#pragma clang optimize.
9477   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
9478 
9479   /// Get the location for the currently active "\#pragma clang optimize
9480   /// off". If this location is invalid, then the state of the pragma is "on".
9481   SourceLocation getOptimizeOffPragmaLocation() const {
9482     return OptimizeOffPragmaLocation;
9483   }
9484 
9485   /// Only called on function definitions; if there is a pragma in scope
9486   /// with the effect of a range-based optnone, consider marking the function
9487   /// with attribute optnone.
9488   void AddRangeBasedOptnone(FunctionDecl *FD);
9489 
9490   /// Adds the 'optnone' attribute to the function declaration if there
9491   /// are no conflicts; Loc represents the location causing the 'optnone'
9492   /// attribute to be added (usually because of a pragma).
9493   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
9494 
9495   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
9496   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9497                       bool IsPackExpansion);
9498   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
9499                       bool IsPackExpansion);
9500 
9501   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
9502   /// declaration.
9503   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9504                             Expr *OE);
9505 
9506   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
9507   /// declaration.
9508   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
9509                          Expr *ParamExpr);
9510 
9511   /// AddAlignValueAttr - Adds an align_value attribute to a particular
9512   /// declaration.
9513   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
9514 
9515   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
9516   /// declaration.
9517   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
9518                            Expr *MaxThreads, Expr *MinBlocks);
9519 
9520   /// AddModeAttr - Adds a mode attribute to a particular declaration.
9521   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
9522                    bool InInstantiation = false);
9523 
9524   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
9525                            ParameterABI ABI);
9526 
9527   enum class RetainOwnershipKind {NS, CF, OS};
9528   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
9529                         RetainOwnershipKind K, bool IsTemplateInstantiation);
9530 
9531   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
9532   /// attribute to a particular declaration.
9533   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
9534                                       Expr *Min, Expr *Max);
9535 
9536   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
9537   /// particular declaration.
9538   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
9539                                Expr *Min, Expr *Max);
9540 
9541   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
9542 
9543   //===--------------------------------------------------------------------===//
9544   // C++ Coroutines TS
9545   //
9546   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
9547                                StringRef Keyword);
9548   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9549   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
9550   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
9551 
9552   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9553                                       bool IsImplicit = false);
9554   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
9555                                         UnresolvedLookupExpr* Lookup);
9556   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
9557   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
9558                                bool IsImplicit = false);
9559   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
9560   bool buildCoroutineParameterMoves(SourceLocation Loc);
9561   VarDecl *buildCoroutinePromise(SourceLocation Loc);
9562   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
9563   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
9564                                            SourceLocation FuncLoc);
9565 
9566   //===--------------------------------------------------------------------===//
9567   // OpenCL extensions.
9568   //
9569 private:
9570   std::string CurrOpenCLExtension;
9571   /// Extensions required by an OpenCL type.
9572   llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
9573   /// Extensions required by an OpenCL declaration.
9574   llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
9575 public:
9576   llvm::StringRef getCurrentOpenCLExtension() const {
9577     return CurrOpenCLExtension;
9578   }
9579 
9580   /// Check if a function declaration \p FD associates with any
9581   /// extensions present in OpenCLDeclExtMap and if so return the
9582   /// extension(s) name(s).
9583   std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
9584 
9585   /// Check if a function type \p FT associates with any
9586   /// extensions present in OpenCLTypeExtMap and if so return the
9587   /// extension(s) name(s).
9588   std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
9589 
9590   /// Find an extension in an appropriate extension map and return its name
9591   template<typename T, typename MapT>
9592   std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
9593 
9594   void setCurrentOpenCLExtension(llvm::StringRef Ext) {
9595     CurrOpenCLExtension = Ext;
9596   }
9597 
9598   /// Set OpenCL extensions for a type which can only be used when these
9599   /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
9600   /// \param Exts A space separated list of OpenCL extensions.
9601   void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
9602 
9603   /// Set OpenCL extensions for a declaration which can only be
9604   /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
9605   /// nothing.
9606   /// \param Exts A space separated list of OpenCL extensions.
9607   void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
9608 
9609   /// Set current OpenCL extensions for a type which can only be used
9610   /// when these OpenCL extensions are enabled. If current OpenCL extension is
9611   /// empty, do nothing.
9612   void setCurrentOpenCLExtensionForType(QualType T);
9613 
9614   /// Set current OpenCL extensions for a declaration which
9615   /// can only be used when these OpenCL extensions are enabled. If current
9616   /// OpenCL extension is empty, do nothing.
9617   void setCurrentOpenCLExtensionForDecl(Decl *FD);
9618 
9619   bool isOpenCLDisabledDecl(Decl *FD);
9620 
9621   /// Check if type \p T corresponding to declaration specifier \p DS
9622   /// is disabled due to required OpenCL extensions being disabled. If so,
9623   /// emit diagnostics.
9624   /// \return true if type is disabled.
9625   bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
9626 
9627   /// Check if declaration \p D used by expression \p E
9628   /// is disabled due to required OpenCL extensions being disabled. If so,
9629   /// emit diagnostics.
9630   /// \return true if type is disabled.
9631   bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
9632 
9633   //===--------------------------------------------------------------------===//
9634   // OpenMP directives and clauses.
9635   //
9636 private:
9637   void *VarDataSharingAttributesStack;
9638   /// Number of nested '#pragma omp declare target' directives.
9639   unsigned DeclareTargetNestingLevel = 0;
9640   /// Initialization of data-sharing attributes stack.
9641   void InitDataSharingAttributesStack();
9642   void DestroyDataSharingAttributesStack();
9643   ExprResult
9644   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
9645                                         bool StrictlyPositive = true);
9646   /// Returns OpenMP nesting level for current directive.
9647   unsigned getOpenMPNestingLevel() const;
9648 
9649   /// Adjusts the function scopes index for the target-based regions.
9650   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
9651                                     unsigned Level) const;
9652 
9653   /// Returns the number of scopes associated with the construct on the given
9654   /// OpenMP level.
9655   int getNumberOfConstructScopes(unsigned Level) const;
9656 
9657   /// Push new OpenMP function region for non-capturing function.
9658   void pushOpenMPFunctionRegion();
9659 
9660   /// Pop OpenMP function region for non-capturing function.
9661   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
9662 
9663   /// Check whether we're allowed to call Callee from the current function.
9664   void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
9665                                  bool CheckForDelayedContext = true);
9666 
9667   /// Check whether we're allowed to call Callee from the current function.
9668   void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
9669                                bool CheckCaller = true);
9670 
9671   /// Check if the expression is allowed to be used in expressions for the
9672   /// OpenMP devices.
9673   void checkOpenMPDeviceExpr(const Expr *E);
9674 
9675   /// Finishes analysis of the deferred functions calls that may be declared as
9676   /// host/nohost during device/host compilation.
9677   void finalizeOpenMPDelayedAnalysis();
9678 
9679   /// Checks if a type or a declaration is disabled due to the owning extension
9680   /// being disabled, and emits diagnostic messages if it is disabled.
9681   /// \param D type or declaration to be checked.
9682   /// \param DiagLoc source location for the diagnostic message.
9683   /// \param DiagInfo information to be emitted for the diagnostic message.
9684   /// \param SrcRange source range of the declaration.
9685   /// \param Map maps type or declaration to the extensions.
9686   /// \param Selector selects diagnostic message: 0 for type and 1 for
9687   ///        declaration.
9688   /// \return true if the type or declaration is disabled.
9689   template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
9690   bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
9691                                      MapT &Map, unsigned Selector = 0,
9692                                      SourceRange SrcRange = SourceRange());
9693 
9694   /// Marks all the functions that might be required for the currently active
9695   /// OpenMP context.
9696   void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
9697                                                FunctionDecl *Func,
9698                                                bool MightBeOdrUse);
9699 
9700 public:
9701   /// Struct to store the context selectors info for declare variant directive.
9702   using OMPCtxStringType = SmallString<8>;
9703   using OMPCtxSelectorData =
9704       OpenMPCtxSelectorData<SmallVector<OMPCtxStringType, 4>, ExprResult>;
9705 
9706   /// Checks if the variant/multiversion functions are compatible.
9707   bool areMultiversionVariantFunctionsCompatible(
9708       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
9709       const PartialDiagnostic &NoProtoDiagID,
9710       const PartialDiagnosticAt &NoteCausedDiagIDAt,
9711       const PartialDiagnosticAt &NoSupportDiagIDAt,
9712       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
9713       bool ConstexprSupported, bool CLinkageMayDiffer);
9714 
9715   /// Function tries to capture lambda's captured variables in the OpenMP region
9716   /// before the original lambda is captured.
9717   void tryCaptureOpenMPLambdas(ValueDecl *V);
9718 
9719   /// Return true if the provided declaration \a VD should be captured by
9720   /// reference.
9721   /// \param Level Relative level of nested OpenMP construct for that the check
9722   /// is performed.
9723   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
9724   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
9725                              unsigned OpenMPCaptureLevel) const;
9726 
9727   /// Check if the specified variable is used in one of the private
9728   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
9729   /// constructs.
9730   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
9731                                 unsigned StopAt = 0);
9732   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9733                                    ExprObjectKind OK, SourceLocation Loc);
9734 
9735   /// If the current region is a loop-based region, mark the start of the loop
9736   /// construct.
9737   void startOpenMPLoop();
9738 
9739   /// If the current region is a range loop-based region, mark the start of the
9740   /// loop construct.
9741   void startOpenMPCXXRangeFor();
9742 
9743   /// Check if the specified variable is used in 'private' clause.
9744   /// \param Level Relative level of nested OpenMP construct for that the check
9745   /// is performed.
9746   bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
9747 
9748   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
9749   /// for \p FD based on DSA for the provided corresponding captured declaration
9750   /// \p D.
9751   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
9752 
9753   /// Check if the specified variable is captured  by 'target' directive.
9754   /// \param Level Relative level of nested OpenMP construct for that the check
9755   /// is performed.
9756   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
9757 
9758   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
9759                                                     Expr *Op);
9760   /// Called on start of new data sharing attribute block.
9761   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
9762                            const DeclarationNameInfo &DirName, Scope *CurScope,
9763                            SourceLocation Loc);
9764   /// Start analysis of clauses.
9765   void StartOpenMPClause(OpenMPClauseKind K);
9766   /// End analysis of clauses.
9767   void EndOpenMPClause();
9768   /// Called on end of data sharing attribute block.
9769   void EndOpenMPDSABlock(Stmt *CurDirective);
9770 
9771   /// Check if the current region is an OpenMP loop region and if it is,
9772   /// mark loop control variable, used in \p Init for loop initialization, as
9773   /// private by default.
9774   /// \param Init First part of the for loop.
9775   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
9776 
9777   // OpenMP directives and clauses.
9778   /// Called on correct id-expression from the '#pragma omp
9779   /// threadprivate'.
9780   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9781                                      const DeclarationNameInfo &Id,
9782                                      OpenMPDirectiveKind Kind);
9783   /// Called on well-formed '#pragma omp threadprivate'.
9784   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
9785                                      SourceLocation Loc,
9786                                      ArrayRef<Expr *> VarList);
9787   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
9788   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
9789                                                   ArrayRef<Expr *> VarList);
9790   /// Called on well-formed '#pragma omp allocate'.
9791   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
9792                                               ArrayRef<Expr *> VarList,
9793                                               ArrayRef<OMPClause *> Clauses,
9794                                               DeclContext *Owner = nullptr);
9795   /// Called on well-formed '#pragma omp requires'.
9796   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
9797                                               ArrayRef<OMPClause *> ClauseList);
9798   /// Check restrictions on Requires directive
9799   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
9800                                         ArrayRef<OMPClause *> Clauses);
9801   /// Check if the specified type is allowed to be used in 'omp declare
9802   /// reduction' construct.
9803   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
9804                                            TypeResult ParsedType);
9805   /// Called on start of '#pragma omp declare reduction'.
9806   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
9807       Scope *S, DeclContext *DC, DeclarationName Name,
9808       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
9809       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
9810   /// Initialize declare reduction construct initializer.
9811   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
9812   /// Finish current declare reduction construct initializer.
9813   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
9814   /// Initialize declare reduction construct initializer.
9815   /// \return omp_priv variable.
9816   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
9817   /// Finish current declare reduction construct initializer.
9818   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
9819                                                  VarDecl *OmpPrivParm);
9820   /// Called at the end of '#pragma omp declare reduction'.
9821   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
9822       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
9823 
9824   /// Check variable declaration in 'omp declare mapper' construct.
9825   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
9826   /// Check if the specified type is allowed to be used in 'omp declare
9827   /// mapper' construct.
9828   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
9829                                         TypeResult ParsedType);
9830   /// Called on start of '#pragma omp declare mapper'.
9831   OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
9832       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
9833       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
9834       Decl *PrevDeclInScope = nullptr);
9835   /// Build the mapper variable of '#pragma omp declare mapper'.
9836   void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
9837                                                 Scope *S, QualType MapperType,
9838                                                 SourceLocation StartLoc,
9839                                                 DeclarationName VN);
9840   /// Called at the end of '#pragma omp declare mapper'.
9841   DeclGroupPtrTy
9842   ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
9843                                        ArrayRef<OMPClause *> ClauseList);
9844 
9845   /// Called on the start of target region i.e. '#pragma omp declare target'.
9846   bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
9847   /// Called at the end of target region i.e. '#pragme omp end declare target'.
9848   void ActOnFinishOpenMPDeclareTargetDirective();
9849   /// Searches for the provided declaration name for OpenMP declare target
9850   /// directive.
9851   NamedDecl *
9852   lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
9853                                 const DeclarationNameInfo &Id,
9854                                 NamedDeclSetType &SameDirectiveDecls);
9855   /// Called on correct id-expression from the '#pragma omp declare target'.
9856   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
9857                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
9858                                     OMPDeclareTargetDeclAttr::DevTypeTy DT);
9859   /// Check declaration inside target region.
9860   void
9861   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
9862                                    SourceLocation IdLoc = SourceLocation());
9863   /// Return true inside OpenMP declare target region.
9864   bool isInOpenMPDeclareTargetContext() const {
9865     return DeclareTargetNestingLevel > 0;
9866   }
9867   /// Return true inside OpenMP target region.
9868   bool isInOpenMPTargetExecutionDirective() const;
9869 
9870   /// Return the number of captured regions created for an OpenMP directive.
9871   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
9872 
9873   /// Initialization of captured region for OpenMP region.
9874   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
9875   /// End of OpenMP region.
9876   ///
9877   /// \param S Statement associated with the current OpenMP region.
9878   /// \param Clauses List of clauses for the current OpenMP region.
9879   ///
9880   /// \returns Statement for finished OpenMP region.
9881   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
9882   StmtResult ActOnOpenMPExecutableDirective(
9883       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
9884       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
9885       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
9886   /// Called on well-formed '\#pragma omp parallel' after parsing
9887   /// of the  associated statement.
9888   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
9889                                           Stmt *AStmt,
9890                                           SourceLocation StartLoc,
9891                                           SourceLocation EndLoc);
9892   using VarsWithInheritedDSAType =
9893       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
9894   /// Called on well-formed '\#pragma omp simd' after parsing
9895   /// of the associated statement.
9896   StmtResult
9897   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9898                            SourceLocation StartLoc, SourceLocation EndLoc,
9899                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
9900   /// Called on well-formed '\#pragma omp for' after parsing
9901   /// of the associated statement.
9902   StmtResult
9903   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9904                           SourceLocation StartLoc, SourceLocation EndLoc,
9905                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
9906   /// Called on well-formed '\#pragma omp for simd' after parsing
9907   /// of the associated statement.
9908   StmtResult
9909   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
9910                               SourceLocation StartLoc, SourceLocation EndLoc,
9911                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
9912   /// Called on well-formed '\#pragma omp sections' after parsing
9913   /// of the associated statement.
9914   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
9915                                           Stmt *AStmt, SourceLocation StartLoc,
9916                                           SourceLocation EndLoc);
9917   /// Called on well-formed '\#pragma omp section' after parsing of the
9918   /// associated statement.
9919   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
9920                                          SourceLocation EndLoc);
9921   /// Called on well-formed '\#pragma omp single' after parsing of the
9922   /// associated statement.
9923   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
9924                                         Stmt *AStmt, SourceLocation StartLoc,
9925                                         SourceLocation EndLoc);
9926   /// Called on well-formed '\#pragma omp master' after parsing of the
9927   /// associated statement.
9928   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
9929                                         SourceLocation EndLoc);
9930   /// Called on well-formed '\#pragma omp critical' after parsing of the
9931   /// associated statement.
9932   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
9933                                           ArrayRef<OMPClause *> Clauses,
9934                                           Stmt *AStmt, SourceLocation StartLoc,
9935                                           SourceLocation EndLoc);
9936   /// Called on well-formed '\#pragma omp parallel for' after parsing
9937   /// of the  associated statement.
9938   StmtResult ActOnOpenMPParallelForDirective(
9939       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9940       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9941   /// Called on well-formed '\#pragma omp parallel for simd' after
9942   /// parsing of the  associated statement.
9943   StmtResult ActOnOpenMPParallelForSimdDirective(
9944       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9945       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
9946   /// Called on well-formed '\#pragma omp parallel master' after
9947   /// parsing of the  associated statement.
9948   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
9949                                                 Stmt *AStmt,
9950                                                 SourceLocation StartLoc,
9951                                                 SourceLocation EndLoc);
9952   /// Called on well-formed '\#pragma omp parallel sections' after
9953   /// parsing of the  associated statement.
9954   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
9955                                                   Stmt *AStmt,
9956                                                   SourceLocation StartLoc,
9957                                                   SourceLocation EndLoc);
9958   /// Called on well-formed '\#pragma omp task' after parsing of the
9959   /// associated statement.
9960   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
9961                                       Stmt *AStmt, SourceLocation StartLoc,
9962                                       SourceLocation EndLoc);
9963   /// Called on well-formed '\#pragma omp taskyield'.
9964   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
9965                                            SourceLocation EndLoc);
9966   /// Called on well-formed '\#pragma omp barrier'.
9967   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
9968                                          SourceLocation EndLoc);
9969   /// Called on well-formed '\#pragma omp taskwait'.
9970   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
9971                                           SourceLocation EndLoc);
9972   /// Called on well-formed '\#pragma omp taskgroup'.
9973   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
9974                                            Stmt *AStmt, SourceLocation StartLoc,
9975                                            SourceLocation EndLoc);
9976   /// Called on well-formed '\#pragma omp flush'.
9977   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
9978                                        SourceLocation StartLoc,
9979                                        SourceLocation EndLoc);
9980   /// Called on well-formed '\#pragma omp ordered' after parsing of the
9981   /// associated statement.
9982   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
9983                                          Stmt *AStmt, SourceLocation StartLoc,
9984                                          SourceLocation EndLoc);
9985   /// Called on well-formed '\#pragma omp atomic' after parsing of the
9986   /// associated statement.
9987   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
9988                                         Stmt *AStmt, SourceLocation StartLoc,
9989                                         SourceLocation EndLoc);
9990   /// Called on well-formed '\#pragma omp target' after parsing of the
9991   /// associated statement.
9992   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9993                                         Stmt *AStmt, SourceLocation StartLoc,
9994                                         SourceLocation EndLoc);
9995   /// Called on well-formed '\#pragma omp target data' after parsing of
9996   /// the associated statement.
9997   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9998                                             Stmt *AStmt, SourceLocation StartLoc,
9999                                             SourceLocation EndLoc);
10000   /// Called on well-formed '\#pragma omp target enter data' after
10001   /// parsing of the associated statement.
10002   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10003                                                  SourceLocation StartLoc,
10004                                                  SourceLocation EndLoc,
10005                                                  Stmt *AStmt);
10006   /// Called on well-formed '\#pragma omp target exit data' after
10007   /// parsing of the associated statement.
10008   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10009                                                 SourceLocation StartLoc,
10010                                                 SourceLocation EndLoc,
10011                                                 Stmt *AStmt);
10012   /// Called on well-formed '\#pragma omp target parallel' after
10013   /// parsing of the associated statement.
10014   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10015                                                 Stmt *AStmt,
10016                                                 SourceLocation StartLoc,
10017                                                 SourceLocation EndLoc);
10018   /// Called on well-formed '\#pragma omp target parallel for' after
10019   /// parsing of the  associated statement.
10020   StmtResult ActOnOpenMPTargetParallelForDirective(
10021       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10022       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10023   /// Called on well-formed '\#pragma omp teams' after parsing of the
10024   /// associated statement.
10025   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10026                                        Stmt *AStmt, SourceLocation StartLoc,
10027                                        SourceLocation EndLoc);
10028   /// Called on well-formed '\#pragma omp cancellation point'.
10029   StmtResult
10030   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10031                                         SourceLocation EndLoc,
10032                                         OpenMPDirectiveKind CancelRegion);
10033   /// Called on well-formed '\#pragma omp cancel'.
10034   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10035                                         SourceLocation StartLoc,
10036                                         SourceLocation EndLoc,
10037                                         OpenMPDirectiveKind CancelRegion);
10038   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10039   /// associated statement.
10040   StmtResult
10041   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10042                                SourceLocation StartLoc, SourceLocation EndLoc,
10043                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
10044   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10045   /// the associated statement.
10046   StmtResult ActOnOpenMPTaskLoopSimdDirective(
10047       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10048       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10049   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10050   /// associated statement.
10051   StmtResult ActOnOpenMPMasterTaskLoopDirective(
10052       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10053       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10054   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10055   /// the associated statement.
10056   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10057       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10058       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10059   /// Called on well-formed '\#pragma omp parallel master taskloop' after
10060   /// parsing of the associated statement.
10061   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10062       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10063       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10064   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10065   /// parsing of the associated statement.
10066   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10067       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10068       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10069   /// Called on well-formed '\#pragma omp distribute' after parsing
10070   /// of the associated statement.
10071   StmtResult
10072   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10073                                  SourceLocation StartLoc, SourceLocation EndLoc,
10074                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10075   /// Called on well-formed '\#pragma omp target update'.
10076   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10077                                               SourceLocation StartLoc,
10078                                               SourceLocation EndLoc,
10079                                               Stmt *AStmt);
10080   /// Called on well-formed '\#pragma omp distribute parallel for' after
10081   /// parsing of the associated statement.
10082   StmtResult ActOnOpenMPDistributeParallelForDirective(
10083       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10084       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10085   /// Called on well-formed '\#pragma omp distribute parallel for simd'
10086   /// after parsing of the associated statement.
10087   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10088       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10089       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10090   /// Called on well-formed '\#pragma omp distribute simd' after
10091   /// parsing of the associated statement.
10092   StmtResult ActOnOpenMPDistributeSimdDirective(
10093       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10094       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10095   /// Called on well-formed '\#pragma omp target parallel for simd' after
10096   /// parsing of the associated statement.
10097   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10098       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10099       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10100   /// Called on well-formed '\#pragma omp target simd' after parsing of
10101   /// the associated statement.
10102   StmtResult
10103   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10104                                  SourceLocation StartLoc, SourceLocation EndLoc,
10105                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10106   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10107   /// the associated statement.
10108   StmtResult ActOnOpenMPTeamsDistributeDirective(
10109       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10110       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10111   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10112   /// of the associated statement.
10113   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10114       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10115       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10116   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10117   /// after parsing of the associated statement.
10118   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10119       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10120       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10121   /// Called on well-formed '\#pragma omp teams distribute parallel for'
10122   /// after parsing of the associated statement.
10123   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10124       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10125       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10126   /// Called on well-formed '\#pragma omp target teams' after parsing of the
10127   /// associated statement.
10128   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10129                                              Stmt *AStmt,
10130                                              SourceLocation StartLoc,
10131                                              SourceLocation EndLoc);
10132   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10133   /// of the associated statement.
10134   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10135       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10136       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10137   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10138   /// after parsing of the associated statement.
10139   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10140       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10141       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10142   /// Called on well-formed '\#pragma omp target teams distribute parallel for
10143   /// simd' after parsing of the associated statement.
10144   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10145       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10146       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10147   /// Called on well-formed '\#pragma omp target teams distribute simd' after
10148   /// parsing of the associated statement.
10149   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10150       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10151       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10152 
10153   /// Checks correctness of linear modifiers.
10154   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10155                                  SourceLocation LinLoc);
10156   /// Checks that the specified declaration matches requirements for the linear
10157   /// decls.
10158   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10159                              OpenMPLinearClauseKind LinKind, QualType Type);
10160 
10161   /// Called on well-formed '\#pragma omp declare simd' after parsing of
10162   /// the associated method/function.
10163   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10164       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10165       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10166       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10167       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10168 
10169   /// Checks '\#pragma omp declare variant' variant function and original
10170   /// functions after parsing of the associated method/function.
10171   /// \param DG Function declaration to which declare variant directive is
10172   /// applied to.
10173   /// \param VariantRef Expression that references the variant function, which
10174   /// must be used instead of the original one, specified in \p DG.
10175   /// \returns None, if the function/variant function are not compatible with
10176   /// the pragma, pair of original function/variant ref expression otherwise.
10177   Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
10178       DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
10179 
10180   /// Called on well-formed '\#pragma omp declare variant' after parsing of
10181   /// the associated method/function.
10182   /// \param FD Function declaration to which declare variant directive is
10183   /// applied to.
10184   /// \param VariantRef Expression that references the variant function, which
10185   /// must be used instead of the original one, specified in \p DG.
10186   /// \param Data Set of context-specific data for the specified context
10187   /// selector.
10188   void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10189                                           SourceRange SR,
10190                                           ArrayRef<OMPCtxSelectorData> Data);
10191 
10192   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10193                                          Expr *Expr,
10194                                          SourceLocation StartLoc,
10195                                          SourceLocation LParenLoc,
10196                                          SourceLocation EndLoc);
10197   /// Called on well-formed 'allocator' clause.
10198   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10199                                         SourceLocation StartLoc,
10200                                         SourceLocation LParenLoc,
10201                                         SourceLocation EndLoc);
10202   /// Called on well-formed 'if' clause.
10203   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10204                                  Expr *Condition, SourceLocation StartLoc,
10205                                  SourceLocation LParenLoc,
10206                                  SourceLocation NameModifierLoc,
10207                                  SourceLocation ColonLoc,
10208                                  SourceLocation EndLoc);
10209   /// Called on well-formed 'final' clause.
10210   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10211                                     SourceLocation LParenLoc,
10212                                     SourceLocation EndLoc);
10213   /// Called on well-formed 'num_threads' clause.
10214   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10215                                          SourceLocation StartLoc,
10216                                          SourceLocation LParenLoc,
10217                                          SourceLocation EndLoc);
10218   /// Called on well-formed 'safelen' clause.
10219   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10220                                       SourceLocation StartLoc,
10221                                       SourceLocation LParenLoc,
10222                                       SourceLocation EndLoc);
10223   /// Called on well-formed 'simdlen' clause.
10224   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10225                                       SourceLocation LParenLoc,
10226                                       SourceLocation EndLoc);
10227   /// Called on well-formed 'collapse' clause.
10228   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10229                                        SourceLocation StartLoc,
10230                                        SourceLocation LParenLoc,
10231                                        SourceLocation EndLoc);
10232   /// Called on well-formed 'ordered' clause.
10233   OMPClause *
10234   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10235                            SourceLocation LParenLoc = SourceLocation(),
10236                            Expr *NumForLoops = nullptr);
10237   /// Called on well-formed 'grainsize' clause.
10238   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10239                                         SourceLocation LParenLoc,
10240                                         SourceLocation EndLoc);
10241   /// Called on well-formed 'num_tasks' clause.
10242   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10243                                        SourceLocation LParenLoc,
10244                                        SourceLocation EndLoc);
10245   /// Called on well-formed 'hint' clause.
10246   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10247                                    SourceLocation LParenLoc,
10248                                    SourceLocation EndLoc);
10249 
10250   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10251                                      unsigned Argument,
10252                                      SourceLocation ArgumentLoc,
10253                                      SourceLocation StartLoc,
10254                                      SourceLocation LParenLoc,
10255                                      SourceLocation EndLoc);
10256   /// Called on well-formed 'default' clause.
10257   OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
10258                                       SourceLocation KindLoc,
10259                                       SourceLocation StartLoc,
10260                                       SourceLocation LParenLoc,
10261                                       SourceLocation EndLoc);
10262   /// Called on well-formed 'proc_bind' clause.
10263   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
10264                                        SourceLocation KindLoc,
10265                                        SourceLocation StartLoc,
10266                                        SourceLocation LParenLoc,
10267                                        SourceLocation EndLoc);
10268 
10269   OMPClause *ActOnOpenMPSingleExprWithArgClause(
10270       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
10271       SourceLocation StartLoc, SourceLocation LParenLoc,
10272       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
10273       SourceLocation EndLoc);
10274   /// Called on well-formed 'schedule' clause.
10275   OMPClause *ActOnOpenMPScheduleClause(
10276       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10277       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10278       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10279       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
10280 
10281   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
10282                                SourceLocation EndLoc);
10283   /// Called on well-formed 'nowait' clause.
10284   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10285                                      SourceLocation EndLoc);
10286   /// Called on well-formed 'untied' clause.
10287   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10288                                      SourceLocation EndLoc);
10289   /// Called on well-formed 'mergeable' clause.
10290   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10291                                         SourceLocation EndLoc);
10292   /// Called on well-formed 'read' clause.
10293   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
10294                                    SourceLocation EndLoc);
10295   /// Called on well-formed 'write' clause.
10296   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
10297                                     SourceLocation EndLoc);
10298   /// Called on well-formed 'update' clause.
10299   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10300                                      SourceLocation EndLoc);
10301   /// Called on well-formed 'capture' clause.
10302   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10303                                       SourceLocation EndLoc);
10304   /// Called on well-formed 'seq_cst' clause.
10305   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10306                                      SourceLocation EndLoc);
10307   /// Called on well-formed 'threads' clause.
10308   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10309                                       SourceLocation EndLoc);
10310   /// Called on well-formed 'simd' clause.
10311   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10312                                    SourceLocation EndLoc);
10313   /// Called on well-formed 'nogroup' clause.
10314   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10315                                       SourceLocation EndLoc);
10316   /// Called on well-formed 'unified_address' clause.
10317   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10318                                              SourceLocation EndLoc);
10319 
10320   /// Called on well-formed 'unified_address' clause.
10321   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10322                                                   SourceLocation EndLoc);
10323 
10324   /// Called on well-formed 'reverse_offload' clause.
10325   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10326                                              SourceLocation EndLoc);
10327 
10328   /// Called on well-formed 'dynamic_allocators' clause.
10329   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10330                                                 SourceLocation EndLoc);
10331 
10332   /// Called on well-formed 'atomic_default_mem_order' clause.
10333   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
10334       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
10335       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10336 
10337   OMPClause *ActOnOpenMPVarListClause(
10338       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
10339       const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10340       CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10341       DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
10342       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10343       ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
10344       SourceLocation DepLinMapLastLoc);
10345   /// Called on well-formed 'allocate' clause.
10346   OMPClause *
10347   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
10348                             SourceLocation StartLoc, SourceLocation ColonLoc,
10349                             SourceLocation LParenLoc, SourceLocation EndLoc);
10350   /// Called on well-formed 'private' clause.
10351   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10352                                       SourceLocation StartLoc,
10353                                       SourceLocation LParenLoc,
10354                                       SourceLocation EndLoc);
10355   /// Called on well-formed 'firstprivate' clause.
10356   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10357                                            SourceLocation StartLoc,
10358                                            SourceLocation LParenLoc,
10359                                            SourceLocation EndLoc);
10360   /// Called on well-formed 'lastprivate' clause.
10361   OMPClause *ActOnOpenMPLastprivateClause(
10362       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
10363       SourceLocation LPKindLoc, SourceLocation ColonLoc,
10364       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10365   /// Called on well-formed 'shared' clause.
10366   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10367                                      SourceLocation StartLoc,
10368                                      SourceLocation LParenLoc,
10369                                      SourceLocation EndLoc);
10370   /// Called on well-formed 'reduction' clause.
10371   OMPClause *ActOnOpenMPReductionClause(
10372       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10373       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10374       CXXScopeSpec &ReductionIdScopeSpec,
10375       const DeclarationNameInfo &ReductionId,
10376       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10377   /// Called on well-formed 'task_reduction' clause.
10378   OMPClause *ActOnOpenMPTaskReductionClause(
10379       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10380       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10381       CXXScopeSpec &ReductionIdScopeSpec,
10382       const DeclarationNameInfo &ReductionId,
10383       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10384   /// Called on well-formed 'in_reduction' clause.
10385   OMPClause *ActOnOpenMPInReductionClause(
10386       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10387       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10388       CXXScopeSpec &ReductionIdScopeSpec,
10389       const DeclarationNameInfo &ReductionId,
10390       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10391   /// Called on well-formed 'linear' clause.
10392   OMPClause *
10393   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
10394                           SourceLocation StartLoc, SourceLocation LParenLoc,
10395                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
10396                           SourceLocation ColonLoc, SourceLocation EndLoc);
10397   /// Called on well-formed 'aligned' clause.
10398   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
10399                                       Expr *Alignment,
10400                                       SourceLocation StartLoc,
10401                                       SourceLocation LParenLoc,
10402                                       SourceLocation ColonLoc,
10403                                       SourceLocation EndLoc);
10404   /// Called on well-formed 'copyin' clause.
10405   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10406                                      SourceLocation StartLoc,
10407                                      SourceLocation LParenLoc,
10408                                      SourceLocation EndLoc);
10409   /// Called on well-formed 'copyprivate' clause.
10410   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10411                                           SourceLocation StartLoc,
10412                                           SourceLocation LParenLoc,
10413                                           SourceLocation EndLoc);
10414   /// Called on well-formed 'flush' pseudo clause.
10415   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10416                                     SourceLocation StartLoc,
10417                                     SourceLocation LParenLoc,
10418                                     SourceLocation EndLoc);
10419   /// Called on well-formed 'depend' clause.
10420   OMPClause *
10421   ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
10422                           SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
10423                           SourceLocation StartLoc, SourceLocation LParenLoc,
10424                           SourceLocation EndLoc);
10425   /// Called on well-formed 'device' clause.
10426   OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10427                                      SourceLocation LParenLoc,
10428                                      SourceLocation EndLoc);
10429   /// Called on well-formed 'map' clause.
10430   OMPClause *
10431   ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10432                        ArrayRef<SourceLocation> MapTypeModifiersLoc,
10433                        CXXScopeSpec &MapperIdScopeSpec,
10434                        DeclarationNameInfo &MapperId,
10435                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10436                        SourceLocation MapLoc, SourceLocation ColonLoc,
10437                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
10438                        ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10439   /// Called on well-formed 'num_teams' clause.
10440   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
10441                                        SourceLocation LParenLoc,
10442                                        SourceLocation EndLoc);
10443   /// Called on well-formed 'thread_limit' clause.
10444   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10445                                           SourceLocation StartLoc,
10446                                           SourceLocation LParenLoc,
10447                                           SourceLocation EndLoc);
10448   /// Called on well-formed 'priority' clause.
10449   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
10450                                        SourceLocation LParenLoc,
10451                                        SourceLocation EndLoc);
10452   /// Called on well-formed 'dist_schedule' clause.
10453   OMPClause *ActOnOpenMPDistScheduleClause(
10454       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
10455       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
10456       SourceLocation CommaLoc, SourceLocation EndLoc);
10457   /// Called on well-formed 'defaultmap' clause.
10458   OMPClause *ActOnOpenMPDefaultmapClause(
10459       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10460       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10461       SourceLocation KindLoc, SourceLocation EndLoc);
10462   /// Called on well-formed 'to' clause.
10463   OMPClause *
10464   ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10465                       DeclarationNameInfo &MapperId,
10466                       const OMPVarListLocTy &Locs,
10467                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10468   /// Called on well-formed 'from' clause.
10469   OMPClause *ActOnOpenMPFromClause(
10470       ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
10471       DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
10472       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
10473   /// Called on well-formed 'use_device_ptr' clause.
10474   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
10475                                            const OMPVarListLocTy &Locs);
10476   /// Called on well-formed 'is_device_ptr' clause.
10477   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
10478                                           const OMPVarListLocTy &Locs);
10479   /// Called on well-formed 'nontemporal' clause.
10480   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
10481                                           SourceLocation StartLoc,
10482                                           SourceLocation LParenLoc,
10483                                           SourceLocation EndLoc);
10484 
10485   /// The kind of conversion being performed.
10486   enum CheckedConversionKind {
10487     /// An implicit conversion.
10488     CCK_ImplicitConversion,
10489     /// A C-style cast.
10490     CCK_CStyleCast,
10491     /// A functional-style cast.
10492     CCK_FunctionalCast,
10493     /// A cast other than a C-style cast.
10494     CCK_OtherCast,
10495     /// A conversion for an operand of a builtin overloaded operator.
10496     CCK_ForBuiltinOverloadedOp
10497   };
10498 
10499   static bool isCast(CheckedConversionKind CCK) {
10500     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
10501            CCK == CCK_OtherCast;
10502   }
10503 
10504   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
10505   /// cast.  If there is already an implicit cast, merge into the existing one.
10506   /// If isLvalue, the result of the cast is an lvalue.
10507   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
10508                                ExprValueKind VK = VK_RValue,
10509                                const CXXCastPath *BasePath = nullptr,
10510                                CheckedConversionKind CCK
10511                                   = CCK_ImplicitConversion);
10512 
10513   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
10514   /// to the conversion from scalar type ScalarTy to the Boolean type.
10515   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
10516 
10517   /// IgnoredValueConversions - Given that an expression's result is
10518   /// syntactically ignored, perform any conversions that are
10519   /// required.
10520   ExprResult IgnoredValueConversions(Expr *E);
10521 
10522   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
10523   // functions and arrays to their respective pointers (C99 6.3.2.1).
10524   ExprResult UsualUnaryConversions(Expr *E);
10525 
10526   /// CallExprUnaryConversions - a special case of an unary conversion
10527   /// performed on a function designator of a call expression.
10528   ExprResult CallExprUnaryConversions(Expr *E);
10529 
10530   // DefaultFunctionArrayConversion - converts functions and arrays
10531   // to their respective pointers (C99 6.3.2.1).
10532   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
10533 
10534   // DefaultFunctionArrayLvalueConversion - converts functions and
10535   // arrays to their respective pointers and performs the
10536   // lvalue-to-rvalue conversion.
10537   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
10538                                                   bool Diagnose = true);
10539 
10540   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
10541   // the operand.  This is DefaultFunctionArrayLvalueConversion,
10542   // except that it assumes the operand isn't of function or array
10543   // type.
10544   ExprResult DefaultLvalueConversion(Expr *E);
10545 
10546   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
10547   // do not have a prototype. Integer promotions are performed on each
10548   // argument, and arguments that have type float are promoted to double.
10549   ExprResult DefaultArgumentPromotion(Expr *E);
10550 
10551   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
10552   /// it as an xvalue. In C++98, the result will still be a prvalue, because
10553   /// we don't have xvalues there.
10554   ExprResult TemporaryMaterializationConversion(Expr *E);
10555 
10556   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
10557   enum VariadicCallType {
10558     VariadicFunction,
10559     VariadicBlock,
10560     VariadicMethod,
10561     VariadicConstructor,
10562     VariadicDoesNotApply
10563   };
10564 
10565   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
10566                                        const FunctionProtoType *Proto,
10567                                        Expr *Fn);
10568 
10569   // Used for determining in which context a type is allowed to be passed to a
10570   // vararg function.
10571   enum VarArgKind {
10572     VAK_Valid,
10573     VAK_ValidInCXX11,
10574     VAK_Undefined,
10575     VAK_MSVCUndefined,
10576     VAK_Invalid
10577   };
10578 
10579   // Determines which VarArgKind fits an expression.
10580   VarArgKind isValidVarArgType(const QualType &Ty);
10581 
10582   /// Check to see if the given expression is a valid argument to a variadic
10583   /// function, issuing a diagnostic if not.
10584   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
10585 
10586   /// Check to see if a given expression could have '.c_str()' called on it.
10587   bool hasCStrMethod(const Expr *E);
10588 
10589   /// GatherArgumentsForCall - Collector argument expressions for various
10590   /// form of call prototypes.
10591   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
10592                               const FunctionProtoType *Proto,
10593                               unsigned FirstParam, ArrayRef<Expr *> Args,
10594                               SmallVectorImpl<Expr *> &AllArgs,
10595                               VariadicCallType CallType = VariadicDoesNotApply,
10596                               bool AllowExplicit = false,
10597                               bool IsListInitialization = false);
10598 
10599   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
10600   // will create a runtime trap if the resulting type is not a POD type.
10601   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
10602                                               FunctionDecl *FDecl);
10603 
10604   /// Context in which we're performing a usual arithmetic conversion.
10605   enum ArithConvKind {
10606     /// An arithmetic operation.
10607     ACK_Arithmetic,
10608     /// A bitwise operation.
10609     ACK_BitwiseOp,
10610     /// A comparison.
10611     ACK_Comparison,
10612     /// A conditional (?:) operator.
10613     ACK_Conditional,
10614     /// A compound assignment expression.
10615     ACK_CompAssign,
10616   };
10617 
10618   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
10619   // operands and then handles various conversions that are common to binary
10620   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
10621   // routine returns the first non-arithmetic type found. The client is
10622   // responsible for emitting appropriate error diagnostics.
10623   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
10624                                       SourceLocation Loc, ArithConvKind ACK);
10625 
10626   /// AssignConvertType - All of the 'assignment' semantic checks return this
10627   /// enum to indicate whether the assignment was allowed.  These checks are
10628   /// done for simple assignments, as well as initialization, return from
10629   /// function, argument passing, etc.  The query is phrased in terms of a
10630   /// source and destination type.
10631   enum AssignConvertType {
10632     /// Compatible - the types are compatible according to the standard.
10633     Compatible,
10634 
10635     /// PointerToInt - The assignment converts a pointer to an int, which we
10636     /// accept as an extension.
10637     PointerToInt,
10638 
10639     /// IntToPointer - The assignment converts an int to a pointer, which we
10640     /// accept as an extension.
10641     IntToPointer,
10642 
10643     /// FunctionVoidPointer - The assignment is between a function pointer and
10644     /// void*, which the standard doesn't allow, but we accept as an extension.
10645     FunctionVoidPointer,
10646 
10647     /// IncompatiblePointer - The assignment is between two pointers types that
10648     /// are not compatible, but we accept them as an extension.
10649     IncompatiblePointer,
10650 
10651     /// IncompatiblePointerSign - The assignment is between two pointers types
10652     /// which point to integers which have a different sign, but are otherwise
10653     /// identical. This is a subset of the above, but broken out because it's by
10654     /// far the most common case of incompatible pointers.
10655     IncompatiblePointerSign,
10656 
10657     /// CompatiblePointerDiscardsQualifiers - The assignment discards
10658     /// c/v/r qualifiers, which we accept as an extension.
10659     CompatiblePointerDiscardsQualifiers,
10660 
10661     /// IncompatiblePointerDiscardsQualifiers - The assignment
10662     /// discards qualifiers that we don't permit to be discarded,
10663     /// like address spaces.
10664     IncompatiblePointerDiscardsQualifiers,
10665 
10666     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
10667     /// changes address spaces in nested pointer types which is not allowed.
10668     /// For instance, converting __private int ** to __generic int ** is
10669     /// illegal even though __private could be converted to __generic.
10670     IncompatibleNestedPointerAddressSpaceMismatch,
10671 
10672     /// IncompatibleNestedPointerQualifiers - The assignment is between two
10673     /// nested pointer types, and the qualifiers other than the first two
10674     /// levels differ e.g. char ** -> const char **, but we accept them as an
10675     /// extension.
10676     IncompatibleNestedPointerQualifiers,
10677 
10678     /// IncompatibleVectors - The assignment is between two vector types that
10679     /// have the same size, which we accept as an extension.
10680     IncompatibleVectors,
10681 
10682     /// IntToBlockPointer - The assignment converts an int to a block
10683     /// pointer. We disallow this.
10684     IntToBlockPointer,
10685 
10686     /// IncompatibleBlockPointer - The assignment is between two block
10687     /// pointers types that are not compatible.
10688     IncompatibleBlockPointer,
10689 
10690     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
10691     /// id type and something else (that is incompatible with it). For example,
10692     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
10693     IncompatibleObjCQualifiedId,
10694 
10695     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
10696     /// object with __weak qualifier.
10697     IncompatibleObjCWeakRef,
10698 
10699     /// Incompatible - We reject this conversion outright, it is invalid to
10700     /// represent it in the AST.
10701     Incompatible
10702   };
10703 
10704   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
10705   /// assignment conversion type specified by ConvTy.  This returns true if the
10706   /// conversion was invalid or false if the conversion was accepted.
10707   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
10708                                 SourceLocation Loc,
10709                                 QualType DstType, QualType SrcType,
10710                                 Expr *SrcExpr, AssignmentAction Action,
10711                                 bool *Complained = nullptr);
10712 
10713   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
10714   /// enum. If AllowMask is true, then we also allow the complement of a valid
10715   /// value, to be used as a mask.
10716   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
10717                          bool AllowMask) const;
10718 
10719   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
10720   /// integer not in the range of enum values.
10721   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
10722                               Expr *SrcExpr);
10723 
10724   /// CheckAssignmentConstraints - Perform type checking for assignment,
10725   /// argument passing, variable initialization, and function return values.
10726   /// C99 6.5.16.
10727   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
10728                                                QualType LHSType,
10729                                                QualType RHSType);
10730 
10731   /// Check assignment constraints and optionally prepare for a conversion of
10732   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
10733   /// is true.
10734   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
10735                                                ExprResult &RHS,
10736                                                CastKind &Kind,
10737                                                bool ConvertRHS = true);
10738 
10739   /// Check assignment constraints for an assignment of RHS to LHSType.
10740   ///
10741   /// \param LHSType The destination type for the assignment.
10742   /// \param RHS The source expression for the assignment.
10743   /// \param Diagnose If \c true, diagnostics may be produced when checking
10744   ///        for assignability. If a diagnostic is produced, \p RHS will be
10745   ///        set to ExprError(). Note that this function may still return
10746   ///        without producing a diagnostic, even for an invalid assignment.
10747   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
10748   ///        in an audited Core Foundation API and does not need to be checked
10749   ///        for ARC retain issues.
10750   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
10751   ///        conversions necessary to perform the assignment. If \c false,
10752   ///        \p Diagnose must also be \c false.
10753   AssignConvertType CheckSingleAssignmentConstraints(
10754       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
10755       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
10756 
10757   // If the lhs type is a transparent union, check whether we
10758   // can initialize the transparent union with the given expression.
10759   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
10760                                                              ExprResult &RHS);
10761 
10762   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
10763 
10764   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
10765 
10766   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10767                                        AssignmentAction Action,
10768                                        bool AllowExplicit = false);
10769   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10770                                        AssignmentAction Action,
10771                                        bool AllowExplicit,
10772                                        ImplicitConversionSequence& ICS);
10773   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10774                                        const ImplicitConversionSequence& ICS,
10775                                        AssignmentAction Action,
10776                                        CheckedConversionKind CCK
10777                                           = CCK_ImplicitConversion);
10778   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10779                                        const StandardConversionSequence& SCS,
10780                                        AssignmentAction Action,
10781                                        CheckedConversionKind CCK);
10782 
10783   ExprResult PerformQualificationConversion(
10784       Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
10785       CheckedConversionKind CCK = CCK_ImplicitConversion);
10786 
10787   /// the following "Check" methods will return a valid/converted QualType
10788   /// or a null QualType (indicating an error diagnostic was issued).
10789 
10790   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
10791   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10792                            ExprResult &RHS);
10793   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10794                                  ExprResult &RHS);
10795   QualType CheckPointerToMemberOperands( // C++ 5.5
10796     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
10797     SourceLocation OpLoc, bool isIndirect);
10798   QualType CheckMultiplyDivideOperands( // C99 6.5.5
10799     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
10800     bool IsDivide);
10801   QualType CheckRemainderOperands( // C99 6.5.5
10802     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10803     bool IsCompAssign = false);
10804   QualType CheckAdditionOperands( // C99 6.5.6
10805     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10806     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
10807   QualType CheckSubtractionOperands( // C99 6.5.6
10808     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10809     QualType* CompLHSTy = nullptr);
10810   QualType CheckShiftOperands( // C99 6.5.7
10811     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10812     BinaryOperatorKind Opc, bool IsCompAssign = false);
10813   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
10814   QualType CheckCompareOperands( // C99 6.5.8/9
10815       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10816       BinaryOperatorKind Opc);
10817   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
10818       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10819       BinaryOperatorKind Opc);
10820   QualType CheckLogicalOperands( // C99 6.5.[13,14]
10821     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
10822     BinaryOperatorKind Opc);
10823   // CheckAssignmentOperands is used for both simple and compound assignment.
10824   // For simple assignment, pass both expressions and a null converted type.
10825   // For compound assignment, pass both expressions and the converted type.
10826   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
10827     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
10828 
10829   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
10830                                      UnaryOperatorKind Opcode, Expr *Op);
10831   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
10832                                          BinaryOperatorKind Opcode,
10833                                          Expr *LHS, Expr *RHS);
10834   ExprResult checkPseudoObjectRValue(Expr *E);
10835   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
10836 
10837   QualType CheckConditionalOperands( // C99 6.5.15
10838     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
10839     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
10840   QualType CXXCheckConditionalOperands( // C++ 5.16
10841     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
10842     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
10843   QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
10844                                           ExprResult &RHS,
10845                                           SourceLocation QuestionLoc);
10846   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
10847                                     bool ConvertArgs = true);
10848   QualType FindCompositePointerType(SourceLocation Loc,
10849                                     ExprResult &E1, ExprResult &E2,
10850                                     bool ConvertArgs = true) {
10851     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
10852     QualType Composite =
10853         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
10854     E1 = E1Tmp;
10855     E2 = E2Tmp;
10856     return Composite;
10857   }
10858 
10859   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
10860                                         SourceLocation QuestionLoc);
10861 
10862   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
10863                                   SourceLocation QuestionLoc);
10864 
10865   void DiagnoseAlwaysNonNullPointer(Expr *E,
10866                                     Expr::NullPointerConstantKind NullType,
10867                                     bool IsEqual, SourceRange Range);
10868 
10869   /// type checking for vector binary operators.
10870   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10871                                SourceLocation Loc, bool IsCompAssign,
10872                                bool AllowBothBool, bool AllowBoolConversion);
10873   QualType GetSignedVectorType(QualType V);
10874   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10875                                       SourceLocation Loc,
10876                                       BinaryOperatorKind Opc);
10877   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10878                                       SourceLocation Loc);
10879 
10880   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
10881   bool isLaxVectorConversion(QualType srcType, QualType destType);
10882 
10883   /// type checking declaration initializers (C99 6.7.8)
10884   bool CheckForConstantInitializer(Expr *e, QualType t);
10885 
10886   // type checking C++ declaration initializers (C++ [dcl.init]).
10887 
10888   /// ReferenceCompareResult - Expresses the result of comparing two
10889   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10890   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10891   enum ReferenceCompareResult {
10892     /// Ref_Incompatible - The two types are incompatible, so direct
10893     /// reference binding is not possible.
10894     Ref_Incompatible = 0,
10895     /// Ref_Related - The two types are reference-related, which means
10896     /// that their unqualified forms (T1 and T2) are either the same
10897     /// or T1 is a base class of T2.
10898     Ref_Related,
10899     /// Ref_Compatible - The two types are reference-compatible.
10900     Ref_Compatible
10901   };
10902 
10903   // Fake up a scoped enumeration that still contextually converts to bool.
10904   struct ReferenceConversionsScope {
10905     /// The conversions that would be performed on an lvalue of type T2 when
10906     /// binding a reference of type T1 to it, as determined when evaluating
10907     /// whether T1 is reference-compatible with T2.
10908     enum ReferenceConversions {
10909       Qualification = 0x1,
10910       NestedQualification = 0x2,
10911       Function = 0x4,
10912       DerivedToBase = 0x8,
10913       ObjC = 0x10,
10914       ObjCLifetime = 0x20,
10915 
10916       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10917     };
10918   };
10919   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10920 
10921   ReferenceCompareResult
10922   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10923                                ReferenceConversions *Conv = nullptr);
10924 
10925   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10926                                  Expr *CastExpr, CastKind &CastKind,
10927                                  ExprValueKind &VK, CXXCastPath &Path);
10928 
10929   /// Force an expression with unknown-type to an expression of the
10930   /// given type.
10931   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
10932 
10933   /// Type-check an expression that's being passed to an
10934   /// __unknown_anytype parameter.
10935   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
10936                                 Expr *result, QualType &paramType);
10937 
10938   // CheckVectorCast - check type constraints for vectors.
10939   // Since vectors are an extension, there are no C standard reference for this.
10940   // We allow casting between vectors and integer datatypes of the same size.
10941   // returns true if the cast is invalid
10942   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
10943                        CastKind &Kind);
10944 
10945   /// Prepare `SplattedExpr` for a vector splat operation, adding
10946   /// implicit casts if necessary.
10947   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
10948 
10949   // CheckExtVectorCast - check type constraints for extended vectors.
10950   // Since vectors are an extension, there are no C standard reference for this.
10951   // We allow casting between vectors and integer datatypes of the same size,
10952   // or vectors and the element type of that vector.
10953   // returns the cast expr
10954   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
10955                                 CastKind &Kind);
10956 
10957   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
10958                                         SourceLocation LParenLoc,
10959                                         Expr *CastExpr,
10960                                         SourceLocation RParenLoc);
10961 
10962   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
10963 
10964   /// Checks for invalid conversions and casts between
10965   /// retainable pointers and other pointer kinds for ARC and Weak.
10966   ARCConversionResult CheckObjCConversion(SourceRange castRange,
10967                                           QualType castType, Expr *&op,
10968                                           CheckedConversionKind CCK,
10969                                           bool Diagnose = true,
10970                                           bool DiagnoseCFAudited = false,
10971                                           BinaryOperatorKind Opc = BO_PtrMemD
10972                                           );
10973 
10974   Expr *stripARCUnbridgedCast(Expr *e);
10975   void diagnoseARCUnbridgedCast(Expr *e);
10976 
10977   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
10978                                              QualType ExprType);
10979 
10980   /// checkRetainCycles - Check whether an Objective-C message send
10981   /// might create an obvious retain cycle.
10982   void checkRetainCycles(ObjCMessageExpr *msg);
10983   void checkRetainCycles(Expr *receiver, Expr *argument);
10984   void checkRetainCycles(VarDecl *Var, Expr *Init);
10985 
10986   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
10987   /// to weak/__unsafe_unretained type.
10988   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
10989 
10990   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
10991   /// to weak/__unsafe_unretained expression.
10992   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
10993 
10994   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
10995   /// \param Method - May be null.
10996   /// \param [out] ReturnType - The return type of the send.
10997   /// \return true iff there were any incompatible types.
10998   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
10999                                  MultiExprArg Args, Selector Sel,
11000                                  ArrayRef<SourceLocation> SelectorLocs,
11001                                  ObjCMethodDecl *Method, bool isClassMessage,
11002                                  bool isSuperMessage, SourceLocation lbrac,
11003                                  SourceLocation rbrac, SourceRange RecRange,
11004                                  QualType &ReturnType, ExprValueKind &VK);
11005 
11006   /// Determine the result of a message send expression based on
11007   /// the type of the receiver, the method expected to receive the message,
11008   /// and the form of the message send.
11009   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11010                                     ObjCMethodDecl *Method, bool isClassMessage,
11011                                     bool isSuperMessage);
11012 
11013   /// If the given expression involves a message send to a method
11014   /// with a related result type, emit a note describing what happened.
11015   void EmitRelatedResultTypeNote(const Expr *E);
11016 
11017   /// Given that we had incompatible pointer types in a return
11018   /// statement, check whether we're in a method with a related result
11019   /// type, and if so, emit a note describing what happened.
11020   void EmitRelatedResultTypeNoteForReturn(QualType destType);
11021 
11022   class ConditionResult {
11023     Decl *ConditionVar;
11024     FullExprArg Condition;
11025     bool Invalid;
11026     bool HasKnownValue;
11027     bool KnownValue;
11028 
11029     friend class Sema;
11030     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11031                     bool IsConstexpr)
11032         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11033           HasKnownValue(IsConstexpr && Condition.get() &&
11034                         !Condition.get()->isValueDependent()),
11035           KnownValue(HasKnownValue &&
11036                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
11037     explicit ConditionResult(bool Invalid)
11038         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11039           HasKnownValue(false), KnownValue(false) {}
11040 
11041   public:
11042     ConditionResult() : ConditionResult(false) {}
11043     bool isInvalid() const { return Invalid; }
11044     std::pair<VarDecl *, Expr *> get() const {
11045       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11046                             Condition.get());
11047     }
11048     llvm::Optional<bool> getKnownValue() const {
11049       if (!HasKnownValue)
11050         return None;
11051       return KnownValue;
11052     }
11053   };
11054   static ConditionResult ConditionError() { return ConditionResult(true); }
11055 
11056   enum class ConditionKind {
11057     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
11058     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
11059     Switch       ///< An integral condition for a 'switch' statement.
11060   };
11061 
11062   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
11063                                  Expr *SubExpr, ConditionKind CK);
11064 
11065   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
11066                                          SourceLocation StmtLoc,
11067                                          ConditionKind CK);
11068 
11069   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
11070 
11071   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
11072                                     SourceLocation StmtLoc,
11073                                     ConditionKind CK);
11074   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11075 
11076   /// CheckBooleanCondition - Diagnose problems involving the use of
11077   /// the given expression as a boolean condition (e.g. in an if
11078   /// statement).  Also performs the standard function and array
11079   /// decays, possibly changing the input variable.
11080   ///
11081   /// \param Loc - A location associated with the condition, e.g. the
11082   /// 'if' keyword.
11083   /// \return true iff there were any errors
11084   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
11085                                    bool IsConstexpr = false);
11086 
11087   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
11088   /// found in an explicit(bool) specifier.
11089   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
11090 
11091   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
11092   /// Returns true if the explicit specifier is now resolved.
11093   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
11094 
11095   /// DiagnoseAssignmentAsCondition - Given that an expression is
11096   /// being used as a boolean condition, warn if it's an assignment.
11097   void DiagnoseAssignmentAsCondition(Expr *E);
11098 
11099   /// Redundant parentheses over an equality comparison can indicate
11100   /// that the user intended an assignment used as condition.
11101   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
11102 
11103   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
11104   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
11105 
11106   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
11107   /// the specified width and sign.  If an overflow occurs, detect it and emit
11108   /// the specified diagnostic.
11109   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
11110                                           unsigned NewWidth, bool NewSign,
11111                                           SourceLocation Loc, unsigned DiagID);
11112 
11113   /// Checks that the Objective-C declaration is declared in the global scope.
11114   /// Emits an error and marks the declaration as invalid if it's not declared
11115   /// in the global scope.
11116   bool CheckObjCDeclScope(Decl *D);
11117 
11118   /// Abstract base class used for diagnosing integer constant
11119   /// expression violations.
11120   class VerifyICEDiagnoser {
11121   public:
11122     bool Suppress;
11123 
11124     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
11125 
11126     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
11127     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
11128     virtual ~VerifyICEDiagnoser() { }
11129   };
11130 
11131   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
11132   /// and reports the appropriate diagnostics. Returns false on success.
11133   /// Can optionally return the value of the expression.
11134   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11135                                              VerifyICEDiagnoser &Diagnoser,
11136                                              bool AllowFold = true);
11137   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11138                                              unsigned DiagID,
11139                                              bool AllowFold = true);
11140   ExprResult VerifyIntegerConstantExpression(Expr *E,
11141                                              llvm::APSInt *Result = nullptr);
11142 
11143   /// VerifyBitField - verifies that a bit field expression is an ICE and has
11144   /// the correct width, and that the field type is valid.
11145   /// Returns false on success.
11146   /// Can optionally return whether the bit-field is of width 0
11147   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
11148                             QualType FieldTy, bool IsMsStruct,
11149                             Expr *BitWidth, bool *ZeroWidth = nullptr);
11150 
11151 private:
11152   unsigned ForceCUDAHostDeviceDepth = 0;
11153 
11154 public:
11155   /// Increments our count of the number of times we've seen a pragma forcing
11156   /// functions to be __host__ __device__.  So long as this count is greater
11157   /// than zero, all functions encountered will be __host__ __device__.
11158   void PushForceCUDAHostDevice();
11159 
11160   /// Decrements our count of the number of times we've seen a pragma forcing
11161   /// functions to be __host__ __device__.  Returns false if the count is 0
11162   /// before incrementing, so you can emit an error.
11163   bool PopForceCUDAHostDevice();
11164 
11165   /// Diagnostics that are emitted only if we discover that the given function
11166   /// must be codegen'ed.  Because handling these correctly adds overhead to
11167   /// compilation, this is currently only enabled for CUDA compilations.
11168   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
11169                  std::vector<PartialDiagnosticAt>>
11170       DeviceDeferredDiags;
11171 
11172   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
11173   /// key in a hashtable, both the FD and location are hashed.
11174   struct FunctionDeclAndLoc {
11175     CanonicalDeclPtr<FunctionDecl> FD;
11176     SourceLocation Loc;
11177   };
11178 
11179   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
11180   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
11181   /// same deferred diag twice.
11182   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
11183 
11184   /// An inverse call graph, mapping known-emitted functions to one of their
11185   /// known-emitted callers (plus the location of the call).
11186   ///
11187   /// Functions that we can tell a priori must be emitted aren't added to this
11188   /// map.
11189   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
11190                  /* Caller = */ FunctionDeclAndLoc>
11191       DeviceKnownEmittedFns;
11192 
11193   /// A partial call graph maintained during CUDA/OpenMP device code compilation
11194   /// to support deferred diagnostics.
11195   ///
11196   /// Functions are only added here if, at the time they're considered, they are
11197   /// not known-emitted.  As soon as we discover that a function is
11198   /// known-emitted, we remove it and everything it transitively calls from this
11199   /// set and add those functions to DeviceKnownEmittedFns.
11200   llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
11201                  /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
11202                                                  SourceLocation>>
11203       DeviceCallGraph;
11204 
11205   /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
11206   /// deferred.
11207   ///
11208   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
11209   /// which are not allowed to appear inside __device__ functions and are
11210   /// allowed to appear in __host__ __device__ functions only if the host+device
11211   /// function is never codegen'ed.
11212   ///
11213   /// To handle this, we use the notion of "deferred diagnostics", where we
11214   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
11215   ///
11216   /// This class lets you emit either a regular diagnostic, a deferred
11217   /// diagnostic, or no diagnostic at all, according to an argument you pass to
11218   /// its constructor, thus simplifying the process of creating these "maybe
11219   /// deferred" diagnostics.
11220   class DeviceDiagBuilder {
11221   public:
11222     enum Kind {
11223       /// Emit no diagnostics.
11224       K_Nop,
11225       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
11226       K_Immediate,
11227       /// Emit the diagnostic immediately, and, if it's a warning or error, also
11228       /// emit a call stack showing how this function can be reached by an a
11229       /// priori known-emitted function.
11230       K_ImmediateWithCallStack,
11231       /// Create a deferred diagnostic, which is emitted only if the function
11232       /// it's attached to is codegen'ed.  Also emit a call stack as with
11233       /// K_ImmediateWithCallStack.
11234       K_Deferred
11235     };
11236 
11237     DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
11238                       FunctionDecl *Fn, Sema &S);
11239     DeviceDiagBuilder(DeviceDiagBuilder &&D);
11240     DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
11241     ~DeviceDiagBuilder();
11242 
11243     /// Convertible to bool: True if we immediately emitted an error, false if
11244     /// we didn't emit an error or we created a deferred error.
11245     ///
11246     /// Example usage:
11247     ///
11248     ///   if (DeviceDiagBuilder(...) << foo << bar)
11249     ///     return ExprError();
11250     ///
11251     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
11252     /// want to use these instead of creating a DeviceDiagBuilder yourself.
11253     operator bool() const { return ImmediateDiag.hasValue(); }
11254 
11255     template <typename T>
11256     friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
11257                                                const T &Value) {
11258       if (Diag.ImmediateDiag.hasValue())
11259         *Diag.ImmediateDiag << Value;
11260       else if (Diag.PartialDiagId.hasValue())
11261         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
11262             << Value;
11263       return Diag;
11264     }
11265 
11266   private:
11267     Sema &S;
11268     SourceLocation Loc;
11269     unsigned DiagID;
11270     FunctionDecl *Fn;
11271     bool ShowCallStack;
11272 
11273     // Invariant: At most one of these Optionals has a value.
11274     // FIXME: Switch these to a Variant once that exists.
11275     llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
11276     llvm::Optional<unsigned> PartialDiagId;
11277   };
11278 
11279   /// Indicate that this function (and thus everything it transtively calls)
11280   /// will be codegen'ed, and emit any deferred diagnostics on this function and
11281   /// its (transitive) callees.
11282   void markKnownEmitted(
11283       Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
11284       SourceLocation OrigLoc,
11285       const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
11286 
11287   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11288   /// is "used as device code".
11289   ///
11290   /// - If CurContext is a __host__ function, does not emit any diagnostics.
11291   /// - If CurContext is a __device__ or __global__ function, emits the
11292   ///   diagnostics immediately.
11293   /// - If CurContext is a __host__ __device__ function and we are compiling for
11294   ///   the device, creates a diagnostic which is emitted if and when we realize
11295   ///   that the function will be codegen'ed.
11296   ///
11297   /// Example usage:
11298   ///
11299   ///  // Variable-length arrays are not allowed in CUDA device code.
11300   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
11301   ///    return ExprError();
11302   ///  // Otherwise, continue parsing as normal.
11303   DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
11304 
11305   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
11306   /// is "used as host code".
11307   ///
11308   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
11309   DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
11310 
11311   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11312   /// context is "used as device code".
11313   ///
11314   /// - If CurContext is a `declare target` function or it is known that the
11315   /// function is emitted for the device, emits the diagnostics immediately.
11316   /// - If CurContext is a non-`declare target` function and we are compiling
11317   ///   for the device, creates a diagnostic which is emitted if and when we
11318   ///   realize that the function will be codegen'ed.
11319   ///
11320   /// Example usage:
11321   ///
11322   ///  // Variable-length arrays are not allowed in NVPTX device code.
11323   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
11324   ///    return ExprError();
11325   ///  // Otherwise, continue parsing as normal.
11326   DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
11327 
11328   /// Creates a DeviceDiagBuilder that emits the diagnostic if the current
11329   /// context is "used as host code".
11330   ///
11331   /// - If CurContext is a `declare target` function or it is known that the
11332   /// function is emitted for the host, emits the diagnostics immediately.
11333   /// - If CurContext is a non-host function, just ignore it.
11334   ///
11335   /// Example usage:
11336   ///
11337   ///  // Variable-length arrays are not allowed in NVPTX device code.
11338   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
11339   ///    return ExprError();
11340   ///  // Otherwise, continue parsing as normal.
11341   DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
11342 
11343   DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
11344 
11345   enum CUDAFunctionTarget {
11346     CFT_Device,
11347     CFT_Global,
11348     CFT_Host,
11349     CFT_HostDevice,
11350     CFT_InvalidTarget
11351   };
11352 
11353   /// Determines whether the given function is a CUDA device/host/kernel/etc.
11354   /// function.
11355   ///
11356   /// Use this rather than examining the function's attributes yourself -- you
11357   /// will get it wrong.  Returns CFT_Host if D is null.
11358   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
11359                                         bool IgnoreImplicitHDAttr = false);
11360   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
11361 
11362   /// Gets the CUDA target for the current context.
11363   CUDAFunctionTarget CurrentCUDATarget() {
11364     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
11365   }
11366 
11367   // CUDA function call preference. Must be ordered numerically from
11368   // worst to best.
11369   enum CUDAFunctionPreference {
11370     CFP_Never,      // Invalid caller/callee combination.
11371     CFP_WrongSide,  // Calls from host-device to host or device
11372                     // function that do not match current compilation
11373                     // mode.
11374     CFP_HostDevice, // Any calls to host/device functions.
11375     CFP_SameSide,   // Calls from host-device to host or device
11376                     // function matching current compilation mode.
11377     CFP_Native,     // host-to-host or device-to-device calls.
11378   };
11379 
11380   /// Identifies relative preference of a given Caller/Callee
11381   /// combination, based on their host/device attributes.
11382   /// \param Caller function which needs address of \p Callee.
11383   ///               nullptr in case of global context.
11384   /// \param Callee target function
11385   ///
11386   /// \returns preference value for particular Caller/Callee combination.
11387   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
11388                                                 const FunctionDecl *Callee);
11389 
11390   /// Determines whether Caller may invoke Callee, based on their CUDA
11391   /// host/device attributes.  Returns false if the call is not allowed.
11392   ///
11393   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
11394   /// semantically correct CUDA programs, but only if they're never codegen'ed.
11395   bool IsAllowedCUDACall(const FunctionDecl *Caller,
11396                          const FunctionDecl *Callee) {
11397     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
11398   }
11399 
11400   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
11401   /// depending on FD and the current compilation settings.
11402   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
11403                                    const LookupResult &Previous);
11404 
11405 public:
11406   /// Check whether we're allowed to call Callee from the current context.
11407   ///
11408   /// - If the call is never allowed in a semantically-correct program
11409   ///   (CFP_Never), emits an error and returns false.
11410   ///
11411   /// - If the call is allowed in semantically-correct programs, but only if
11412   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
11413   ///   be emitted if and when the caller is codegen'ed, and returns true.
11414   ///
11415   ///   Will only create deferred diagnostics for a given SourceLocation once,
11416   ///   so you can safely call this multiple times without generating duplicate
11417   ///   deferred errors.
11418   ///
11419   /// - Otherwise, returns true without emitting any diagnostics.
11420   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
11421 
11422   /// Set __device__ or __host__ __device__ attributes on the given lambda
11423   /// operator() method.
11424   ///
11425   /// CUDA lambdas declared inside __device__ or __global__ functions inherit
11426   /// the __device__ attribute.  Similarly, lambdas inside __host__ __device__
11427   /// functions become __host__ __device__ themselves.
11428   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
11429 
11430   /// Finds a function in \p Matches with highest calling priority
11431   /// from \p Caller context and erases all functions with lower
11432   /// calling priority.
11433   void EraseUnwantedCUDAMatches(
11434       const FunctionDecl *Caller,
11435       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
11436 
11437   /// Given a implicit special member, infer its CUDA target from the
11438   /// calls it needs to make to underlying base/field special members.
11439   /// \param ClassDecl the class for which the member is being created.
11440   /// \param CSM the kind of special member.
11441   /// \param MemberDecl the special member itself.
11442   /// \param ConstRHS true if this is a copy operation with a const object on
11443   ///        its RHS.
11444   /// \param Diagnose true if this call should emit diagnostics.
11445   /// \return true if there was an error inferring.
11446   /// The result of this call is implicit CUDA target attribute(s) attached to
11447   /// the member declaration.
11448   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
11449                                                CXXSpecialMember CSM,
11450                                                CXXMethodDecl *MemberDecl,
11451                                                bool ConstRHS,
11452                                                bool Diagnose);
11453 
11454   /// \return true if \p CD can be considered empty according to CUDA
11455   /// (E.2.3.1 in CUDA 7.5 Programming guide).
11456   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
11457   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
11458 
11459   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
11460   // case of error emits appropriate diagnostic and invalidates \p Var.
11461   //
11462   // \details CUDA allows only empty constructors as initializers for global
11463   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
11464   // __shared__ variables whether they are local or not (they all are implicitly
11465   // static in CUDA). One exception is that CUDA allows constant initializers
11466   // for __constant__ and __device__ variables.
11467   void checkAllowedCUDAInitializer(VarDecl *VD);
11468 
11469   /// Check whether NewFD is a valid overload for CUDA. Emits
11470   /// diagnostics and invalidates NewFD if not.
11471   void checkCUDATargetOverload(FunctionDecl *NewFD,
11472                                const LookupResult &Previous);
11473   /// Copies target attributes from the template TD to the function FD.
11474   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
11475 
11476   /// Returns the name of the launch configuration function.  This is the name
11477   /// of the function that will be called to configure kernel call, with the
11478   /// parameters specified via <<<>>>.
11479   std::string getCudaConfigureFuncName() const;
11480 
11481   /// \name Code completion
11482   //@{
11483   /// Describes the context in which code completion occurs.
11484   enum ParserCompletionContext {
11485     /// Code completion occurs at top-level or namespace context.
11486     PCC_Namespace,
11487     /// Code completion occurs within a class, struct, or union.
11488     PCC_Class,
11489     /// Code completion occurs within an Objective-C interface, protocol,
11490     /// or category.
11491     PCC_ObjCInterface,
11492     /// Code completion occurs within an Objective-C implementation or
11493     /// category implementation
11494     PCC_ObjCImplementation,
11495     /// Code completion occurs within the list of instance variables
11496     /// in an Objective-C interface, protocol, category, or implementation.
11497     PCC_ObjCInstanceVariableList,
11498     /// Code completion occurs following one or more template
11499     /// headers.
11500     PCC_Template,
11501     /// Code completion occurs following one or more template
11502     /// headers within a class.
11503     PCC_MemberTemplate,
11504     /// Code completion occurs within an expression.
11505     PCC_Expression,
11506     /// Code completion occurs within a statement, which may
11507     /// also be an expression or a declaration.
11508     PCC_Statement,
11509     /// Code completion occurs at the beginning of the
11510     /// initialization statement (or expression) in a for loop.
11511     PCC_ForInit,
11512     /// Code completion occurs within the condition of an if,
11513     /// while, switch, or for statement.
11514     PCC_Condition,
11515     /// Code completion occurs within the body of a function on a
11516     /// recovery path, where we do not have a specific handle on our position
11517     /// in the grammar.
11518     PCC_RecoveryInFunction,
11519     /// Code completion occurs where only a type is permitted.
11520     PCC_Type,
11521     /// Code completion occurs in a parenthesized expression, which
11522     /// might also be a type cast.
11523     PCC_ParenthesizedExpression,
11524     /// Code completion occurs within a sequence of declaration
11525     /// specifiers within a function, method, or block.
11526     PCC_LocalDeclarationSpecifiers
11527   };
11528 
11529   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
11530   void CodeCompleteOrdinaryName(Scope *S,
11531                                 ParserCompletionContext CompletionContext);
11532   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
11533                             bool AllowNonIdentifiers,
11534                             bool AllowNestedNameSpecifiers);
11535 
11536   struct CodeCompleteExpressionData;
11537   void CodeCompleteExpression(Scope *S,
11538                               const CodeCompleteExpressionData &Data);
11539   void CodeCompleteExpression(Scope *S, QualType PreferredType,
11540                               bool IsParenthesized = false);
11541   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
11542                                        SourceLocation OpLoc, bool IsArrow,
11543                                        bool IsBaseExprStatement,
11544                                        QualType PreferredType);
11545   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
11546                                      QualType PreferredType);
11547   void CodeCompleteTag(Scope *S, unsigned TagSpec);
11548   void CodeCompleteTypeQualifiers(DeclSpec &DS);
11549   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
11550                                       const VirtSpecifiers *VS = nullptr);
11551   void CodeCompleteBracketDeclarator(Scope *S);
11552   void CodeCompleteCase(Scope *S);
11553   /// Reports signatures for a call to CodeCompleteConsumer and returns the
11554   /// preferred type for the current argument. Returned type can be null.
11555   QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
11556                                     SourceLocation OpenParLoc);
11557   QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
11558                                            SourceLocation Loc,
11559                                            ArrayRef<Expr *> Args,
11560                                            SourceLocation OpenParLoc);
11561   QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
11562                                               CXXScopeSpec SS,
11563                                               ParsedType TemplateTypeTy,
11564                                               ArrayRef<Expr *> ArgExprs,
11565                                               IdentifierInfo *II,
11566                                               SourceLocation OpenParLoc);
11567   void CodeCompleteInitializer(Scope *S, Decl *D);
11568   void CodeCompleteAfterIf(Scope *S);
11569 
11570   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
11571                                bool IsUsingDeclaration, QualType BaseType,
11572                                QualType PreferredType);
11573   void CodeCompleteUsing(Scope *S);
11574   void CodeCompleteUsingDirective(Scope *S);
11575   void CodeCompleteNamespaceDecl(Scope *S);
11576   void CodeCompleteNamespaceAliasDecl(Scope *S);
11577   void CodeCompleteOperatorName(Scope *S);
11578   void CodeCompleteConstructorInitializer(
11579                                 Decl *Constructor,
11580                                 ArrayRef<CXXCtorInitializer *> Initializers);
11581 
11582   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
11583                                     bool AfterAmpersand);
11584 
11585   void CodeCompleteObjCAtDirective(Scope *S);
11586   void CodeCompleteObjCAtVisibility(Scope *S);
11587   void CodeCompleteObjCAtStatement(Scope *S);
11588   void CodeCompleteObjCAtExpression(Scope *S);
11589   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
11590   void CodeCompleteObjCPropertyGetter(Scope *S);
11591   void CodeCompleteObjCPropertySetter(Scope *S);
11592   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
11593                                    bool IsParameter);
11594   void CodeCompleteObjCMessageReceiver(Scope *S);
11595   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
11596                                     ArrayRef<IdentifierInfo *> SelIdents,
11597                                     bool AtArgumentExpression);
11598   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
11599                                     ArrayRef<IdentifierInfo *> SelIdents,
11600                                     bool AtArgumentExpression,
11601                                     bool IsSuper = false);
11602   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
11603                                        ArrayRef<IdentifierInfo *> SelIdents,
11604                                        bool AtArgumentExpression,
11605                                        ObjCInterfaceDecl *Super = nullptr);
11606   void CodeCompleteObjCForCollection(Scope *S,
11607                                      DeclGroupPtrTy IterationVar);
11608   void CodeCompleteObjCSelector(Scope *S,
11609                                 ArrayRef<IdentifierInfo *> SelIdents);
11610   void CodeCompleteObjCProtocolReferences(
11611                                          ArrayRef<IdentifierLocPair> Protocols);
11612   void CodeCompleteObjCProtocolDecl(Scope *S);
11613   void CodeCompleteObjCInterfaceDecl(Scope *S);
11614   void CodeCompleteObjCSuperclass(Scope *S,
11615                                   IdentifierInfo *ClassName,
11616                                   SourceLocation ClassNameLoc);
11617   void CodeCompleteObjCImplementationDecl(Scope *S);
11618   void CodeCompleteObjCInterfaceCategory(Scope *S,
11619                                          IdentifierInfo *ClassName,
11620                                          SourceLocation ClassNameLoc);
11621   void CodeCompleteObjCImplementationCategory(Scope *S,
11622                                               IdentifierInfo *ClassName,
11623                                               SourceLocation ClassNameLoc);
11624   void CodeCompleteObjCPropertyDefinition(Scope *S);
11625   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
11626                                               IdentifierInfo *PropertyName);
11627   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
11628                                   ParsedType ReturnType);
11629   void CodeCompleteObjCMethodDeclSelector(Scope *S,
11630                                           bool IsInstanceMethod,
11631                                           bool AtParameterName,
11632                                           ParsedType ReturnType,
11633                                           ArrayRef<IdentifierInfo *> SelIdents);
11634   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
11635                                             SourceLocation ClassNameLoc,
11636                                             bool IsBaseExprStatement);
11637   void CodeCompletePreprocessorDirective(bool InConditional);
11638   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
11639   void CodeCompletePreprocessorMacroName(bool IsDefinition);
11640   void CodeCompletePreprocessorExpression();
11641   void CodeCompletePreprocessorMacroArgument(Scope *S,
11642                                              IdentifierInfo *Macro,
11643                                              MacroInfo *MacroInfo,
11644                                              unsigned Argument);
11645   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
11646   void CodeCompleteNaturalLanguage();
11647   void CodeCompleteAvailabilityPlatformName();
11648   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
11649                                    CodeCompletionTUInfo &CCTUInfo,
11650                   SmallVectorImpl<CodeCompletionResult> &Results);
11651   //@}
11652 
11653   //===--------------------------------------------------------------------===//
11654   // Extra semantic analysis beyond the C type system
11655 
11656 public:
11657   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
11658                                                 unsigned ByteNo) const;
11659 
11660 private:
11661   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11662                         const ArraySubscriptExpr *ASE=nullptr,
11663                         bool AllowOnePastEnd=true, bool IndexNegated=false);
11664   void CheckArrayAccess(const Expr *E);
11665   // Used to grab the relevant information from a FormatAttr and a
11666   // FunctionDeclaration.
11667   struct FormatStringInfo {
11668     unsigned FormatIdx;
11669     unsigned FirstDataArg;
11670     bool HasVAListArg;
11671   };
11672 
11673   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
11674                                   FormatStringInfo *FSI);
11675   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
11676                          const FunctionProtoType *Proto);
11677   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
11678                            ArrayRef<const Expr *> Args);
11679   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
11680                         const FunctionProtoType *Proto);
11681   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
11682   void CheckConstructorCall(FunctionDecl *FDecl,
11683                             ArrayRef<const Expr *> Args,
11684                             const FunctionProtoType *Proto,
11685                             SourceLocation Loc);
11686 
11687   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
11688                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
11689                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
11690                  VariadicCallType CallType);
11691 
11692   bool CheckObjCString(Expr *Arg);
11693   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
11694 
11695   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
11696                                       unsigned BuiltinID, CallExpr *TheCall);
11697   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
11698 
11699   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
11700                                     unsigned MaxWidth);
11701   bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11702   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11703   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11704 
11705   bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11706   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11707   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11708   bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11709   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11710   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11711   bool CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
11712   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
11713   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11714   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
11715   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
11716   bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11717   bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
11718 
11719   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
11720   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
11721   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
11722   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
11723   bool SemaBuiltinVSX(CallExpr *TheCall);
11724   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
11725 
11726 public:
11727   // Used by C++ template instantiation.
11728   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
11729   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
11730                                    SourceLocation BuiltinLoc,
11731                                    SourceLocation RParenLoc);
11732 
11733 private:
11734   bool SemaBuiltinPrefetch(CallExpr *TheCall);
11735   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
11736   bool SemaBuiltinAssume(CallExpr *TheCall);
11737   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
11738   bool SemaBuiltinLongjmp(CallExpr *TheCall);
11739   bool SemaBuiltinSetjmp(CallExpr *TheCall);
11740   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
11741   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
11742   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
11743                                      AtomicExpr::AtomicOp Op);
11744   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
11745                                                     bool IsDelete);
11746   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
11747                               llvm::APSInt &Result);
11748   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
11749                                    int High, bool RangeIsError = true);
11750   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
11751                                       unsigned Multiple);
11752   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
11753   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum);
11754   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum);
11755   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
11756                                 int ArgNum, unsigned ExpectedFieldNum,
11757                                 bool AllowName);
11758   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
11759 public:
11760   enum FormatStringType {
11761     FST_Scanf,
11762     FST_Printf,
11763     FST_NSString,
11764     FST_Strftime,
11765     FST_Strfmon,
11766     FST_Kprintf,
11767     FST_FreeBSDKPrintf,
11768     FST_OSTrace,
11769     FST_OSLog,
11770     FST_Unknown
11771   };
11772   static FormatStringType GetFormatStringType(const FormatAttr *Format);
11773 
11774   bool FormatStringHasSArg(const StringLiteral *FExpr);
11775 
11776   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
11777 
11778 private:
11779   bool CheckFormatArguments(const FormatAttr *Format,
11780                             ArrayRef<const Expr *> Args,
11781                             bool IsCXXMember,
11782                             VariadicCallType CallType,
11783                             SourceLocation Loc, SourceRange Range,
11784                             llvm::SmallBitVector &CheckedVarArgs);
11785   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
11786                             bool HasVAListArg, unsigned format_idx,
11787                             unsigned firstDataArg, FormatStringType Type,
11788                             VariadicCallType CallType,
11789                             SourceLocation Loc, SourceRange range,
11790                             llvm::SmallBitVector &CheckedVarArgs);
11791 
11792   void CheckAbsoluteValueFunction(const CallExpr *Call,
11793                                   const FunctionDecl *FDecl);
11794 
11795   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
11796 
11797   void CheckMemaccessArguments(const CallExpr *Call,
11798                                unsigned BId,
11799                                IdentifierInfo *FnName);
11800 
11801   void CheckStrlcpycatArguments(const CallExpr *Call,
11802                                 IdentifierInfo *FnName);
11803 
11804   void CheckStrncatArguments(const CallExpr *Call,
11805                              IdentifierInfo *FnName);
11806 
11807   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11808                           SourceLocation ReturnLoc,
11809                           bool isObjCMethod = false,
11810                           const AttrVec *Attrs = nullptr,
11811                           const FunctionDecl *FD = nullptr);
11812 
11813 public:
11814   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
11815 
11816 private:
11817   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
11818   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
11819   void CheckForIntOverflow(Expr *E);
11820   void CheckUnsequencedOperations(const Expr *E);
11821 
11822   /// Perform semantic checks on a completed expression. This will either
11823   /// be a full-expression or a default argument expression.
11824   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
11825                           bool IsConstexpr = false);
11826 
11827   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
11828                                    Expr *Init);
11829 
11830   /// Check if there is a field shadowing.
11831   void CheckShadowInheritedFields(const SourceLocation &Loc,
11832                                   DeclarationName FieldName,
11833                                   const CXXRecordDecl *RD,
11834                                   bool DeclIsField = true);
11835 
11836   /// Check if the given expression contains 'break' or 'continue'
11837   /// statement that produces control flow different from GCC.
11838   void CheckBreakContinueBinding(Expr *E);
11839 
11840   /// Check whether receiver is mutable ObjC container which
11841   /// attempts to add itself into the container
11842   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
11843 
11844   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
11845   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
11846                                  bool DeleteWasArrayForm);
11847 public:
11848   /// Register a magic integral constant to be used as a type tag.
11849   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11850                                   uint64_t MagicValue, QualType Type,
11851                                   bool LayoutCompatible, bool MustBeNull);
11852 
11853   struct TypeTagData {
11854     TypeTagData() {}
11855 
11856     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
11857         Type(Type), LayoutCompatible(LayoutCompatible),
11858         MustBeNull(MustBeNull)
11859     {}
11860 
11861     QualType Type;
11862 
11863     /// If true, \c Type should be compared with other expression's types for
11864     /// layout-compatibility.
11865     unsigned LayoutCompatible : 1;
11866     unsigned MustBeNull : 1;
11867   };
11868 
11869   /// A pair of ArgumentKind identifier and magic value.  This uniquely
11870   /// identifies the magic value.
11871   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
11872 
11873 private:
11874   /// A map from magic value to type information.
11875   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
11876       TypeTagForDatatypeMagicValues;
11877 
11878   /// Peform checks on a call of a function with argument_with_type_tag
11879   /// or pointer_with_type_tag attributes.
11880   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11881                                 const ArrayRef<const Expr *> ExprArgs,
11882                                 SourceLocation CallSiteLoc);
11883 
11884   /// Check if we are taking the address of a packed field
11885   /// as this may be a problem if the pointer value is dereferenced.
11886   void CheckAddressOfPackedMember(Expr *rhs);
11887 
11888   /// The parser's current scope.
11889   ///
11890   /// The parser maintains this state here.
11891   Scope *CurScope;
11892 
11893   mutable IdentifierInfo *Ident_super;
11894   mutable IdentifierInfo *Ident___float128;
11895 
11896   /// Nullability type specifiers.
11897   IdentifierInfo *Ident__Nonnull = nullptr;
11898   IdentifierInfo *Ident__Nullable = nullptr;
11899   IdentifierInfo *Ident__Null_unspecified = nullptr;
11900 
11901   IdentifierInfo *Ident_NSError = nullptr;
11902 
11903   /// The handler for the FileChanged preprocessor events.
11904   ///
11905   /// Used for diagnostics that implement custom semantic analysis for #include
11906   /// directives, like -Wpragma-pack.
11907   sema::SemaPPCallbacks *SemaPPCallbackHandler;
11908 
11909 protected:
11910   friend class Parser;
11911   friend class InitializationSequence;
11912   friend class ASTReader;
11913   friend class ASTDeclReader;
11914   friend class ASTWriter;
11915 
11916 public:
11917   /// Retrieve the keyword associated
11918   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
11919 
11920   /// The struct behind the CFErrorRef pointer.
11921   RecordDecl *CFError = nullptr;
11922 
11923   /// Retrieve the identifier "NSError".
11924   IdentifierInfo *getNSErrorIdent();
11925 
11926   /// Retrieve the parser's current scope.
11927   ///
11928   /// This routine must only be used when it is certain that semantic analysis
11929   /// and the parser are in precisely the same context, which is not the case
11930   /// when, e.g., we are performing any kind of template instantiation.
11931   /// Therefore, the only safe places to use this scope are in the parser
11932   /// itself and in routines directly invoked from the parser and *never* from
11933   /// template substitution or instantiation.
11934   Scope *getCurScope() const { return CurScope; }
11935 
11936   void incrementMSManglingNumber() const {
11937     return CurScope->incrementMSManglingNumber();
11938   }
11939 
11940   IdentifierInfo *getSuperIdentifier() const;
11941   IdentifierInfo *getFloat128Identifier() const;
11942 
11943   Decl *getObjCDeclContext() const;
11944 
11945   DeclContext *getCurLexicalContext() const {
11946     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
11947   }
11948 
11949   const DeclContext *getCurObjCLexicalContext() const {
11950     const DeclContext *DC = getCurLexicalContext();
11951     // A category implicitly has the attribute of the interface.
11952     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
11953       DC = CatD->getClassInterface();
11954     return DC;
11955   }
11956 
11957   /// Determine the number of levels of enclosing template parameters. This is
11958   /// only usable while parsing. Note that this does not include dependent
11959   /// contexts in which no template parameters have yet been declared, such as
11960   /// in a terse function template or generic lambda before the first 'auto' is
11961   /// encountered.
11962   unsigned getTemplateDepth(Scope *S) const;
11963 
11964   /// To be used for checking whether the arguments being passed to
11965   /// function exceeds the number of parameters expected for it.
11966   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
11967                                bool PartialOverloading = false) {
11968     // We check whether we're just after a comma in code-completion.
11969     if (NumArgs > 0 && PartialOverloading)
11970       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
11971     return NumArgs > NumParams;
11972   }
11973 
11974   // Emitting members of dllexported classes is delayed until the class
11975   // (including field initializers) is fully parsed.
11976   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
11977   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
11978 
11979 private:
11980   int ParsingClassDepth = 0;
11981 
11982   class SavePendingParsedClassStateRAII {
11983   public:
11984     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
11985 
11986     ~SavePendingParsedClassStateRAII() {
11987       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
11988              "there shouldn't be any pending delayed exception spec checks");
11989       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
11990              "there shouldn't be any pending delayed exception spec checks");
11991       swapSavedState();
11992     }
11993 
11994   private:
11995     Sema &S;
11996     decltype(DelayedOverridingExceptionSpecChecks)
11997         SavedOverridingExceptionSpecChecks;
11998     decltype(DelayedEquivalentExceptionSpecChecks)
11999         SavedEquivalentExceptionSpecChecks;
12000 
12001     void swapSavedState() {
12002       SavedOverridingExceptionSpecChecks.swap(
12003           S.DelayedOverridingExceptionSpecChecks);
12004       SavedEquivalentExceptionSpecChecks.swap(
12005           S.DelayedEquivalentExceptionSpecChecks);
12006     }
12007   };
12008 
12009   /// Helper class that collects misaligned member designations and
12010   /// their location info for delayed diagnostics.
12011   struct MisalignedMember {
12012     Expr *E;
12013     RecordDecl *RD;
12014     ValueDecl *MD;
12015     CharUnits Alignment;
12016 
12017     MisalignedMember() : E(), RD(), MD(), Alignment() {}
12018     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12019                      CharUnits Alignment)
12020         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
12021     explicit MisalignedMember(Expr *E)
12022         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12023 
12024     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12025   };
12026   /// Small set of gathered accesses to potentially misaligned members
12027   /// due to the packed attribute.
12028   SmallVector<MisalignedMember, 4> MisalignedMembers;
12029 
12030   /// Adds an expression to the set of gathered misaligned members.
12031   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12032                                      CharUnits Alignment);
12033 
12034 public:
12035   /// Diagnoses the current set of gathered accesses. This typically
12036   /// happens at full expression level. The set is cleared after emitting the
12037   /// diagnostics.
12038   void DiagnoseMisalignedMembers();
12039 
12040   /// This function checks if the expression is in the sef of potentially
12041   /// misaligned members and it is converted to some pointer type T with lower
12042   /// or equal alignment requirements. If so it removes it. This is used when
12043   /// we do not want to diagnose such misaligned access (e.g. in conversions to
12044   /// void*).
12045   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
12046 
12047   /// This function calls Action when it determines that E designates a
12048   /// misaligned member due to the packed attribute. This is used to emit
12049   /// local diagnostics like in reference binding.
12050   void RefersToMemberWithReducedAlignment(
12051       Expr *E,
12052       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12053           Action);
12054 
12055   /// Describes the reason a calling convention specification was ignored, used
12056   /// for diagnostics.
12057   enum class CallingConventionIgnoredReason {
12058     ForThisTarget = 0,
12059     VariadicFunction,
12060     ConstructorDestructor,
12061     BuiltinFunction
12062   };
12063 };
12064 
12065 /// RAII object that enters a new expression evaluation context.
12066 class EnterExpressionEvaluationContext {
12067   Sema &Actions;
12068   bool Entered = true;
12069 
12070 public:
12071   EnterExpressionEvaluationContext(
12072       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12073       Decl *LambdaContextDecl = nullptr,
12074       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12075           Sema::ExpressionEvaluationContextRecord::EK_Other,
12076       bool ShouldEnter = true)
12077       : Actions(Actions), Entered(ShouldEnter) {
12078     if (Entered)
12079       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
12080                                               ExprContext);
12081   }
12082   EnterExpressionEvaluationContext(
12083       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12084       Sema::ReuseLambdaContextDecl_t,
12085       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12086           Sema::ExpressionEvaluationContextRecord::EK_Other)
12087       : Actions(Actions) {
12088     Actions.PushExpressionEvaluationContext(
12089         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
12090   }
12091 
12092   enum InitListTag { InitList };
12093   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
12094                                    bool ShouldEnter = true)
12095       : Actions(Actions), Entered(false) {
12096     // In C++11 onwards, narrowing checks are performed on the contents of
12097     // braced-init-lists, even when they occur within unevaluated operands.
12098     // Therefore we still need to instantiate constexpr functions used in such
12099     // a context.
12100     if (ShouldEnter && Actions.isUnevaluatedContext() &&
12101         Actions.getLangOpts().CPlusPlus11) {
12102       Actions.PushExpressionEvaluationContext(
12103           Sema::ExpressionEvaluationContext::UnevaluatedList);
12104       Entered = true;
12105     }
12106   }
12107 
12108   ~EnterExpressionEvaluationContext() {
12109     if (Entered)
12110       Actions.PopExpressionEvaluationContext();
12111   }
12112 };
12113 
12114 DeductionFailureInfo
12115 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
12116                          sema::TemplateDeductionInfo &Info);
12117 
12118 /// Contains a late templated function.
12119 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
12120 struct LateParsedTemplate {
12121   CachedTokens Toks;
12122   /// The template function declaration to be late parsed.
12123   Decl *D;
12124 };
12125 } // end namespace clang
12126 
12127 namespace llvm {
12128 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
12129 // SourceLocation.
12130 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
12131   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
12132   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
12133 
12134   static FunctionDeclAndLoc getEmptyKey() {
12135     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
12136   }
12137 
12138   static FunctionDeclAndLoc getTombstoneKey() {
12139     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
12140   }
12141 
12142   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
12143     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
12144                         FDL.Loc.getRawEncoding());
12145   }
12146 
12147   static bool isEqual(const FunctionDeclAndLoc &LHS,
12148                       const FunctionDeclAndLoc &RHS) {
12149     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
12150   }
12151 };
12152 } // namespace llvm
12153 
12154 #endif
12155