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