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/ASTFwd.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Availability.h"
21 #include "clang/AST/ComparisonCategories.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprConcepts.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/LocInfoType.h"
31 #include "clang/AST/MangleNumberingContext.h"
32 #include "clang/AST/NSAPI.h"
33 #include "clang/AST/PrettyPrinter.h"
34 #include "clang/AST/StmtCXX.h"
35 #include "clang/AST/StmtOpenMP.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/TypeOrdering.h"
38 #include "clang/Basic/BitmaskEnum.h"
39 #include "clang/Basic/Builtins.h"
40 #include "clang/Basic/DarwinSDKInfo.h"
41 #include "clang/Basic/ExpressionTraits.h"
42 #include "clang/Basic/Module.h"
43 #include "clang/Basic/OpenCLOptions.h"
44 #include "clang/Basic/OpenMPKinds.h"
45 #include "clang/Basic/PragmaKinds.h"
46 #include "clang/Basic/Specifiers.h"
47 #include "clang/Basic/TemplateKinds.h"
48 #include "clang/Basic/TypeTraits.h"
49 #include "clang/Sema/AnalysisBasedWarnings.h"
50 #include "clang/Sema/CleanupInfo.h"
51 #include "clang/Sema/DeclSpec.h"
52 #include "clang/Sema/ExternalSemaSource.h"
53 #include "clang/Sema/IdentifierResolver.h"
54 #include "clang/Sema/ObjCMethodList.h"
55 #include "clang/Sema/Ownership.h"
56 #include "clang/Sema/Scope.h"
57 #include "clang/Sema/SemaConcept.h"
58 #include "clang/Sema/TypoCorrection.h"
59 #include "clang/Sema/Weak.h"
60 #include "llvm/ADT/ArrayRef.h"
61 #include "llvm/ADT/Optional.h"
62 #include "llvm/ADT/SetVector.h"
63 #include "llvm/ADT/SmallBitVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/SmallSet.h"
66 #include "llvm/ADT/SmallVector.h"
67 #include "llvm/ADT/TinyPtrVector.h"
68 #include "llvm/Frontend/OpenMP/OMPConstants.h"
69 #include <deque>
70 #include <memory>
71 #include <string>
72 #include <tuple>
73 #include <vector>
74 
75 namespace llvm {
76   class APSInt;
77   template <typename ValueT, typename ValueInfoT> class DenseSet;
78   class SmallBitVector;
79   struct InlineAsmIdentifierInfo;
80 }
81 
82 namespace clang {
83   class ADLResult;
84   class ASTConsumer;
85   class ASTContext;
86   class ASTMutationListener;
87   class ASTReader;
88   class ASTWriter;
89   class ArrayType;
90   class ParsedAttr;
91   class BindingDecl;
92   class BlockDecl;
93   class CapturedDecl;
94   class CXXBasePath;
95   class CXXBasePaths;
96   class CXXBindTemporaryExpr;
97   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98   class CXXConstructorDecl;
99   class CXXConversionDecl;
100   class CXXDeleteExpr;
101   class CXXDestructorDecl;
102   class CXXFieldCollector;
103   class CXXMemberCallExpr;
104   class CXXMethodDecl;
105   class CXXScopeSpec;
106   class CXXTemporary;
107   class CXXTryStmt;
108   class CallExpr;
109   class ClassTemplateDecl;
110   class ClassTemplatePartialSpecializationDecl;
111   class ClassTemplateSpecializationDecl;
112   class VarTemplatePartialSpecializationDecl;
113   class CodeCompleteConsumer;
114   class CodeCompletionAllocator;
115   class CodeCompletionTUInfo;
116   class CodeCompletionResult;
117   class CoroutineBodyStmt;
118   class Decl;
119   class DeclAccessPair;
120   class DeclContext;
121   class DeclRefExpr;
122   class DeclaratorDecl;
123   class DeducedTemplateArgument;
124   class DependentDiagnostic;
125   class DesignatedInitExpr;
126   class Designation;
127   class EnableIfAttr;
128   class EnumConstantDecl;
129   class Expr;
130   class ExtVectorType;
131   class FormatAttr;
132   class FriendDecl;
133   class FunctionDecl;
134   class FunctionProtoType;
135   class FunctionTemplateDecl;
136   class ImplicitConversionSequence;
137   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138   class InitListExpr;
139   class InitializationKind;
140   class InitializationSequence;
141   class InitializedEntity;
142   class IntegerLiteral;
143   class LabelStmt;
144   class LambdaExpr;
145   class LangOptions;
146   class LocalInstantiationScope;
147   class LookupResult;
148   class MacroInfo;
149   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150   class ModuleLoader;
151   class MultiLevelTemplateArgumentList;
152   class NamedDecl;
153   class ObjCCategoryDecl;
154   class ObjCCategoryImplDecl;
155   class ObjCCompatibleAliasDecl;
156   class ObjCContainerDecl;
157   class ObjCImplDecl;
158   class ObjCImplementationDecl;
159   class ObjCInterfaceDecl;
160   class ObjCIvarDecl;
161   template <class T> class ObjCList;
162   class ObjCMessageExpr;
163   class ObjCMethodDecl;
164   class ObjCPropertyDecl;
165   class ObjCProtocolDecl;
166   class OMPThreadPrivateDecl;
167   class OMPRequiresDecl;
168   class OMPDeclareReductionDecl;
169   class OMPDeclareSimdDecl;
170   class OMPClause;
171   struct OMPVarListLocTy;
172   struct OverloadCandidate;
173   enum class OverloadCandidateParamOrder : char;
174   enum OverloadCandidateRewriteKind : unsigned;
175   class OverloadCandidateSet;
176   class OverloadExpr;
177   class ParenListExpr;
178   class ParmVarDecl;
179   class Preprocessor;
180   class PseudoDestructorTypeStorage;
181   class PseudoObjectExpr;
182   class QualType;
183   class StandardConversionSequence;
184   class Stmt;
185   class StringLiteral;
186   class SwitchStmt;
187   class TemplateArgument;
188   class TemplateArgumentList;
189   class TemplateArgumentLoc;
190   class TemplateDecl;
191   class TemplateInstantiationCallback;
192   class TemplateParameterList;
193   class TemplatePartialOrderingContext;
194   class TemplateTemplateParmDecl;
195   class Token;
196   class TypeAliasDecl;
197   class TypedefDecl;
198   class TypedefNameDecl;
199   class TypeLoc;
200   class TypoCorrectionConsumer;
201   class UnqualifiedId;
202   class UnresolvedLookupExpr;
203   class UnresolvedMemberExpr;
204   class UnresolvedSetImpl;
205   class UnresolvedSetIterator;
206   class UsingDecl;
207   class UsingShadowDecl;
208   class ValueDecl;
209   class VarDecl;
210   class VarTemplateSpecializationDecl;
211   class VisibilityAttr;
212   class VisibleDeclConsumer;
213   class IndirectFieldDecl;
214   struct DeductionFailureInfo;
215   class TemplateSpecCandidateSet;
216 
217 namespace sema {
218   class AccessedEntity;
219   class BlockScopeInfo;
220   class Capture;
221   class CapturedRegionScopeInfo;
222   class CapturingScopeInfo;
223   class CompoundScopeInfo;
224   class DelayedDiagnostic;
225   class DelayedDiagnosticPool;
226   class FunctionScopeInfo;
227   class LambdaScopeInfo;
228   class PossiblyUnreachableDiag;
229   class SemaPPCallbacks;
230   class TemplateDeductionInfo;
231 }
232 
233 namespace threadSafety {
234   class BeforeSet;
235   void threadSafetyCleanup(BeforeSet* Cache);
236 }
237 
238 // FIXME: No way to easily map from TemplateTypeParmTypes to
239 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
240 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
241                   SourceLocation> UnexpandedParameterPack;
242 
243 /// Describes whether we've seen any nullability information for the given
244 /// file.
245 struct FileNullability {
246   /// The first pointer declarator (of any pointer kind) in the file that does
247   /// not have a corresponding nullability annotation.
248   SourceLocation PointerLoc;
249 
250   /// The end location for the first pointer declarator in the file. Used for
251   /// placing fix-its.
252   SourceLocation PointerEndLoc;
253 
254   /// Which kind of pointer declarator we saw.
255   uint8_t PointerKind;
256 
257   /// Whether we saw any type nullability annotations in the given file.
258   bool SawTypeNullability = false;
259 };
260 
261 /// A mapping from file IDs to a record of whether we've seen nullability
262 /// information in that file.
263 class FileNullabilityMap {
264   /// A mapping from file IDs to the nullability information for each file ID.
265   llvm::DenseMap<FileID, FileNullability> Map;
266 
267   /// A single-element cache based on the file ID.
268   struct {
269     FileID File;
270     FileNullability Nullability;
271   } Cache;
272 
273 public:
274   FileNullability &operator[](FileID file) {
275     // Check the single-element cache.
276     if (file == Cache.File)
277       return Cache.Nullability;
278 
279     // It's not in the single-element cache; flush the cache if we have one.
280     if (!Cache.File.isInvalid()) {
281       Map[Cache.File] = Cache.Nullability;
282     }
283 
284     // Pull this entry into the cache.
285     Cache.File = file;
286     Cache.Nullability = Map[file];
287     return Cache.Nullability;
288   }
289 };
290 
291 /// Tracks expected type during expression parsing, for use in code completion.
292 /// The type is tied to a particular token, all functions that update or consume
293 /// the type take a start location of the token they are looking at as a
294 /// parameter. This avoids updating the type on hot paths in the parser.
295 class PreferredTypeBuilder {
296 public:
297   PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
298 
299   void enterCondition(Sema &S, SourceLocation Tok);
300   void enterReturn(Sema &S, SourceLocation Tok);
301   void enterVariableInit(SourceLocation Tok, Decl *D);
302   /// Handles e.g. BaseType{ .D = Tok...
303   void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
304                                   const Designation &D);
305   /// Computing a type for the function argument may require running
306   /// overloading, so we postpone its computation until it is actually needed.
307   ///
308   /// Clients should be very careful when using this funciton, as it stores a
309   /// function_ref, clients should make sure all calls to get() with the same
310   /// location happen while function_ref is alive.
311   ///
312   /// The callback should also emit signature help as a side-effect, but only
313   /// if the completion point has been reached.
314   void enterFunctionArgument(SourceLocation Tok,
315                              llvm::function_ref<QualType()> ComputeType);
316 
317   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
318   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
319                   SourceLocation OpLoc);
320   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
321   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
322   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
323   /// Handles all type casts, including C-style cast, C++ casts, etc.
324   void enterTypeCast(SourceLocation Tok, QualType CastType);
325 
326   /// Get the expected type associated with this location, if any.
327   ///
328   /// If the location is a function argument, determining the expected type
329   /// involves considering all function overloads and the arguments so far.
330   /// In this case, signature help for these function overloads will be reported
331   /// as a side-effect (only if the completion point has been reached).
332   QualType get(SourceLocation Tok) const {
333     if (!Enabled || Tok != ExpectedLoc)
334       return QualType();
335     if (!Type.isNull())
336       return Type;
337     if (ComputeType)
338       return ComputeType();
339     return QualType();
340   }
341 
342 private:
343   bool Enabled;
344   /// Start position of a token for which we store expected type.
345   SourceLocation ExpectedLoc;
346   /// Expected type for a token starting at ExpectedLoc.
347   QualType Type;
348   /// A function to compute expected type at ExpectedLoc. It is only considered
349   /// if Type is null.
350   llvm::function_ref<QualType()> ComputeType;
351 };
352 
353 /// Sema - This implements semantic analysis and AST building for C.
354 class Sema final {
355   Sema(const Sema &) = delete;
356   void operator=(const Sema &) = delete;
357 
358   ///Source of additional semantic information.
359   ExternalSemaSource *ExternalSource;
360 
361   ///Whether Sema has generated a multiplexer and has to delete it.
362   bool isMultiplexExternalSource;
363 
364   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
365 
366   /// Determine whether two declarations should be linked together, given that
367   /// the old declaration might not be visible and the new declaration might
368   /// not have external linkage.
369   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
370                                     const NamedDecl *New) {
371     if (isVisible(Old))
372      return true;
373     // See comment in below overload for why it's safe to compute the linkage
374     // of the new declaration here.
375     if (New->isExternallyDeclarable()) {
376       assert(Old->isExternallyDeclarable() &&
377              "should not have found a non-externally-declarable previous decl");
378       return true;
379     }
380     return false;
381   }
382   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
383 
384   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
385                                       QualType ResultTy,
386                                       ArrayRef<QualType> Args);
387 
388 public:
389   /// The maximum alignment, same as in llvm::Value. We duplicate them here
390   /// because that allows us not to duplicate the constants in clang code,
391   /// which we must to since we can't directly use the llvm constants.
392   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
393   ///
394   /// This is the greatest alignment value supported by load, store, and alloca
395   /// instructions, and global values.
396   static const unsigned MaxAlignmentExponent = 32;
397   static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
398 
399   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
400   typedef OpaquePtr<TemplateName> TemplateTy;
401   typedef OpaquePtr<QualType> TypeTy;
402 
403   OpenCLOptions OpenCLFeatures;
404   FPOptions CurFPFeatures;
405 
406   const LangOptions &LangOpts;
407   Preprocessor &PP;
408   ASTContext &Context;
409   ASTConsumer &Consumer;
410   DiagnosticsEngine &Diags;
411   SourceManager &SourceMgr;
412 
413   /// Flag indicating whether or not to collect detailed statistics.
414   bool CollectStats;
415 
416   /// Code-completion consumer.
417   CodeCompleteConsumer *CodeCompleter;
418 
419   /// CurContext - This is the current declaration context of parsing.
420   DeclContext *CurContext;
421 
422   /// Generally null except when we temporarily switch decl contexts,
423   /// like in \see ActOnObjCTemporaryExitContainerContext.
424   DeclContext *OriginalLexicalContext;
425 
426   /// VAListTagName - The declaration name corresponding to __va_list_tag.
427   /// This is used as part of a hack to omit that class from ADL results.
428   DeclarationName VAListTagName;
429 
430   bool MSStructPragmaOn; // True when \#pragma ms_struct on
431 
432   /// Controls member pointer representation format under the MS ABI.
433   LangOptions::PragmaMSPointersToMembersKind
434       MSPointerToMemberRepresentationMethod;
435 
436   /// Stack of active SEH __finally scopes.  Can be empty.
437   SmallVector<Scope*, 2> CurrentSEHFinally;
438 
439   /// Source location for newly created implicit MSInheritanceAttrs
440   SourceLocation ImplicitMSInheritanceAttrLoc;
441 
442   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
443   /// `TransformTypos` in order to keep track of any TypoExprs that are created
444   /// recursively during typo correction and wipe them away if the correction
445   /// fails.
446   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
447 
448   /// pragma clang section kind
449   enum PragmaClangSectionKind {
450     PCSK_Invalid      = 0,
451     PCSK_BSS          = 1,
452     PCSK_Data         = 2,
453     PCSK_Rodata       = 3,
454     PCSK_Text         = 4,
455     PCSK_Relro        = 5
456    };
457 
458   enum PragmaClangSectionAction {
459     PCSA_Set     = 0,
460     PCSA_Clear   = 1
461   };
462 
463   struct PragmaClangSection {
464     std::string SectionName;
465     bool Valid = false;
466     SourceLocation PragmaLocation;
467   };
468 
469    PragmaClangSection PragmaClangBSSSection;
470    PragmaClangSection PragmaClangDataSection;
471    PragmaClangSection PragmaClangRodataSection;
472    PragmaClangSection PragmaClangRelroSection;
473    PragmaClangSection PragmaClangTextSection;
474 
475   enum PragmaMsStackAction {
476     PSK_Reset     = 0x0,                // #pragma ()
477     PSK_Set       = 0x1,                // #pragma (value)
478     PSK_Push      = 0x2,                // #pragma (push[, id])
479     PSK_Pop       = 0x4,                // #pragma (pop[, id])
480     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
481     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
482     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
483   };
484 
485   // #pragma pack and align.
486   class AlignPackInfo {
487   public:
488     // `Native` represents default align mode, which may vary based on the
489     // platform.
490     enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
491 
492     // #pragma pack info constructor
493     AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
494         : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
495       assert(Num == PackNumber && "The pack number has been truncated.");
496     }
497 
498     // #pragma align info constructor
499     AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
500         : PackAttr(false), AlignMode(M),
501           PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
502 
503     explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
504 
505     AlignPackInfo() : AlignPackInfo(Native, false) {}
506 
507     // When a AlignPackInfo itself cannot be used, this returns an 32-bit
508     // integer encoding for it. This should only be passed to
509     // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
510     static uint32_t getRawEncoding(const AlignPackInfo &Info) {
511       std::uint32_t Encoding{};
512       if (Info.IsXLStack())
513         Encoding |= IsXLMask;
514 
515       Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
516 
517       if (Info.IsPackAttr())
518         Encoding |= PackAttrMask;
519 
520       Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
521 
522       return Encoding;
523     }
524 
525     static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
526       bool IsXL = static_cast<bool>(Encoding & IsXLMask);
527       AlignPackInfo::Mode M =
528           static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
529       int PackNumber = (Encoding & PackNumMask) >> 4;
530 
531       if (Encoding & PackAttrMask)
532         return AlignPackInfo(M, PackNumber, IsXL);
533 
534       return AlignPackInfo(M, IsXL);
535     }
536 
537     bool IsPackAttr() const { return PackAttr; }
538 
539     bool IsAlignAttr() const { return !PackAttr; }
540 
541     Mode getAlignMode() const { return AlignMode; }
542 
543     unsigned getPackNumber() const { return PackNumber; }
544 
545     bool IsPackSet() const {
546       // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
547       // attriute on a decl.
548       return PackNumber != UninitPackVal && PackNumber != 0;
549     }
550 
551     bool IsXLStack() const { return XLStack; }
552 
553     bool operator==(const AlignPackInfo &Info) const {
554       return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
555              std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
556                       Info.XLStack);
557     }
558 
559     bool operator!=(const AlignPackInfo &Info) const {
560       return !(*this == Info);
561     }
562 
563   private:
564     /// \brief True if this is a pragma pack attribute,
565     ///         not a pragma align attribute.
566     bool PackAttr;
567 
568     /// \brief The alignment mode that is in effect.
569     Mode AlignMode;
570 
571     /// \brief The pack number of the stack.
572     unsigned char PackNumber;
573 
574     /// \brief True if it is a XL #pragma align/pack stack.
575     bool XLStack;
576 
577     /// \brief Uninitialized pack value.
578     static constexpr unsigned char UninitPackVal = -1;
579 
580     // Masks to encode and decode an AlignPackInfo.
581     static constexpr uint32_t IsXLMask{0x0000'0001};
582     static constexpr uint32_t AlignModeMask{0x0000'0006};
583     static constexpr uint32_t PackAttrMask{0x00000'0008};
584     static constexpr uint32_t PackNumMask{0x0000'01F0};
585   };
586 
587   template<typename ValueType>
588   struct PragmaStack {
589     struct Slot {
590       llvm::StringRef StackSlotLabel;
591       ValueType Value;
592       SourceLocation PragmaLocation;
593       SourceLocation PragmaPushLocation;
594       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
595            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
596           : StackSlotLabel(StackSlotLabel), Value(Value),
597             PragmaLocation(PragmaLocation),
598             PragmaPushLocation(PragmaPushLocation) {}
599     };
600 
601     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
602              llvm::StringRef StackSlotLabel, ValueType Value) {
603       if (Action == PSK_Reset) {
604         CurrentValue = DefaultValue;
605         CurrentPragmaLocation = PragmaLocation;
606         return;
607       }
608       if (Action & PSK_Push)
609         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
610                            PragmaLocation);
611       else if (Action & PSK_Pop) {
612         if (!StackSlotLabel.empty()) {
613           // If we've got a label, try to find it and jump there.
614           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
615             return x.StackSlotLabel == StackSlotLabel;
616           });
617           // If we found the label so pop from there.
618           if (I != Stack.rend()) {
619             CurrentValue = I->Value;
620             CurrentPragmaLocation = I->PragmaLocation;
621             Stack.erase(std::prev(I.base()), Stack.end());
622           }
623         } else if (!Stack.empty()) {
624           // We do not have a label, just pop the last entry.
625           CurrentValue = Stack.back().Value;
626           CurrentPragmaLocation = Stack.back().PragmaLocation;
627           Stack.pop_back();
628         }
629       }
630       if (Action & PSK_Set) {
631         CurrentValue = Value;
632         CurrentPragmaLocation = PragmaLocation;
633       }
634     }
635 
636     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
637     // method body to restore the stacks on exit, so it works like this:
638     //
639     //   struct S {
640     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
641     //     void Method {}
642     //     #pragma <name>(pop, InternalPragmaSlot)
643     //   };
644     //
645     // It works even with #pragma vtordisp, although MSVC doesn't support
646     //   #pragma vtordisp(push [, id], n)
647     // syntax.
648     //
649     // Push / pop a named sentinel slot.
650     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
651       assert((Action == PSK_Push || Action == PSK_Pop) &&
652              "Can only push / pop #pragma stack sentinels!");
653       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
654     }
655 
656     // Constructors.
657     explicit PragmaStack(const ValueType &Default)
658         : DefaultValue(Default), CurrentValue(Default) {}
659 
660     bool hasValue() const { return CurrentValue != DefaultValue; }
661 
662     SmallVector<Slot, 2> Stack;
663     ValueType DefaultValue; // Value used for PSK_Reset action.
664     ValueType CurrentValue;
665     SourceLocation CurrentPragmaLocation;
666   };
667   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
668   // we shouldn't do so if they're in a module).
669 
670   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
671   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
672   ///
673   /// 0: Suppress all vtordisps
674   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
675   ///    structors
676   /// 2: Always insert vtordisps to support RTTI on partially constructed
677   ///    objects
678   PragmaStack<MSVtorDispMode> VtorDispStack;
679   PragmaStack<AlignPackInfo> AlignPackStack;
680   // The current #pragma align/pack values and locations at each #include.
681   struct AlignPackIncludeState {
682     AlignPackInfo CurrentValue;
683     SourceLocation CurrentPragmaLocation;
684     bool HasNonDefaultValue, ShouldWarnOnInclude;
685   };
686   SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
687   // Segment #pragmas.
688   PragmaStack<StringLiteral *> DataSegStack;
689   PragmaStack<StringLiteral *> BSSSegStack;
690   PragmaStack<StringLiteral *> ConstSegStack;
691   PragmaStack<StringLiteral *> CodeSegStack;
692 
693   // This stack tracks the current state of Sema.CurFPFeatures.
694   PragmaStack<FPOptionsOverride> FpPragmaStack;
695   FPOptionsOverride CurFPFeatureOverrides() {
696     FPOptionsOverride result;
697     if (!FpPragmaStack.hasValue()) {
698       result = FPOptionsOverride();
699     } else {
700       result = FpPragmaStack.CurrentValue;
701     }
702     return result;
703   }
704 
705   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
706   // Actions should be performed only if we enter / exit a C++ method body.
707   class PragmaStackSentinelRAII {
708   public:
709     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
710     ~PragmaStackSentinelRAII();
711 
712   private:
713     Sema &S;
714     StringRef SlotLabel;
715     bool ShouldAct;
716   };
717 
718   /// A mapping that describes the nullability we've seen in each header file.
719   FileNullabilityMap NullabilityMap;
720 
721   /// Last section used with #pragma init_seg.
722   StringLiteral *CurInitSeg;
723   SourceLocation CurInitSegLoc;
724 
725   /// Sections used with #pragma alloc_text.
726   llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
727 
728   /// VisContext - Manages the stack for \#pragma GCC visibility.
729   void *VisContext; // Really a "PragmaVisStack*"
730 
731   /// This an attribute introduced by \#pragma clang attribute.
732   struct PragmaAttributeEntry {
733     SourceLocation Loc;
734     ParsedAttr *Attribute;
735     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
736     bool IsUsed;
737   };
738 
739   /// A push'd group of PragmaAttributeEntries.
740   struct PragmaAttributeGroup {
741     /// The location of the push attribute.
742     SourceLocation Loc;
743     /// The namespace of this push group.
744     const IdentifierInfo *Namespace;
745     SmallVector<PragmaAttributeEntry, 2> Entries;
746   };
747 
748   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
749 
750   /// The declaration that is currently receiving an attribute from the
751   /// #pragma attribute stack.
752   const Decl *PragmaAttributeCurrentTargetDecl;
753 
754   /// This represents the last location of a "#pragma clang optimize off"
755   /// directive if such a directive has not been closed by an "on" yet. If
756   /// optimizations are currently "on", this is set to an invalid location.
757   SourceLocation OptimizeOffPragmaLocation;
758 
759   /// The "on" or "off" argument passed by \#pragma optimize, that denotes
760   /// whether the optimizations in the list passed to the pragma should be
761   /// turned off or on. This boolean is true by default because command line
762   /// options are honored when `#pragma optimize("", on)`.
763   /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
764   bool MSPragmaOptimizeIsOn = true;
765 
766   /// Set of no-builtin functions listed by \#pragma function.
767   llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
768 
769   /// Flag indicating if Sema is building a recovery call expression.
770   ///
771   /// This flag is used to avoid building recovery call expressions
772   /// if Sema is already doing so, which would cause infinite recursions.
773   bool IsBuildingRecoveryCallExpr;
774 
775   /// Used to control the generation of ExprWithCleanups.
776   CleanupInfo Cleanup;
777 
778   /// ExprCleanupObjects - This is the stack of objects requiring
779   /// cleanup that are created by the current full expression.
780   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
781 
782   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
783   /// to a variable (constant) that may or may not be odr-used in this Expr, and
784   /// we won't know until all lvalue-to-rvalue and discarded value conversions
785   /// have been applied to all subexpressions of the enclosing full expression.
786   /// This is cleared at the end of each full expression.
787   using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
788                                              llvm::SmallPtrSet<Expr *, 4>>;
789   MaybeODRUseExprSet MaybeODRUseExprs;
790 
791   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
792 
793   /// Stack containing information about each of the nested
794   /// function, block, and method scopes that are currently active.
795   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
796 
797   /// The index of the first FunctionScope that corresponds to the current
798   /// context.
799   unsigned FunctionScopesStart = 0;
800 
801   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
802     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
803                               FunctionScopes.end());
804   }
805 
806   /// Stack containing information needed when in C++2a an 'auto' is encountered
807   /// in a function declaration parameter type specifier in order to invent a
808   /// corresponding template parameter in the enclosing abbreviated function
809   /// template. This information is also present in LambdaScopeInfo, stored in
810   /// the FunctionScopes stack.
811   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
812 
813   /// The index of the first InventedParameterInfo that refers to the current
814   /// context.
815   unsigned InventedParameterInfosStart = 0;
816 
817   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
818     return llvm::makeArrayRef(InventedParameterInfos.begin() +
819                                   InventedParameterInfosStart,
820                               InventedParameterInfos.end());
821   }
822 
823   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
824                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
825     ExtVectorDeclsType;
826 
827   /// ExtVectorDecls - This is a list all the extended vector types. This allows
828   /// us to associate a raw vector type with one of the ext_vector type names.
829   /// This is only necessary for issuing pretty diagnostics.
830   ExtVectorDeclsType ExtVectorDecls;
831 
832   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
833   std::unique_ptr<CXXFieldCollector> FieldCollector;
834 
835   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
836 
837   /// Set containing all declared private fields that are not used.
838   NamedDeclSetType UnusedPrivateFields;
839 
840   /// Set containing all typedefs that are likely unused.
841   llvm::SmallSetVector<const TypedefNameDecl *, 4>
842       UnusedLocalTypedefNameCandidates;
843 
844   /// Delete-expressions to be analyzed at the end of translation unit
845   ///
846   /// This list contains class members, and locations of delete-expressions
847   /// that could not be proven as to whether they mismatch with new-expression
848   /// used in initializer of the field.
849   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
850   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
851   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
852 
853   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
854 
855   /// PureVirtualClassDiagSet - a set of class declarations which we have
856   /// emitted a list of pure virtual functions. Used to prevent emitting the
857   /// same list more than once.
858   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
859 
860   /// ParsingInitForAutoVars - a set of declarations with auto types for which
861   /// we are currently parsing the initializer.
862   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
863 
864   /// Look for a locally scoped extern "C" declaration by the given name.
865   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
866 
867   typedef LazyVector<VarDecl *, ExternalSemaSource,
868                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
869     TentativeDefinitionsType;
870 
871   /// All the tentative definitions encountered in the TU.
872   TentativeDefinitionsType TentativeDefinitions;
873 
874   /// All the external declarations encoutered and used in the TU.
875   SmallVector<VarDecl *, 4> ExternalDeclarations;
876 
877   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
878                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
879     UnusedFileScopedDeclsType;
880 
881   /// The set of file scoped decls seen so far that have not been used
882   /// and must warn if not used. Only contains the first declaration.
883   UnusedFileScopedDeclsType UnusedFileScopedDecls;
884 
885   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
886                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
887     DelegatingCtorDeclsType;
888 
889   /// All the delegating constructors seen so far in the file, used for
890   /// cycle detection at the end of the TU.
891   DelegatingCtorDeclsType DelegatingCtorDecls;
892 
893   /// All the overriding functions seen during a class definition
894   /// that had their exception spec checks delayed, plus the overridden
895   /// function.
896   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
897     DelayedOverridingExceptionSpecChecks;
898 
899   /// All the function redeclarations seen during a class definition that had
900   /// their exception spec checks delayed, plus the prior declaration they
901   /// should be checked against. Except during error recovery, the new decl
902   /// should always be a friend declaration, as that's the only valid way to
903   /// redeclare a special member before its class is complete.
904   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
905     DelayedEquivalentExceptionSpecChecks;
906 
907   typedef llvm::MapVector<const FunctionDecl *,
908                           std::unique_ptr<LateParsedTemplate>>
909       LateParsedTemplateMapT;
910   LateParsedTemplateMapT LateParsedTemplateMap;
911 
912   /// Callback to the parser to parse templated functions when needed.
913   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
914   typedef void LateTemplateParserCleanupCB(void *P);
915   LateTemplateParserCB *LateTemplateParser;
916   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
917   void *OpaqueParser;
918 
919   void SetLateTemplateParser(LateTemplateParserCB *LTP,
920                              LateTemplateParserCleanupCB *LTPCleanup,
921                              void *P) {
922     LateTemplateParser = LTP;
923     LateTemplateParserCleanup = LTPCleanup;
924     OpaqueParser = P;
925   }
926 
927   class DelayedDiagnostics;
928 
929   class DelayedDiagnosticsState {
930     sema::DelayedDiagnosticPool *SavedPool;
931     friend class Sema::DelayedDiagnostics;
932   };
933   typedef DelayedDiagnosticsState ParsingDeclState;
934   typedef DelayedDiagnosticsState ProcessingContextState;
935 
936   /// A class which encapsulates the logic for delaying diagnostics
937   /// during parsing and other processing.
938   class DelayedDiagnostics {
939     /// The current pool of diagnostics into which delayed
940     /// diagnostics should go.
941     sema::DelayedDiagnosticPool *CurPool;
942 
943   public:
944     DelayedDiagnostics() : CurPool(nullptr) {}
945 
946     /// Adds a delayed diagnostic.
947     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
948 
949     /// Determines whether diagnostics should be delayed.
950     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
951 
952     /// Returns the current delayed-diagnostics pool.
953     sema::DelayedDiagnosticPool *getCurrentPool() const {
954       return CurPool;
955     }
956 
957     /// Enter a new scope.  Access and deprecation diagnostics will be
958     /// collected in this pool.
959     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
960       DelayedDiagnosticsState state;
961       state.SavedPool = CurPool;
962       CurPool = &pool;
963       return state;
964     }
965 
966     /// Leave a delayed-diagnostic state that was previously pushed.
967     /// Do not emit any of the diagnostics.  This is performed as part
968     /// of the bookkeeping of popping a pool "properly".
969     void popWithoutEmitting(DelayedDiagnosticsState state) {
970       CurPool = state.SavedPool;
971     }
972 
973     /// Enter a new scope where access and deprecation diagnostics are
974     /// not delayed.
975     DelayedDiagnosticsState pushUndelayed() {
976       DelayedDiagnosticsState state;
977       state.SavedPool = CurPool;
978       CurPool = nullptr;
979       return state;
980     }
981 
982     /// Undo a previous pushUndelayed().
983     void popUndelayed(DelayedDiagnosticsState state) {
984       assert(CurPool == nullptr);
985       CurPool = state.SavedPool;
986     }
987   } DelayedDiagnostics;
988 
989   /// A RAII object to temporarily push a declaration context.
990   class ContextRAII {
991   private:
992     Sema &S;
993     DeclContext *SavedContext;
994     ProcessingContextState SavedContextState;
995     QualType SavedCXXThisTypeOverride;
996     unsigned SavedFunctionScopesStart;
997     unsigned SavedInventedParameterInfosStart;
998 
999   public:
1000     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1001       : S(S), SavedContext(S.CurContext),
1002         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1003         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1004         SavedFunctionScopesStart(S.FunctionScopesStart),
1005         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1006     {
1007       assert(ContextToPush && "pushing null context");
1008       S.CurContext = ContextToPush;
1009       if (NewThisContext)
1010         S.CXXThisTypeOverride = QualType();
1011       // Any saved FunctionScopes do not refer to this context.
1012       S.FunctionScopesStart = S.FunctionScopes.size();
1013       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1014     }
1015 
1016     void pop() {
1017       if (!SavedContext) return;
1018       S.CurContext = SavedContext;
1019       S.DelayedDiagnostics.popUndelayed(SavedContextState);
1020       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1021       S.FunctionScopesStart = SavedFunctionScopesStart;
1022       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1023       SavedContext = nullptr;
1024     }
1025 
1026     ~ContextRAII() {
1027       pop();
1028     }
1029   };
1030 
1031   /// Whether the AST is currently being rebuilt to correct immediate
1032   /// invocations. Immediate invocation candidates and references to consteval
1033   /// functions aren't tracked when this is set.
1034   bool RebuildingImmediateInvocation = false;
1035 
1036   /// Used to change context to isConstantEvaluated without pushing a heavy
1037   /// ExpressionEvaluationContextRecord object.
1038   bool isConstantEvaluatedOverride;
1039 
1040   bool isConstantEvaluated() {
1041     return ExprEvalContexts.back().isConstantEvaluated() ||
1042            isConstantEvaluatedOverride;
1043   }
1044 
1045   /// RAII object to handle the state changes required to synthesize
1046   /// a function body.
1047   class SynthesizedFunctionScope {
1048     Sema &S;
1049     Sema::ContextRAII SavedContext;
1050     bool PushedCodeSynthesisContext = false;
1051 
1052   public:
1053     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1054         : S(S), SavedContext(S, DC) {
1055       S.PushFunctionScope();
1056       S.PushExpressionEvaluationContext(
1057           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1058       if (auto *FD = dyn_cast<FunctionDecl>(DC))
1059         FD->setWillHaveBody(true);
1060       else
1061         assert(isa<ObjCMethodDecl>(DC));
1062     }
1063 
1064     void addContextNote(SourceLocation UseLoc) {
1065       assert(!PushedCodeSynthesisContext);
1066 
1067       Sema::CodeSynthesisContext Ctx;
1068       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1069       Ctx.PointOfInstantiation = UseLoc;
1070       Ctx.Entity = cast<Decl>(S.CurContext);
1071       S.pushCodeSynthesisContext(Ctx);
1072 
1073       PushedCodeSynthesisContext = true;
1074     }
1075 
1076     ~SynthesizedFunctionScope() {
1077       if (PushedCodeSynthesisContext)
1078         S.popCodeSynthesisContext();
1079       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1080         FD->setWillHaveBody(false);
1081       S.PopExpressionEvaluationContext();
1082       S.PopFunctionScopeInfo();
1083     }
1084   };
1085 
1086   /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1087   /// declared. Rare. May alias another identifier, declared or undeclared.
1088   ///
1089   /// For aliases, the target identifier is used as a key for eventual
1090   /// processing when the target is declared. For the single-identifier form,
1091   /// the sole identifier is used as the key. Each entry is a `SetVector`
1092   /// (ordered by parse order) of aliases (identified by the alias name) in case
1093   /// of multiple aliases to the same undeclared identifier.
1094   llvm::MapVector<
1095       IdentifierInfo *,
1096       llvm::SetVector<
1097           WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1098           llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1099       WeakUndeclaredIdentifiers;
1100 
1101   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1102   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
1103   /// to define functions that occur in multiple standards to call the version
1104   /// in the currently selected standard.
1105   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1106 
1107 
1108   /// Load weak undeclared identifiers from the external source.
1109   void LoadExternalWeakUndeclaredIdentifiers();
1110 
1111   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1112   /// \#pragma weak during processing of other Decls.
1113   /// I couldn't figure out a clean way to generate these in-line, so
1114   /// we store them here and handle separately -- which is a hack.
1115   /// It would be best to refactor this.
1116   SmallVector<Decl*,2> WeakTopLevelDecl;
1117 
1118   IdentifierResolver IdResolver;
1119 
1120   /// Translation Unit Scope - useful to Objective-C actions that need
1121   /// to lookup file scope declarations in the "ordinary" C decl namespace.
1122   /// For example, user-defined classes, built-in "id" type, etc.
1123   Scope *TUScope;
1124 
1125   /// The C++ "std" namespace, where the standard library resides.
1126   LazyDeclPtr StdNamespace;
1127 
1128   /// The C++ "std::bad_alloc" class, which is defined by the C++
1129   /// standard library.
1130   LazyDeclPtr StdBadAlloc;
1131 
1132   /// The C++ "std::align_val_t" enum class, which is defined by the C++
1133   /// standard library.
1134   LazyDeclPtr StdAlignValT;
1135 
1136   /// The C++ "std::experimental" namespace, where the experimental parts
1137   /// of the standard library resides.
1138   NamespaceDecl *StdExperimentalNamespaceCache;
1139 
1140   /// The C++ "std::initializer_list" template, which is defined in
1141   /// \<initializer_list>.
1142   ClassTemplateDecl *StdInitializerList;
1143 
1144   /// The C++ "std::coroutine_traits" template, which is defined in
1145   /// \<coroutine_traits>
1146   ClassTemplateDecl *StdCoroutineTraitsCache;
1147   /// The namespace where coroutine components are defined. In standard,
1148   /// they are defined in std namespace. And in the previous implementation,
1149   /// they are defined in std::experimental namespace.
1150   NamespaceDecl *CoroTraitsNamespaceCache;
1151 
1152   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1153   RecordDecl *CXXTypeInfoDecl;
1154 
1155   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1156   RecordDecl *MSVCGuidDecl;
1157 
1158   /// The C++ "std::source_location::__impl" struct, defined in
1159   /// \<source_location>.
1160   RecordDecl *StdSourceLocationImplDecl;
1161 
1162   /// Caches identifiers/selectors for NSFoundation APIs.
1163   std::unique_ptr<NSAPI> NSAPIObj;
1164 
1165   /// The declaration of the Objective-C NSNumber class.
1166   ObjCInterfaceDecl *NSNumberDecl;
1167 
1168   /// The declaration of the Objective-C NSValue class.
1169   ObjCInterfaceDecl *NSValueDecl;
1170 
1171   /// Pointer to NSNumber type (NSNumber *).
1172   QualType NSNumberPointer;
1173 
1174   /// Pointer to NSValue type (NSValue *).
1175   QualType NSValuePointer;
1176 
1177   /// The Objective-C NSNumber methods used to create NSNumber literals.
1178   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1179 
1180   /// The declaration of the Objective-C NSString class.
1181   ObjCInterfaceDecl *NSStringDecl;
1182 
1183   /// Pointer to NSString type (NSString *).
1184   QualType NSStringPointer;
1185 
1186   /// The declaration of the stringWithUTF8String: method.
1187   ObjCMethodDecl *StringWithUTF8StringMethod;
1188 
1189   /// The declaration of the valueWithBytes:objCType: method.
1190   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1191 
1192   /// The declaration of the Objective-C NSArray class.
1193   ObjCInterfaceDecl *NSArrayDecl;
1194 
1195   /// The declaration of the arrayWithObjects:count: method.
1196   ObjCMethodDecl *ArrayWithObjectsMethod;
1197 
1198   /// The declaration of the Objective-C NSDictionary class.
1199   ObjCInterfaceDecl *NSDictionaryDecl;
1200 
1201   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1202   ObjCMethodDecl *DictionaryWithObjectsMethod;
1203 
1204   /// id<NSCopying> type.
1205   QualType QIDNSCopying;
1206 
1207   /// will hold 'respondsToSelector:'
1208   Selector RespondsToSelectorSel;
1209 
1210   /// A flag to remember whether the implicit forms of operator new and delete
1211   /// have been declared.
1212   bool GlobalNewDeleteDeclared;
1213 
1214   /// Describes how the expressions currently being parsed are
1215   /// evaluated at run-time, if at all.
1216   enum class ExpressionEvaluationContext {
1217     /// The current expression and its subexpressions occur within an
1218     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1219     /// \c sizeof, where the type of the expression may be significant but
1220     /// no code will be generated to evaluate the value of the expression at
1221     /// run time.
1222     Unevaluated,
1223 
1224     /// The current expression occurs within a braced-init-list within
1225     /// an unevaluated operand. This is mostly like a regular unevaluated
1226     /// context, except that we still instantiate constexpr functions that are
1227     /// referenced here so that we can perform narrowing checks correctly.
1228     UnevaluatedList,
1229 
1230     /// The current expression occurs within a discarded statement.
1231     /// This behaves largely similarly to an unevaluated operand in preventing
1232     /// definitions from being required, but not in other ways.
1233     DiscardedStatement,
1234 
1235     /// The current expression occurs within an unevaluated
1236     /// operand that unconditionally permits abstract references to
1237     /// fields, such as a SIZE operator in MS-style inline assembly.
1238     UnevaluatedAbstract,
1239 
1240     /// The current context is "potentially evaluated" in C++11 terms,
1241     /// but the expression is evaluated at compile-time (like the values of
1242     /// cases in a switch statement).
1243     ConstantEvaluated,
1244 
1245     /// In addition of being constant evaluated, the current expression
1246     /// occurs in an immediate function context - either a consteval function
1247     /// or a consteval if function.
1248     ImmediateFunctionContext,
1249 
1250     /// The current expression is potentially evaluated at run time,
1251     /// which means that code may be generated to evaluate the value of the
1252     /// expression at run time.
1253     PotentiallyEvaluated,
1254 
1255     /// The current expression is potentially evaluated, but any
1256     /// declarations referenced inside that expression are only used if
1257     /// in fact the current expression is used.
1258     ///
1259     /// This value is used when parsing default function arguments, for which
1260     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1261     /// through varargs) but do not want to mark declarations as "referenced"
1262     /// until the default argument is used.
1263     PotentiallyEvaluatedIfUsed
1264   };
1265 
1266   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1267 
1268   /// Data structure used to record current or nested
1269   /// expression evaluation contexts.
1270   struct ExpressionEvaluationContextRecord {
1271     /// The expression evaluation context.
1272     ExpressionEvaluationContext Context;
1273 
1274     /// Whether the enclosing context needed a cleanup.
1275     CleanupInfo ParentCleanup;
1276 
1277     /// The number of active cleanup objects when we entered
1278     /// this expression evaluation context.
1279     unsigned NumCleanupObjects;
1280 
1281     /// The number of typos encountered during this expression evaluation
1282     /// context (i.e. the number of TypoExprs created).
1283     unsigned NumTypos;
1284 
1285     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1286 
1287     /// The lambdas that are present within this context, if it
1288     /// is indeed an unevaluated context.
1289     SmallVector<LambdaExpr *, 2> Lambdas;
1290 
1291     /// The declaration that provides context for lambda expressions
1292     /// and block literals if the normal declaration context does not
1293     /// suffice, e.g., in a default function argument.
1294     Decl *ManglingContextDecl;
1295 
1296     /// If we are processing a decltype type, a set of call expressions
1297     /// for which we have deferred checking the completeness of the return type.
1298     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1299 
1300     /// If we are processing a decltype type, a set of temporary binding
1301     /// expressions for which we have deferred checking the destructor.
1302     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1303 
1304     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1305 
1306     /// Expressions appearing as the LHS of a volatile assignment in this
1307     /// context. We produce a warning for these when popping the context if
1308     /// they are not discarded-value expressions nor unevaluated operands.
1309     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1310 
1311     /// Set of candidates for starting an immediate invocation.
1312     llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1313 
1314     /// Set of DeclRefExprs referencing a consteval function when used in a
1315     /// context not already known to be immediately invoked.
1316     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1317 
1318     /// \brief Describes whether we are in an expression constext which we have
1319     /// to handle differently.
1320     enum ExpressionKind {
1321       EK_Decltype, EK_TemplateArgument, EK_Other
1322     } ExprContext;
1323 
1324     // A context can be nested in both a discarded statement context and
1325     // an immediate function context, so they need to be tracked independently.
1326     bool InDiscardedStatement;
1327     bool InImmediateFunctionContext;
1328 
1329     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1330                                       unsigned NumCleanupObjects,
1331                                       CleanupInfo ParentCleanup,
1332                                       Decl *ManglingContextDecl,
1333                                       ExpressionKind ExprContext)
1334         : Context(Context), ParentCleanup(ParentCleanup),
1335           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1336           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1337           InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1338 
1339     bool isUnevaluated() const {
1340       return Context == ExpressionEvaluationContext::Unevaluated ||
1341              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1342              Context == ExpressionEvaluationContext::UnevaluatedList;
1343     }
1344 
1345     bool isConstantEvaluated() const {
1346       return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1347              Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1348     }
1349 
1350     bool isImmediateFunctionContext() const {
1351       return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1352              (Context == ExpressionEvaluationContext::DiscardedStatement &&
1353               InImmediateFunctionContext);
1354     }
1355 
1356     bool isDiscardedStatementContext() const {
1357       return Context == ExpressionEvaluationContext::DiscardedStatement ||
1358              (Context ==
1359                   ExpressionEvaluationContext::ImmediateFunctionContext &&
1360               InDiscardedStatement);
1361     }
1362   };
1363 
1364   /// A stack of expression evaluation contexts.
1365   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1366 
1367   /// Emit a warning for all pending noderef expressions that we recorded.
1368   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1369 
1370   /// Compute the mangling number context for a lambda expression or
1371   /// block literal. Also return the extra mangling decl if any.
1372   ///
1373   /// \param DC - The DeclContext containing the lambda expression or
1374   /// block literal.
1375   std::tuple<MangleNumberingContext *, Decl *>
1376   getCurrentMangleNumberContext(const DeclContext *DC);
1377 
1378 
1379   /// SpecialMemberOverloadResult - The overloading result for a special member
1380   /// function.
1381   ///
1382   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1383   /// integer are used to determine whether overload resolution succeeded.
1384   class SpecialMemberOverloadResult {
1385   public:
1386     enum Kind {
1387       NoMemberOrDeleted,
1388       Ambiguous,
1389       Success
1390     };
1391 
1392   private:
1393     llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1394 
1395   public:
1396     SpecialMemberOverloadResult() {}
1397     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1398         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1399 
1400     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1401     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1402 
1403     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1404     void setKind(Kind K) { Pair.setInt(K); }
1405   };
1406 
1407   class SpecialMemberOverloadResultEntry
1408       : public llvm::FastFoldingSetNode,
1409         public SpecialMemberOverloadResult {
1410   public:
1411     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1412       : FastFoldingSetNode(ID)
1413     {}
1414   };
1415 
1416   /// A cache of special member function overload resolution results
1417   /// for C++ records.
1418   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1419 
1420   /// A cache of the flags available in enumerations with the flag_bits
1421   /// attribute.
1422   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1423 
1424   /// The kind of translation unit we are processing.
1425   ///
1426   /// When we're processing a complete translation unit, Sema will perform
1427   /// end-of-translation-unit semantic tasks (such as creating
1428   /// initializers for tentative definitions in C) once parsing has
1429   /// completed. Modules and precompiled headers perform different kinds of
1430   /// checks.
1431   const TranslationUnitKind TUKind;
1432 
1433   llvm::BumpPtrAllocator BumpAlloc;
1434 
1435   /// The number of SFINAE diagnostics that have been trapped.
1436   unsigned NumSFINAEErrors;
1437 
1438   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1439     UnparsedDefaultArgInstantiationsMap;
1440 
1441   /// A mapping from parameters with unparsed default arguments to the
1442   /// set of instantiations of each parameter.
1443   ///
1444   /// This mapping is a temporary data structure used when parsing
1445   /// nested class templates or nested classes of class templates,
1446   /// where we might end up instantiating an inner class before the
1447   /// default arguments of its methods have been parsed.
1448   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1449 
1450   // Contains the locations of the beginning of unparsed default
1451   // argument locations.
1452   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1453 
1454   /// UndefinedInternals - all the used, undefined objects which require a
1455   /// definition in this translation unit.
1456   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1457 
1458   /// Determine if VD, which must be a variable or function, is an external
1459   /// symbol that nonetheless can't be referenced from outside this translation
1460   /// unit because its type has no linkage and it's not extern "C".
1461   bool isExternalWithNoLinkageType(ValueDecl *VD);
1462 
1463   /// Obtain a sorted list of functions that are undefined but ODR-used.
1464   void getUndefinedButUsed(
1465       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1466 
1467   /// Retrieves list of suspicious delete-expressions that will be checked at
1468   /// the end of translation unit.
1469   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1470   getMismatchingDeleteExpressions() const;
1471 
1472   class GlobalMethodPool {
1473   public:
1474     using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1475     using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1476     iterator begin() { return Methods.begin(); }
1477     iterator end() { return Methods.end(); }
1478     iterator find(Selector Sel) { return Methods.find(Sel); }
1479     std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1480       return Methods.insert(Val);
1481     }
1482     int count(Selector Sel) const { return Methods.count(Sel); }
1483     bool empty() const { return Methods.empty(); }
1484 
1485   private:
1486     llvm::DenseMap<Selector, Lists> Methods;
1487   };
1488 
1489   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1490   /// We need to maintain a list, since selectors can have differing signatures
1491   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1492   /// of selectors are "overloaded").
1493   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1494   /// methods inside categories with a particular selector.
1495   GlobalMethodPool MethodPool;
1496 
1497   /// Method selectors used in a \@selector expression. Used for implementation
1498   /// of -Wselector.
1499   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1500 
1501   /// List of SourceLocations where 'self' is implicitly retained inside a
1502   /// block.
1503   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1504       ImplicitlyRetainedSelfLocs;
1505 
1506   /// Kinds of C++ special members.
1507   enum CXXSpecialMember {
1508     CXXDefaultConstructor,
1509     CXXCopyConstructor,
1510     CXXMoveConstructor,
1511     CXXCopyAssignment,
1512     CXXMoveAssignment,
1513     CXXDestructor,
1514     CXXInvalid
1515   };
1516 
1517   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1518       SpecialMemberDecl;
1519 
1520   /// The C++ special members which we are currently in the process of
1521   /// declaring. If this process recursively triggers the declaration of the
1522   /// same special member, we should act as if it is not yet declared.
1523   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1524 
1525   /// Kinds of defaulted comparison operator functions.
1526   enum class DefaultedComparisonKind : unsigned char {
1527     /// This is not a defaultable comparison operator.
1528     None,
1529     /// This is an operator== that should be implemented as a series of
1530     /// subobject comparisons.
1531     Equal,
1532     /// This is an operator<=> that should be implemented as a series of
1533     /// subobject comparisons.
1534     ThreeWay,
1535     /// This is an operator!= that should be implemented as a rewrite in terms
1536     /// of a == comparison.
1537     NotEqual,
1538     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1539     /// terms of a <=> comparison.
1540     Relational,
1541   };
1542 
1543   /// The function definitions which were renamed as part of typo-correction
1544   /// to match their respective declarations. We want to keep track of them
1545   /// to ensure that we don't emit a "redefinition" error if we encounter a
1546   /// correctly named definition after the renamed definition.
1547   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1548 
1549   /// Stack of types that correspond to the parameter entities that are
1550   /// currently being copy-initialized. Can be empty.
1551   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1552 
1553   void ReadMethodPool(Selector Sel);
1554   void updateOutOfDateSelector(Selector Sel);
1555 
1556   /// Private Helper predicate to check for 'self'.
1557   bool isSelfExpr(Expr *RExpr);
1558   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1559 
1560   /// Cause the active diagnostic on the DiagosticsEngine to be
1561   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1562   /// should not be used elsewhere.
1563   void EmitCurrentDiagnostic(unsigned DiagID);
1564 
1565   /// Records and restores the CurFPFeatures state on entry/exit of compound
1566   /// statements.
1567   class FPFeaturesStateRAII {
1568   public:
1569     FPFeaturesStateRAII(Sema &S);
1570     ~FPFeaturesStateRAII();
1571     FPOptionsOverride getOverrides() { return OldOverrides; }
1572 
1573   private:
1574     Sema& S;
1575     FPOptions OldFPFeaturesState;
1576     FPOptionsOverride OldOverrides;
1577     LangOptions::FPEvalMethodKind OldEvalMethod;
1578     SourceLocation OldFPPragmaLocation;
1579   };
1580 
1581   void addImplicitTypedef(StringRef Name, QualType T);
1582 
1583   bool WarnedStackExhausted = false;
1584 
1585   /// Increment when we find a reference; decrement when we find an ignored
1586   /// assignment.  Ultimately the value is 0 if every reference is an ignored
1587   /// assignment.
1588   llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1589 
1590 private:
1591   Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1592 
1593   bool WarnedDarwinSDKInfoMissing = false;
1594 
1595 public:
1596   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1597        TranslationUnitKind TUKind = TU_Complete,
1598        CodeCompleteConsumer *CompletionConsumer = nullptr);
1599   ~Sema();
1600 
1601   /// Perform initialization that occurs after the parser has been
1602   /// initialized but before it parses anything.
1603   void Initialize();
1604 
1605   /// This virtual key function only exists to limit the emission of debug info
1606   /// describing the Sema class. GCC and Clang only emit debug info for a class
1607   /// with a vtable when the vtable is emitted. Sema is final and not
1608   /// polymorphic, but the debug info size savings are so significant that it is
1609   /// worth adding a vtable just to take advantage of this optimization.
1610   virtual void anchor();
1611 
1612   const LangOptions &getLangOpts() const { return LangOpts; }
1613   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1614   FPOptions     &getCurFPFeatures() { return CurFPFeatures; }
1615 
1616   DiagnosticsEngine &getDiagnostics() const { return Diags; }
1617   SourceManager &getSourceManager() const { return SourceMgr; }
1618   Preprocessor &getPreprocessor() const { return PP; }
1619   ASTContext &getASTContext() const { return Context; }
1620   ASTConsumer &getASTConsumer() const { return Consumer; }
1621   ASTMutationListener *getASTMutationListener() const;
1622   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1623 
1624   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1625                                                          StringRef Platform);
1626   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1627 
1628   ///Registers an external source. If an external source already exists,
1629   /// creates a multiplex external source and appends to it.
1630   ///
1631   ///\param[in] E - A non-null external sema source.
1632   ///
1633   void addExternalSource(ExternalSemaSource *E);
1634 
1635   void PrintStats() const;
1636 
1637   /// Warn that the stack is nearly exhausted.
1638   void warnStackExhausted(SourceLocation Loc);
1639 
1640   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1641   /// guaranteed). Produces a warning if we're low on stack space and allocates
1642   /// more in that case. Use this in code that may recurse deeply (for example,
1643   /// in template instantiation) to avoid stack overflow.
1644   void runWithSufficientStackSpace(SourceLocation Loc,
1645                                    llvm::function_ref<void()> Fn);
1646 
1647   /// Helper class that creates diagnostics with optional
1648   /// template instantiation stacks.
1649   ///
1650   /// This class provides a wrapper around the basic DiagnosticBuilder
1651   /// class that emits diagnostics. ImmediateDiagBuilder is
1652   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1653   /// does) and, if the diagnostic comes from inside a template
1654   /// instantiation, printing the template instantiation stack as
1655   /// well.
1656   class ImmediateDiagBuilder : public DiagnosticBuilder {
1657     Sema &SemaRef;
1658     unsigned DiagID;
1659 
1660   public:
1661     ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1662         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1663     ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1664         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1665 
1666     // This is a cunning lie. DiagnosticBuilder actually performs move
1667     // construction in its copy constructor (but due to varied uses, it's not
1668     // possible to conveniently express this as actual move construction). So
1669     // the default copy ctor here is fine, because the base class disables the
1670     // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1671     // in that case anwyay.
1672     ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1673 
1674     ~ImmediateDiagBuilder() {
1675       // If we aren't active, there is nothing to do.
1676       if (!isActive()) return;
1677 
1678       // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1679       // builder itself so it won't emit the diagnostic in its own destructor.
1680       //
1681       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1682       // do its own needless checks to see if the diagnostic needs to be
1683       // emitted. However, because we take care to ensure that the builder
1684       // objects never escape, a sufficiently smart compiler will be able to
1685       // eliminate that code.
1686       Clear();
1687 
1688       // Dispatch to Sema to emit the diagnostic.
1689       SemaRef.EmitCurrentDiagnostic(DiagID);
1690     }
1691 
1692     /// Teach operator<< to produce an object of the correct type.
1693     template <typename T>
1694     friend const ImmediateDiagBuilder &
1695     operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1696       const DiagnosticBuilder &BaseDiag = Diag;
1697       BaseDiag << Value;
1698       return Diag;
1699     }
1700 
1701     // It is necessary to limit this to rvalue reference to avoid calling this
1702     // function with a bitfield lvalue argument since non-const reference to
1703     // bitfield is not allowed.
1704     template <typename T, typename = typename std::enable_if<
1705                               !std::is_lvalue_reference<T>::value>::type>
1706     const ImmediateDiagBuilder &operator<<(T &&V) const {
1707       const DiagnosticBuilder &BaseDiag = *this;
1708       BaseDiag << std::move(V);
1709       return *this;
1710     }
1711   };
1712 
1713   /// A generic diagnostic builder for errors which may or may not be deferred.
1714   ///
1715   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1716   /// which are not allowed to appear inside __device__ functions and are
1717   /// allowed to appear in __host__ __device__ functions only if the host+device
1718   /// function is never codegen'ed.
1719   ///
1720   /// To handle this, we use the notion of "deferred diagnostics", where we
1721   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1722   ///
1723   /// This class lets you emit either a regular diagnostic, a deferred
1724   /// diagnostic, or no diagnostic at all, according to an argument you pass to
1725   /// its constructor, thus simplifying the process of creating these "maybe
1726   /// deferred" diagnostics.
1727   class SemaDiagnosticBuilder {
1728   public:
1729     enum Kind {
1730       /// Emit no diagnostics.
1731       K_Nop,
1732       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1733       K_Immediate,
1734       /// Emit the diagnostic immediately, and, if it's a warning or error, also
1735       /// emit a call stack showing how this function can be reached by an a
1736       /// priori known-emitted function.
1737       K_ImmediateWithCallStack,
1738       /// Create a deferred diagnostic, which is emitted only if the function
1739       /// it's attached to is codegen'ed.  Also emit a call stack as with
1740       /// K_ImmediateWithCallStack.
1741       K_Deferred
1742     };
1743 
1744     SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1745                           FunctionDecl *Fn, Sema &S);
1746     SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1747     SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1748     ~SemaDiagnosticBuilder();
1749 
1750     bool isImmediate() const { return ImmediateDiag.has_value(); }
1751 
1752     /// Convertible to bool: True if we immediately emitted an error, false if
1753     /// we didn't emit an error or we created a deferred error.
1754     ///
1755     /// Example usage:
1756     ///
1757     ///   if (SemaDiagnosticBuilder(...) << foo << bar)
1758     ///     return ExprError();
1759     ///
1760     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1761     /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1762     operator bool() const { return isImmediate(); }
1763 
1764     template <typename T>
1765     friend const SemaDiagnosticBuilder &
1766     operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1767       if (Diag.ImmediateDiag)
1768         *Diag.ImmediateDiag << Value;
1769       else if (Diag.PartialDiagId)
1770         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1771             << Value;
1772       return Diag;
1773     }
1774 
1775     // It is necessary to limit this to rvalue reference to avoid calling this
1776     // function with a bitfield lvalue argument since non-const reference to
1777     // bitfield is not allowed.
1778     template <typename T, typename = typename std::enable_if<
1779                               !std::is_lvalue_reference<T>::value>::type>
1780     const SemaDiagnosticBuilder &operator<<(T &&V) const {
1781       if (ImmediateDiag)
1782         *ImmediateDiag << std::move(V);
1783       else if (PartialDiagId)
1784         S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1785       return *this;
1786     }
1787 
1788     friend const SemaDiagnosticBuilder &
1789     operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1790       if (Diag.ImmediateDiag)
1791         PD.Emit(*Diag.ImmediateDiag);
1792       else if (Diag.PartialDiagId)
1793         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1794       return Diag;
1795     }
1796 
1797     void AddFixItHint(const FixItHint &Hint) const {
1798       if (ImmediateDiag)
1799         ImmediateDiag->AddFixItHint(Hint);
1800       else if (PartialDiagId)
1801         S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1802     }
1803 
1804     friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1805       return ExprError();
1806     }
1807     friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1808       return StmtError();
1809     }
1810     operator ExprResult() const { return ExprError(); }
1811     operator StmtResult() const { return StmtError(); }
1812     operator TypeResult() const { return TypeError(); }
1813     operator DeclResult() const { return DeclResult(true); }
1814     operator MemInitResult() const { return MemInitResult(true); }
1815 
1816   private:
1817     Sema &S;
1818     SourceLocation Loc;
1819     unsigned DiagID;
1820     FunctionDecl *Fn;
1821     bool ShowCallStack;
1822 
1823     // Invariant: At most one of these Optionals has a value.
1824     // FIXME: Switch these to a Variant once that exists.
1825     llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1826     llvm::Optional<unsigned> PartialDiagId;
1827   };
1828 
1829   /// Is the last error level diagnostic immediate. This is used to determined
1830   /// whether the next info diagnostic should be immediate.
1831   bool IsLastErrorImmediate = true;
1832 
1833   /// Emit a diagnostic.
1834   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1835                              bool DeferHint = false);
1836 
1837   /// Emit a partial diagnostic.
1838   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1839                              bool DeferHint = false);
1840 
1841   /// Build a partial diagnostic.
1842   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1843 
1844   /// Whether deferrable diagnostics should be deferred.
1845   bool DeferDiags = false;
1846 
1847   /// RAII class to control scope of DeferDiags.
1848   class DeferDiagsRAII {
1849     Sema &S;
1850     bool SavedDeferDiags = false;
1851 
1852   public:
1853     DeferDiagsRAII(Sema &S, bool DeferDiags)
1854         : S(S), SavedDeferDiags(S.DeferDiags) {
1855       S.DeferDiags = DeferDiags;
1856     }
1857     ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1858   };
1859 
1860   /// Whether uncompilable error has occurred. This includes error happens
1861   /// in deferred diagnostics.
1862   bool hasUncompilableErrorOccurred() const;
1863 
1864   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1865 
1866   /// Get a string to suggest for zero-initialization of a type.
1867   std::string
1868   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1869   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1870 
1871   /// Calls \c Lexer::getLocForEndOfToken()
1872   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1873 
1874   /// Retrieve the module loader associated with the preprocessor.
1875   ModuleLoader &getModuleLoader() const;
1876 
1877   /// Invent a new identifier for parameters of abbreviated templates.
1878   IdentifierInfo *
1879   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1880                                              unsigned Index);
1881 
1882   void emitAndClearUnusedLocalTypedefWarnings();
1883 
1884   private:
1885     /// Function or variable declarations to be checked for whether the deferred
1886     /// diagnostics should be emitted.
1887     llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1888 
1889   public:
1890   // Emit all deferred diagnostics.
1891   void emitDeferredDiags();
1892 
1893   enum TUFragmentKind {
1894     /// The global module fragment, between 'module;' and a module-declaration.
1895     Global,
1896     /// A normal translation unit fragment. For a non-module unit, this is the
1897     /// entire translation unit. Otherwise, it runs from the module-declaration
1898     /// to the private-module-fragment (if any) or the end of the TU (if not).
1899     Normal,
1900     /// The private module fragment, between 'module :private;' and the end of
1901     /// the translation unit.
1902     Private
1903   };
1904 
1905   void ActOnStartOfTranslationUnit();
1906   void ActOnEndOfTranslationUnit();
1907   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1908 
1909   void CheckDelegatingCtorCycles();
1910 
1911   Scope *getScopeForContext(DeclContext *Ctx);
1912 
1913   void PushFunctionScope();
1914   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1915   sema::LambdaScopeInfo *PushLambdaScope();
1916 
1917   /// This is used to inform Sema what the current TemplateParameterDepth
1918   /// is during Parsing.  Currently it is used to pass on the depth
1919   /// when parsing generic lambda 'auto' parameters.
1920   void RecordParsingTemplateParameterDepth(unsigned Depth);
1921 
1922   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1923                                RecordDecl *RD, CapturedRegionKind K,
1924                                unsigned OpenMPCaptureLevel = 0);
1925 
1926   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1927   /// time after they've been popped.
1928   class PoppedFunctionScopeDeleter {
1929     Sema *Self;
1930 
1931   public:
1932     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1933     void operator()(sema::FunctionScopeInfo *Scope) const;
1934   };
1935 
1936   using PoppedFunctionScopePtr =
1937       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1938 
1939   PoppedFunctionScopePtr
1940   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1941                        const Decl *D = nullptr,
1942                        QualType BlockType = QualType());
1943 
1944   sema::FunctionScopeInfo *getCurFunction() const {
1945     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1946   }
1947 
1948   sema::FunctionScopeInfo *getEnclosingFunction() const;
1949 
1950   void setFunctionHasBranchIntoScope();
1951   void setFunctionHasBranchProtectedScope();
1952   void setFunctionHasIndirectGoto();
1953   void setFunctionHasMustTail();
1954 
1955   void PushCompoundScope(bool IsStmtExpr);
1956   void PopCompoundScope();
1957 
1958   sema::CompoundScopeInfo &getCurCompoundScope() const;
1959 
1960   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1961 
1962   /// Retrieve the current block, if any.
1963   sema::BlockScopeInfo *getCurBlock();
1964 
1965   /// Get the innermost lambda enclosing the current location, if any. This
1966   /// looks through intervening non-lambda scopes such as local functions and
1967   /// blocks.
1968   sema::LambdaScopeInfo *getEnclosingLambda() const;
1969 
1970   /// Retrieve the current lambda scope info, if any.
1971   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1972   /// lambda scope info ignoring all inner capturing scopes that are not
1973   /// lambda scopes.
1974   sema::LambdaScopeInfo *
1975   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1976 
1977   /// Retrieve the current generic lambda info, if any.
1978   sema::LambdaScopeInfo *getCurGenericLambda();
1979 
1980   /// Retrieve the current captured region, if any.
1981   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1982 
1983   /// Retrieve the current function, if any, that should be analyzed for
1984   /// potential availability violations.
1985   sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
1986 
1987   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1988   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1989 
1990   /// Called before parsing a function declarator belonging to a function
1991   /// declaration.
1992   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1993                                                unsigned TemplateParameterDepth);
1994 
1995   /// Called after parsing a function declarator belonging to a function
1996   /// declaration.
1997   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1998 
1999   void ActOnComment(SourceRange Comment);
2000 
2001   //===--------------------------------------------------------------------===//
2002   // Type Analysis / Processing: SemaType.cpp.
2003   //
2004 
2005   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2006                               const DeclSpec *DS = nullptr);
2007   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2008                               const DeclSpec *DS = nullptr);
2009   QualType BuildPointerType(QualType T,
2010                             SourceLocation Loc, DeclarationName Entity);
2011   QualType BuildReferenceType(QualType T, bool LValueRef,
2012                               SourceLocation Loc, DeclarationName Entity);
2013   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2014                           Expr *ArraySize, unsigned Quals,
2015                           SourceRange Brackets, DeclarationName Entity);
2016   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2017   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2018                               SourceLocation AttrLoc);
2019   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2020                            SourceLocation AttrLoc);
2021 
2022   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2023                                  SourceLocation AttrLoc);
2024 
2025   /// Same as above, but constructs the AddressSpace index if not provided.
2026   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2027                                  SourceLocation AttrLoc);
2028 
2029   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2030 
2031   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2032 
2033   /// Build a function type.
2034   ///
2035   /// This routine checks the function type according to C++ rules and
2036   /// under the assumption that the result type and parameter types have
2037   /// just been instantiated from a template. It therefore duplicates
2038   /// some of the behavior of GetTypeForDeclarator, but in a much
2039   /// simpler form that is only suitable for this narrow use case.
2040   ///
2041   /// \param T The return type of the function.
2042   ///
2043   /// \param ParamTypes The parameter types of the function. This array
2044   /// will be modified to account for adjustments to the types of the
2045   /// function parameters.
2046   ///
2047   /// \param Loc The location of the entity whose type involves this
2048   /// function type or, if there is no such entity, the location of the
2049   /// type that will have function type.
2050   ///
2051   /// \param Entity The name of the entity that involves the function
2052   /// type, if known.
2053   ///
2054   /// \param EPI Extra information about the function type. Usually this will
2055   /// be taken from an existing function with the same prototype.
2056   ///
2057   /// \returns A suitable function type, if there are no errors. The
2058   /// unqualified type will always be a FunctionProtoType.
2059   /// Otherwise, returns a NULL type.
2060   QualType BuildFunctionType(QualType T,
2061                              MutableArrayRef<QualType> ParamTypes,
2062                              SourceLocation Loc, DeclarationName Entity,
2063                              const FunctionProtoType::ExtProtoInfo &EPI);
2064 
2065   QualType BuildMemberPointerType(QualType T, QualType Class,
2066                                   SourceLocation Loc,
2067                                   DeclarationName Entity);
2068   QualType BuildBlockPointerType(QualType T,
2069                                  SourceLocation Loc, DeclarationName Entity);
2070   QualType BuildParenType(QualType T);
2071   QualType BuildAtomicType(QualType T, SourceLocation Loc);
2072   QualType BuildReadPipeType(QualType T,
2073                          SourceLocation Loc);
2074   QualType BuildWritePipeType(QualType T,
2075                          SourceLocation Loc);
2076   QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2077 
2078   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2079   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2080 
2081   /// Package the given type and TSI into a ParsedType.
2082   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2083   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2084   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2085   static QualType GetTypeFromParser(ParsedType Ty,
2086                                     TypeSourceInfo **TInfo = nullptr);
2087   CanThrowResult canThrow(const Stmt *E);
2088   /// Determine whether the callee of a particular function call can throw.
2089   /// E, D and Loc are all optional.
2090   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2091                                        SourceLocation Loc = SourceLocation());
2092   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2093                                                 const FunctionProtoType *FPT);
2094   void UpdateExceptionSpec(FunctionDecl *FD,
2095                            const FunctionProtoType::ExceptionSpecInfo &ESI);
2096   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2097   bool CheckDistantExceptionSpec(QualType T);
2098   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2099   bool CheckEquivalentExceptionSpec(
2100       const FunctionProtoType *Old, SourceLocation OldLoc,
2101       const FunctionProtoType *New, SourceLocation NewLoc);
2102   bool CheckEquivalentExceptionSpec(
2103       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2104       const FunctionProtoType *Old, SourceLocation OldLoc,
2105       const FunctionProtoType *New, SourceLocation NewLoc);
2106   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2107   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2108                                 const PartialDiagnostic &NestedDiagID,
2109                                 const PartialDiagnostic &NoteID,
2110                                 const PartialDiagnostic &NoThrowDiagID,
2111                                 const FunctionProtoType *Superset,
2112                                 SourceLocation SuperLoc,
2113                                 const FunctionProtoType *Subset,
2114                                 SourceLocation SubLoc);
2115   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2116                                const PartialDiagnostic &NoteID,
2117                                const FunctionProtoType *Target,
2118                                SourceLocation TargetLoc,
2119                                const FunctionProtoType *Source,
2120                                SourceLocation SourceLoc);
2121 
2122   TypeResult ActOnTypeName(Scope *S, Declarator &D);
2123 
2124   /// The parser has parsed the context-sensitive type 'instancetype'
2125   /// in an Objective-C message declaration. Return the appropriate type.
2126   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2127 
2128   /// Abstract class used to diagnose incomplete types.
2129   struct TypeDiagnoser {
2130     TypeDiagnoser() {}
2131 
2132     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2133     virtual ~TypeDiagnoser() {}
2134   };
2135 
2136   static int getPrintable(int I) { return I; }
2137   static unsigned getPrintable(unsigned I) { return I; }
2138   static bool getPrintable(bool B) { return B; }
2139   static const char * getPrintable(const char *S) { return S; }
2140   static StringRef getPrintable(StringRef S) { return S; }
2141   static const std::string &getPrintable(const std::string &S) { return S; }
2142   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2143     return II;
2144   }
2145   static DeclarationName getPrintable(DeclarationName N) { return N; }
2146   static QualType getPrintable(QualType T) { return T; }
2147   static SourceRange getPrintable(SourceRange R) { return R; }
2148   static SourceRange getPrintable(SourceLocation L) { return L; }
2149   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2150   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2151 
2152   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2153   protected:
2154     unsigned DiagID;
2155     std::tuple<const Ts &...> Args;
2156 
2157     template <std::size_t... Is>
2158     void emit(const SemaDiagnosticBuilder &DB,
2159               std::index_sequence<Is...>) const {
2160       // Apply all tuple elements to the builder in order.
2161       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2162       (void)Dummy;
2163     }
2164 
2165   public:
2166     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2167         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2168       assert(DiagID != 0 && "no diagnostic for type diagnoser");
2169     }
2170 
2171     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2172       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2173       emit(DB, std::index_sequence_for<Ts...>());
2174       DB << T;
2175     }
2176   };
2177 
2178   /// Do a check to make sure \p Name looks like a legal argument for the
2179   /// swift_name attribute applied to decl \p D.  Raise a diagnostic if the name
2180   /// is invalid for the given declaration.
2181   ///
2182   /// \p AL is used to provide caret diagnostics in case of a malformed name.
2183   ///
2184   /// \returns true if the name is a valid swift name for \p D, false otherwise.
2185   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2186                          const ParsedAttr &AL, bool IsAsync);
2187 
2188   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2189   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2190   /// For example, a diagnostic with no other parameters would generally have
2191   /// the form "...%select{incomplete|sizeless}0 type %1...".
2192   template <typename... Ts>
2193   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2194   public:
2195     SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2196         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2197 
2198     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2199       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2200       this->emit(DB, std::index_sequence_for<Ts...>());
2201       DB << T->isSizelessType() << T;
2202     }
2203   };
2204 
2205   enum class CompleteTypeKind {
2206     /// Apply the normal rules for complete types.  In particular,
2207     /// treat all sizeless types as incomplete.
2208     Normal,
2209 
2210     /// Relax the normal rules for complete types so that they include
2211     /// sizeless built-in types.
2212     AcceptSizeless,
2213 
2214     // FIXME: Eventually we should flip the default to Normal and opt in
2215     // to AcceptSizeless rather than opt out of it.
2216     Default = AcceptSizeless
2217   };
2218 
2219   enum class AcceptableKind { Visible, Reachable };
2220 
2221 private:
2222   /// Methods for marking which expressions involve dereferencing a pointer
2223   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2224   /// they are parsed, meaning that a noderef pointer may not be accessed. For
2225   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2226   /// `*p`, but need to check that `address of` is called on it. This requires
2227   /// keeping a container of all pending expressions and checking if the address
2228   /// of them are eventually taken.
2229   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2230   void CheckAddressOfNoDeref(const Expr *E);
2231   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2232 
2233   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2234                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2235 
2236   struct ModuleScope {
2237     SourceLocation BeginLoc;
2238     clang::Module *Module = nullptr;
2239     bool ModuleInterface = false;
2240     bool IsPartition = false;
2241     bool ImplicitGlobalModuleFragment = false;
2242     VisibleModuleSet OuterVisibleModules;
2243   };
2244   /// The modules we're currently parsing.
2245   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2246   /// The global module fragment of the current translation unit.
2247   clang::Module *GlobalModuleFragment = nullptr;
2248 
2249   /// The modules we imported directly.
2250   llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2251 
2252   /// Namespace definitions that we will export when they finish.
2253   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2254 
2255   /// Helper function to judge if we are in module purview.
2256   /// Return false if we are not in a module.
2257   bool isCurrentModulePurview() const {
2258     return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2259   }
2260 
2261   /// Enter the scope of the global module.
2262   Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2263   /// Leave the scope of the global module.
2264   void PopGlobalModuleFragment();
2265 
2266   VisibleModuleSet VisibleModules;
2267 
2268   /// Cache for module units which is usable for current module.
2269   llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2270 
2271   bool isUsableModule(const Module *M);
2272 
2273   bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2274 
2275 public:
2276   /// Get the module unit whose scope we are currently within.
2277   Module *getCurrentModule() const {
2278     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2279   }
2280 
2281   /// Get the module owning an entity.
2282   Module *getOwningModule(const Decl *Entity) {
2283     return Entity->getOwningModule();
2284   }
2285 
2286   bool isModuleDirectlyImported(const Module *M) {
2287     return DirectModuleImports.contains(M);
2288   }
2289 
2290   /// Make a merged definition of an existing hidden definition \p ND
2291   /// visible at the specified location.
2292   void makeMergedDefinitionVisible(NamedDecl *ND);
2293 
2294   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2295 
2296   // When loading a non-modular PCH files, this is used to restore module
2297   // visibility.
2298   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2299     VisibleModules.setVisible(Mod, ImportLoc);
2300   }
2301 
2302   /// Determine whether a declaration is visible to name lookup.
2303   bool isVisible(const NamedDecl *D) {
2304     return D->isUnconditionallyVisible() ||
2305            isAcceptableSlow(D, AcceptableKind::Visible);
2306   }
2307 
2308   /// Determine whether a declaration is reachable.
2309   bool isReachable(const NamedDecl *D) {
2310     // All visible declarations are reachable.
2311     return D->isUnconditionallyVisible() ||
2312            isAcceptableSlow(D, AcceptableKind::Reachable);
2313   }
2314 
2315   /// Determine whether a declaration is acceptable (visible/reachable).
2316   bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2317     return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2318   }
2319 
2320   /// Determine whether any declaration of an entity is visible.
2321   bool
2322   hasVisibleDeclaration(const NamedDecl *D,
2323                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2324     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2325   }
2326 
2327   bool hasVisibleDeclarationSlow(const NamedDecl *D,
2328                                  llvm::SmallVectorImpl<Module *> *Modules);
2329   /// Determine whether any declaration of an entity is reachable.
2330   bool
2331   hasReachableDeclaration(const NamedDecl *D,
2332                           llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2333     return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2334   }
2335   bool hasReachableDeclarationSlow(
2336       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2337 
2338   bool hasVisibleMergedDefinition(NamedDecl *Def);
2339   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2340 
2341   /// Determine if \p D and \p Suggested have a structurally compatible
2342   /// layout as described in C11 6.2.7/1.
2343   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2344 
2345   /// Determine if \p D has a visible definition. If not, suggest a declaration
2346   /// that should be made visible to expose the definition.
2347   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2348                             bool OnlyNeedComplete = false);
2349   bool hasVisibleDefinition(const NamedDecl *D) {
2350     NamedDecl *Hidden;
2351     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2352   }
2353 
2354   /// Determine if \p D has a reachable definition. If not, suggest a
2355   /// declaration that should be made reachable to expose the definition.
2356   bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2357                               bool OnlyNeedComplete = false);
2358   bool hasReachableDefinition(NamedDecl *D) {
2359     NamedDecl *Hidden;
2360     return hasReachableDefinition(D, &Hidden);
2361   }
2362 
2363   bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2364                                AcceptableKind Kind,
2365                                bool OnlyNeedComplete = false);
2366   bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2367     NamedDecl *Hidden;
2368     return hasAcceptableDefinition(D, &Hidden, Kind);
2369   }
2370 
2371   /// Determine if the template parameter \p D has a visible default argument.
2372   bool
2373   hasVisibleDefaultArgument(const NamedDecl *D,
2374                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2375   /// Determine if the template parameter \p D has a reachable default argument.
2376   bool hasReachableDefaultArgument(
2377       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2378   /// Determine if the template parameter \p D has a reachable default argument.
2379   bool hasAcceptableDefaultArgument(const NamedDecl *D,
2380                                     llvm::SmallVectorImpl<Module *> *Modules,
2381                                     Sema::AcceptableKind Kind);
2382 
2383   /// Determine if there is a visible declaration of \p D that is an explicit
2384   /// specialization declaration for a specialization of a template. (For a
2385   /// member specialization, use hasVisibleMemberSpecialization.)
2386   bool hasVisibleExplicitSpecialization(
2387       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2388   /// Determine if there is a reachable declaration of \p D that is an explicit
2389   /// specialization declaration for a specialization of a template. (For a
2390   /// member specialization, use hasReachableMemberSpecialization.)
2391   bool hasReachableExplicitSpecialization(
2392       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2393 
2394   /// Determine if there is a visible declaration of \p D that is a member
2395   /// specialization declaration (as opposed to an instantiated declaration).
2396   bool hasVisibleMemberSpecialization(
2397       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2398   /// Determine if there is a reachable declaration of \p D that is a member
2399   /// specialization declaration (as opposed to an instantiated declaration).
2400   bool hasReachableMemberSpecialization(
2401       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2402 
2403   /// Determine if \p A and \p B are equivalent internal linkage declarations
2404   /// from different modules, and thus an ambiguity error can be downgraded to
2405   /// an extension warning.
2406   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2407                                               const NamedDecl *B);
2408   void diagnoseEquivalentInternalLinkageDeclarations(
2409       SourceLocation Loc, const NamedDecl *D,
2410       ArrayRef<const NamedDecl *> Equiv);
2411 
2412   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2413 
2414   bool isCompleteType(SourceLocation Loc, QualType T,
2415                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
2416     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2417   }
2418   bool RequireCompleteType(SourceLocation Loc, QualType T,
2419                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2420   bool RequireCompleteType(SourceLocation Loc, QualType T,
2421                            CompleteTypeKind Kind, unsigned DiagID);
2422 
2423   bool RequireCompleteType(SourceLocation Loc, QualType T,
2424                            TypeDiagnoser &Diagnoser) {
2425     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2426   }
2427   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2428     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2429   }
2430 
2431   template <typename... Ts>
2432   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2433                            const Ts &...Args) {
2434     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2435     return RequireCompleteType(Loc, T, Diagnoser);
2436   }
2437 
2438   template <typename... Ts>
2439   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2440                                 const Ts &... Args) {
2441     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2442     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2443   }
2444 
2445   /// Get the type of expression E, triggering instantiation to complete the
2446   /// type if necessary -- that is, if the expression refers to a templated
2447   /// static data member of incomplete array type.
2448   ///
2449   /// May still return an incomplete type if instantiation was not possible or
2450   /// if the type is incomplete for a different reason. Use
2451   /// RequireCompleteExprType instead if a diagnostic is expected for an
2452   /// incomplete expression type.
2453   QualType getCompletedType(Expr *E);
2454 
2455   void completeExprArrayBound(Expr *E);
2456   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2457                                TypeDiagnoser &Diagnoser);
2458   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2459 
2460   template <typename... Ts>
2461   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2462     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2463     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2464   }
2465 
2466   template <typename... Ts>
2467   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2468                                     const Ts &... Args) {
2469     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2470     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2471   }
2472 
2473   bool RequireLiteralType(SourceLocation Loc, QualType T,
2474                           TypeDiagnoser &Diagnoser);
2475   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2476 
2477   template <typename... Ts>
2478   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2479                           const Ts &...Args) {
2480     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2481     return RequireLiteralType(Loc, T, Diagnoser);
2482   }
2483 
2484   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2485                              const CXXScopeSpec &SS, QualType T,
2486                              TagDecl *OwnedTagDecl = nullptr);
2487 
2488   // Returns the underlying type of a decltype with the given expression.
2489   QualType getDecltypeForExpr(Expr *E);
2490 
2491   QualType BuildTypeofExprType(Expr *E);
2492   /// If AsUnevaluated is false, E is treated as though it were an evaluated
2493   /// context, such as when building a type for decltype(auto).
2494   QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2495   QualType BuildUnaryTransformType(QualType BaseType,
2496                                    UnaryTransformType::UTTKind UKind,
2497                                    SourceLocation Loc);
2498 
2499   //===--------------------------------------------------------------------===//
2500   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2501   //
2502 
2503   struct SkipBodyInfo {
2504     SkipBodyInfo()
2505         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2506           New(nullptr) {}
2507     bool ShouldSkip;
2508     bool CheckSameAsPrevious;
2509     NamedDecl *Previous;
2510     NamedDecl *New;
2511   };
2512 
2513   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2514 
2515   void DiagnoseUseOfUnimplementedSelectors();
2516 
2517   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2518 
2519   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2520                          Scope *S, CXXScopeSpec *SS = nullptr,
2521                          bool isClassName = false, bool HasTrailingDot = false,
2522                          ParsedType ObjectType = nullptr,
2523                          bool IsCtorOrDtorName = false,
2524                          bool WantNontrivialTypeSourceInfo = false,
2525                          bool IsClassTemplateDeductionContext = true,
2526                          IdentifierInfo **CorrectedII = nullptr);
2527   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2528   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2529   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2530                                SourceLocation IILoc,
2531                                Scope *S,
2532                                CXXScopeSpec *SS,
2533                                ParsedType &SuggestedType,
2534                                bool IsTemplateName = false);
2535 
2536   /// Attempt to behave like MSVC in situations where lookup of an unqualified
2537   /// type name has failed in a dependent context. In these situations, we
2538   /// automatically form a DependentTypeName that will retry lookup in a related
2539   /// scope during instantiation.
2540   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2541                                       SourceLocation NameLoc,
2542                                       bool IsTemplateTypeArg);
2543 
2544   /// Describes the result of the name lookup and resolution performed
2545   /// by \c ClassifyName().
2546   enum NameClassificationKind {
2547     /// This name is not a type or template in this context, but might be
2548     /// something else.
2549     NC_Unknown,
2550     /// Classification failed; an error has been produced.
2551     NC_Error,
2552     /// The name has been typo-corrected to a keyword.
2553     NC_Keyword,
2554     /// The name was classified as a type.
2555     NC_Type,
2556     /// The name was classified as a specific non-type, non-template
2557     /// declaration. ActOnNameClassifiedAsNonType should be called to
2558     /// convert the declaration to an expression.
2559     NC_NonType,
2560     /// The name was classified as an ADL-only function name.
2561     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2562     /// result to an expression.
2563     NC_UndeclaredNonType,
2564     /// The name denotes a member of a dependent type that could not be
2565     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2566     /// convert the result to an expression.
2567     NC_DependentNonType,
2568     /// The name was classified as an overload set, and an expression
2569     /// representing that overload set has been formed.
2570     /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2571     /// expression referencing the overload set.
2572     NC_OverloadSet,
2573     /// The name was classified as a template whose specializations are types.
2574     NC_TypeTemplate,
2575     /// The name was classified as a variable template name.
2576     NC_VarTemplate,
2577     /// The name was classified as a function template name.
2578     NC_FunctionTemplate,
2579     /// The name was classified as an ADL-only function template name.
2580     NC_UndeclaredTemplate,
2581     /// The name was classified as a concept name.
2582     NC_Concept,
2583   };
2584 
2585   class NameClassification {
2586     NameClassificationKind Kind;
2587     union {
2588       ExprResult Expr;
2589       NamedDecl *NonTypeDecl;
2590       TemplateName Template;
2591       ParsedType Type;
2592     };
2593 
2594     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2595 
2596   public:
2597     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2598 
2599     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2600 
2601     static NameClassification Error() {
2602       return NameClassification(NC_Error);
2603     }
2604 
2605     static NameClassification Unknown() {
2606       return NameClassification(NC_Unknown);
2607     }
2608 
2609     static NameClassification OverloadSet(ExprResult E) {
2610       NameClassification Result(NC_OverloadSet);
2611       Result.Expr = E;
2612       return Result;
2613     }
2614 
2615     static NameClassification NonType(NamedDecl *D) {
2616       NameClassification Result(NC_NonType);
2617       Result.NonTypeDecl = D;
2618       return Result;
2619     }
2620 
2621     static NameClassification UndeclaredNonType() {
2622       return NameClassification(NC_UndeclaredNonType);
2623     }
2624 
2625     static NameClassification DependentNonType() {
2626       return NameClassification(NC_DependentNonType);
2627     }
2628 
2629     static NameClassification TypeTemplate(TemplateName Name) {
2630       NameClassification Result(NC_TypeTemplate);
2631       Result.Template = Name;
2632       return Result;
2633     }
2634 
2635     static NameClassification VarTemplate(TemplateName Name) {
2636       NameClassification Result(NC_VarTemplate);
2637       Result.Template = Name;
2638       return Result;
2639     }
2640 
2641     static NameClassification FunctionTemplate(TemplateName Name) {
2642       NameClassification Result(NC_FunctionTemplate);
2643       Result.Template = Name;
2644       return Result;
2645     }
2646 
2647     static NameClassification Concept(TemplateName Name) {
2648       NameClassification Result(NC_Concept);
2649       Result.Template = Name;
2650       return Result;
2651     }
2652 
2653     static NameClassification UndeclaredTemplate(TemplateName Name) {
2654       NameClassification Result(NC_UndeclaredTemplate);
2655       Result.Template = Name;
2656       return Result;
2657     }
2658 
2659     NameClassificationKind getKind() const { return Kind; }
2660 
2661     ExprResult getExpression() const {
2662       assert(Kind == NC_OverloadSet);
2663       return Expr;
2664     }
2665 
2666     ParsedType getType() const {
2667       assert(Kind == NC_Type);
2668       return Type;
2669     }
2670 
2671     NamedDecl *getNonTypeDecl() const {
2672       assert(Kind == NC_NonType);
2673       return NonTypeDecl;
2674     }
2675 
2676     TemplateName getTemplateName() const {
2677       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2678              Kind == NC_VarTemplate || Kind == NC_Concept ||
2679              Kind == NC_UndeclaredTemplate);
2680       return Template;
2681     }
2682 
2683     TemplateNameKind getTemplateNameKind() const {
2684       switch (Kind) {
2685       case NC_TypeTemplate:
2686         return TNK_Type_template;
2687       case NC_FunctionTemplate:
2688         return TNK_Function_template;
2689       case NC_VarTemplate:
2690         return TNK_Var_template;
2691       case NC_Concept:
2692         return TNK_Concept_template;
2693       case NC_UndeclaredTemplate:
2694         return TNK_Undeclared_template;
2695       default:
2696         llvm_unreachable("unsupported name classification.");
2697       }
2698     }
2699   };
2700 
2701   /// Perform name lookup on the given name, classifying it based on
2702   /// the results of name lookup and the following token.
2703   ///
2704   /// This routine is used by the parser to resolve identifiers and help direct
2705   /// parsing. When the identifier cannot be found, this routine will attempt
2706   /// to correct the typo and classify based on the resulting name.
2707   ///
2708   /// \param S The scope in which we're performing name lookup.
2709   ///
2710   /// \param SS The nested-name-specifier that precedes the name.
2711   ///
2712   /// \param Name The identifier. If typo correction finds an alternative name,
2713   /// this pointer parameter will be updated accordingly.
2714   ///
2715   /// \param NameLoc The location of the identifier.
2716   ///
2717   /// \param NextToken The token following the identifier. Used to help
2718   /// disambiguate the name.
2719   ///
2720   /// \param CCC The correction callback, if typo correction is desired.
2721   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2722                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2723                                   const Token &NextToken,
2724                                   CorrectionCandidateCallback *CCC = nullptr);
2725 
2726   /// Act on the result of classifying a name as an undeclared (ADL-only)
2727   /// non-type declaration.
2728   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2729                                                     SourceLocation NameLoc);
2730   /// Act on the result of classifying a name as an undeclared member of a
2731   /// dependent base class.
2732   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2733                                                    IdentifierInfo *Name,
2734                                                    SourceLocation NameLoc,
2735                                                    bool IsAddressOfOperand);
2736   /// Act on the result of classifying a name as a specific non-type
2737   /// declaration.
2738   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2739                                           NamedDecl *Found,
2740                                           SourceLocation NameLoc,
2741                                           const Token &NextToken);
2742   /// Act on the result of classifying a name as an overload set.
2743   ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2744 
2745   /// Describes the detailed kind of a template name. Used in diagnostics.
2746   enum class TemplateNameKindForDiagnostics {
2747     ClassTemplate,
2748     FunctionTemplate,
2749     VarTemplate,
2750     AliasTemplate,
2751     TemplateTemplateParam,
2752     Concept,
2753     DependentTemplate
2754   };
2755   TemplateNameKindForDiagnostics
2756   getTemplateNameKindForDiagnostics(TemplateName Name);
2757 
2758   /// Determine whether it's plausible that E was intended to be a
2759   /// template-name.
2760   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2761     if (!getLangOpts().CPlusPlus || E.isInvalid())
2762       return false;
2763     Dependent = false;
2764     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2765       return !DRE->hasExplicitTemplateArgs();
2766     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2767       return !ME->hasExplicitTemplateArgs();
2768     Dependent = true;
2769     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2770       return !DSDRE->hasExplicitTemplateArgs();
2771     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2772       return !DSME->hasExplicitTemplateArgs();
2773     // Any additional cases recognized here should also be handled by
2774     // diagnoseExprIntendedAsTemplateName.
2775     return false;
2776   }
2777   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2778                                           SourceLocation Less,
2779                                           SourceLocation Greater);
2780 
2781   void warnOnReservedIdentifier(const NamedDecl *D);
2782 
2783   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2784 
2785   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2786                               MultiTemplateParamsArg TemplateParameterLists);
2787   bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2788                                        QualType &T, SourceLocation Loc,
2789                                        unsigned FailedFoldDiagID);
2790   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2791   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2792   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2793                                     DeclarationName Name, SourceLocation Loc,
2794                                     bool IsTemplateId);
2795   void
2796   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2797                             SourceLocation FallbackLoc,
2798                             SourceLocation ConstQualLoc = SourceLocation(),
2799                             SourceLocation VolatileQualLoc = SourceLocation(),
2800                             SourceLocation RestrictQualLoc = SourceLocation(),
2801                             SourceLocation AtomicQualLoc = SourceLocation(),
2802                             SourceLocation UnalignedQualLoc = SourceLocation());
2803 
2804   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2805   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2806   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2807                                     const LookupResult &R);
2808   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2809   NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2810                                     const LookupResult &R);
2811   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2812                    const LookupResult &R);
2813   void CheckShadow(Scope *S, VarDecl *D);
2814 
2815   /// Warn if 'E', which is an expression that is about to be modified, refers
2816   /// to a shadowing declaration.
2817   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2818 
2819   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2820 
2821 private:
2822   /// Map of current shadowing declarations to shadowed declarations. Warn if
2823   /// it looks like the user is trying to modify the shadowing declaration.
2824   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2825 
2826 public:
2827   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2828   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2829   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2830                                     TypedefNameDecl *NewTD);
2831   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2832   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2833                                     TypeSourceInfo *TInfo,
2834                                     LookupResult &Previous);
2835   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2836                                   LookupResult &Previous, bool &Redeclaration);
2837   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2838                                      TypeSourceInfo *TInfo,
2839                                      LookupResult &Previous,
2840                                      MultiTemplateParamsArg TemplateParamLists,
2841                                      bool &AddToScope,
2842                                      ArrayRef<BindingDecl *> Bindings = None);
2843   NamedDecl *
2844   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2845                                MultiTemplateParamsArg TemplateParamLists);
2846   // Returns true if the variable declaration is a redeclaration
2847   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2848   void CheckVariableDeclarationType(VarDecl *NewVD);
2849   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2850                                      Expr *Init);
2851   void CheckCompleteVariableDeclaration(VarDecl *VD);
2852   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2853   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2854 
2855   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2856                                      TypeSourceInfo *TInfo,
2857                                      LookupResult &Previous,
2858                                      MultiTemplateParamsArg TemplateParamLists,
2859                                      bool &AddToScope);
2860   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2861 
2862   enum class CheckConstexprKind {
2863     /// Diagnose issues that are non-constant or that are extensions.
2864     Diagnose,
2865     /// Identify whether this function satisfies the formal rules for constexpr
2866     /// functions in the current lanugage mode (with no extensions).
2867     CheckValid
2868   };
2869 
2870   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2871                                         CheckConstexprKind Kind);
2872 
2873   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2874   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2875                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2876   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2877                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2878   // Returns true if the function declaration is a redeclaration
2879   bool CheckFunctionDeclaration(Scope *S,
2880                                 FunctionDecl *NewFD, LookupResult &Previous,
2881                                 bool IsMemberSpecialization, bool DeclIsDefn);
2882   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2883   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2884                                       QualType NewT, QualType OldT);
2885   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2886   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2887   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2888                                                    bool IsDefinition);
2889   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2890   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2891   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2892                                           SourceLocation Loc,
2893                                           QualType T);
2894   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2895                               SourceLocation NameLoc, IdentifierInfo *Name,
2896                               QualType T, TypeSourceInfo *TSInfo,
2897                               StorageClass SC);
2898   void ActOnParamDefaultArgument(Decl *param,
2899                                  SourceLocation EqualLoc,
2900                                  Expr *defarg);
2901   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2902                                          SourceLocation ArgLoc);
2903   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2904   ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2905                                          SourceLocation EqualLoc);
2906   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2907                                SourceLocation EqualLoc);
2908 
2909   // Contexts where using non-trivial C union types can be disallowed. This is
2910   // passed to err_non_trivial_c_union_in_invalid_context.
2911   enum NonTrivialCUnionContext {
2912     // Function parameter.
2913     NTCUC_FunctionParam,
2914     // Function return.
2915     NTCUC_FunctionReturn,
2916     // Default-initialized object.
2917     NTCUC_DefaultInitializedObject,
2918     // Variable with automatic storage duration.
2919     NTCUC_AutoVar,
2920     // Initializer expression that might copy from another object.
2921     NTCUC_CopyInit,
2922     // Assignment.
2923     NTCUC_Assignment,
2924     // Compound literal.
2925     NTCUC_CompoundLiteral,
2926     // Block capture.
2927     NTCUC_BlockCapture,
2928     // lvalue-to-rvalue conversion of volatile type.
2929     NTCUC_LValueToRValueVolatile,
2930   };
2931 
2932   /// Emit diagnostics if the initializer or any of its explicit or
2933   /// implicitly-generated subexpressions require copying or
2934   /// default-initializing a type that is or contains a C union type that is
2935   /// non-trivial to copy or default-initialize.
2936   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2937 
2938   // These flags are passed to checkNonTrivialCUnion.
2939   enum NonTrivialCUnionKind {
2940     NTCUK_Init = 0x1,
2941     NTCUK_Destruct = 0x2,
2942     NTCUK_Copy = 0x4,
2943   };
2944 
2945   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2946   /// a non-trivial C union is used in an invalid context.
2947   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2948                              NonTrivialCUnionContext UseContext,
2949                              unsigned NonTrivialKind);
2950 
2951   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2952   void ActOnUninitializedDecl(Decl *dcl);
2953   void ActOnInitializerError(Decl *Dcl);
2954 
2955   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2956   void ActOnCXXForRangeDecl(Decl *D);
2957   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2958                                         IdentifierInfo *Ident,
2959                                         ParsedAttributes &Attrs);
2960   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2961   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2962   void CheckStaticLocalForDllExport(VarDecl *VD);
2963   void FinalizeDeclaration(Decl *D);
2964   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2965                                          ArrayRef<Decl *> Group);
2966   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2967 
2968   /// Should be called on all declarations that might have attached
2969   /// documentation comments.
2970   void ActOnDocumentableDecl(Decl *D);
2971   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2972 
2973   enum class FnBodyKind {
2974     /// C++ [dcl.fct.def.general]p1
2975     /// function-body:
2976     ///   ctor-initializer[opt] compound-statement
2977     ///   function-try-block
2978     Other,
2979     ///   = default ;
2980     Default,
2981     ///   = delete ;
2982     Delete
2983   };
2984 
2985   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2986                                        SourceLocation LocAfterDecls);
2987   void CheckForFunctionRedefinition(
2988       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2989       SkipBodyInfo *SkipBody = nullptr);
2990   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2991                                 MultiTemplateParamsArg TemplateParamLists,
2992                                 SkipBodyInfo *SkipBody = nullptr,
2993                                 FnBodyKind BodyKind = FnBodyKind::Other);
2994   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2995                                 SkipBodyInfo *SkipBody = nullptr,
2996                                 FnBodyKind BodyKind = FnBodyKind::Other);
2997   void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
2998   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2999   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3000   ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3001   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3002   bool isObjCMethodDecl(Decl *D) {
3003     return D && isa<ObjCMethodDecl>(D);
3004   }
3005 
3006   /// Determine whether we can delay parsing the body of a function or
3007   /// function template until it is used, assuming we don't care about emitting
3008   /// code for that function.
3009   ///
3010   /// This will be \c false if we may need the body of the function in the
3011   /// middle of parsing an expression (where it's impractical to switch to
3012   /// parsing a different function), for instance, if it's constexpr in C++11
3013   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3014   bool canDelayFunctionBody(const Declarator &D);
3015 
3016   /// Determine whether we can skip parsing the body of a function
3017   /// definition, assuming we don't care about analyzing its body or emitting
3018   /// code for that function.
3019   ///
3020   /// This will be \c false only if we may need the body of the function in
3021   /// order to parse the rest of the program (for instance, if it is
3022   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3023   bool canSkipFunctionBody(Decl *D);
3024 
3025   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3026   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3027   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3028   Decl *ActOnSkippedFunctionBody(Decl *Decl);
3029   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3030 
3031   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3032   /// attribute for which parsing is delayed.
3033   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3034 
3035   /// Diagnose any unused parameters in the given sequence of
3036   /// ParmVarDecl pointers.
3037   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3038 
3039   /// Diagnose whether the size of parameters or return value of a
3040   /// function or obj-c method definition is pass-by-value and larger than a
3041   /// specified threshold.
3042   void
3043   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3044                                          QualType ReturnTy, NamedDecl *D);
3045 
3046   void DiagnoseInvalidJumps(Stmt *Body);
3047   Decl *ActOnFileScopeAsmDecl(Expr *expr,
3048                               SourceLocation AsmLoc,
3049                               SourceLocation RParenLoc);
3050 
3051   /// Handle a C++11 empty-declaration and attribute-declaration.
3052   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3053                               SourceLocation SemiLoc);
3054 
3055   enum class ModuleDeclKind {
3056     Interface,               ///< 'export module X;'
3057     Implementation,          ///< 'module X;'
3058     PartitionInterface,      ///< 'export module X:Y;'
3059     PartitionImplementation, ///< 'module X:Y;'
3060   };
3061 
3062   /// An enumeration to represent the transition of states in parsing module
3063   /// fragments and imports.  If we are not parsing a C++20 TU, or we find
3064   /// an error in state transition, the state is set to NotACXX20Module.
3065   enum class ModuleImportState {
3066     FirstDecl,       ///< Parsing the first decl in a TU.
3067     GlobalFragment,  ///< after 'module;' but before 'module X;'
3068     ImportAllowed,   ///< after 'module X;' but before any non-import decl.
3069     ImportFinished,  ///< after any non-import decl.
3070     PrivateFragment, ///< after 'module :private;'.
3071     NotACXX20Module  ///< Not a C++20 TU, or an invalid state was found.
3072   };
3073 
3074 private:
3075   /// The parser has begun a translation unit to be compiled as a C++20
3076   /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3077   void HandleStartOfHeaderUnit();
3078 
3079 public:
3080   /// The parser has processed a module-declaration that begins the definition
3081   /// of a module interface or implementation.
3082   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3083                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
3084                                  ModuleIdPath Path, ModuleIdPath Partition,
3085                                  ModuleImportState &ImportState);
3086 
3087   /// The parser has processed a global-module-fragment declaration that begins
3088   /// the definition of the global module fragment of the current module unit.
3089   /// \param ModuleLoc The location of the 'module' keyword.
3090   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3091 
3092   /// The parser has processed a private-module-fragment declaration that begins
3093   /// the definition of the private module fragment of the current module unit.
3094   /// \param ModuleLoc The location of the 'module' keyword.
3095   /// \param PrivateLoc The location of the 'private' keyword.
3096   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3097                                                 SourceLocation PrivateLoc);
3098 
3099   /// The parser has processed a module import declaration.
3100   ///
3101   /// \param StartLoc The location of the first token in the declaration. This
3102   ///        could be the location of an '@', 'export', or 'import'.
3103   /// \param ExportLoc The location of the 'export' keyword, if any.
3104   /// \param ImportLoc The location of the 'import' keyword.
3105   /// \param Path The module toplevel name as an access path.
3106   /// \param IsPartition If the name is for a partition.
3107   DeclResult ActOnModuleImport(SourceLocation StartLoc,
3108                                SourceLocation ExportLoc,
3109                                SourceLocation ImportLoc, ModuleIdPath Path,
3110                                bool IsPartition = false);
3111   DeclResult ActOnModuleImport(SourceLocation StartLoc,
3112                                SourceLocation ExportLoc,
3113                                SourceLocation ImportLoc, Module *M,
3114                                ModuleIdPath Path = {});
3115 
3116   /// The parser has processed a module import translated from a
3117   /// #include or similar preprocessing directive.
3118   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3119   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3120 
3121   /// The parsed has entered a submodule.
3122   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3123   /// The parser has left a submodule.
3124   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3125 
3126   /// Create an implicit import of the given module at the given
3127   /// source location, for error recovery, if possible.
3128   ///
3129   /// This routine is typically used when an entity found by name lookup
3130   /// is actually hidden within a module that we know about but the user
3131   /// has forgotten to import.
3132   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3133                                                   Module *Mod);
3134 
3135   /// Kinds of missing import. Note, the values of these enumerators correspond
3136   /// to %select values in diagnostics.
3137   enum class MissingImportKind {
3138     Declaration,
3139     Definition,
3140     DefaultArgument,
3141     ExplicitSpecialization,
3142     PartialSpecialization
3143   };
3144 
3145   /// Diagnose that the specified declaration needs to be visible but
3146   /// isn't, and suggest a module import that would resolve the problem.
3147   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3148                              MissingImportKind MIK, bool Recover = true);
3149   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3150                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3151                              MissingImportKind MIK, bool Recover);
3152 
3153   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3154                              SourceLocation LBraceLoc);
3155   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3156                               SourceLocation RBraceLoc);
3157 
3158   /// We've found a use of a templated declaration that would trigger an
3159   /// implicit instantiation. Check that any relevant explicit specializations
3160   /// and partial specializations are visible/reachable, and diagnose if not.
3161   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3162   void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3163 
3164   /// Retrieve a suitable printing policy for diagnostics.
3165   PrintingPolicy getPrintingPolicy() const {
3166     return getPrintingPolicy(Context, PP);
3167   }
3168 
3169   /// Retrieve a suitable printing policy for diagnostics.
3170   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3171                                           const Preprocessor &PP);
3172 
3173   /// Scope actions.
3174   void ActOnPopScope(SourceLocation Loc, Scope *S);
3175   void ActOnTranslationUnitScope(Scope *S);
3176 
3177   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3178                                    const ParsedAttributesView &DeclAttrs,
3179                                    RecordDecl *&AnonRecord);
3180   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3181                                    const ParsedAttributesView &DeclAttrs,
3182                                    MultiTemplateParamsArg TemplateParams,
3183                                    bool IsExplicitInstantiation,
3184                                    RecordDecl *&AnonRecord);
3185 
3186   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3187                                     AccessSpecifier AS,
3188                                     RecordDecl *Record,
3189                                     const PrintingPolicy &Policy);
3190 
3191   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3192                                        RecordDecl *Record);
3193 
3194   /// Common ways to introduce type names without a tag for use in diagnostics.
3195   /// Keep in sync with err_tag_reference_non_tag.
3196   enum NonTagKind {
3197     NTK_NonStruct,
3198     NTK_NonClass,
3199     NTK_NonUnion,
3200     NTK_NonEnum,
3201     NTK_Typedef,
3202     NTK_TypeAlias,
3203     NTK_Template,
3204     NTK_TypeAliasTemplate,
3205     NTK_TemplateTemplateArgument,
3206   };
3207 
3208   /// Given a non-tag type declaration, returns an enum useful for indicating
3209   /// what kind of non-tag type this is.
3210   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3211 
3212   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3213                                     TagTypeKind NewTag, bool isDefinition,
3214                                     SourceLocation NewTagLoc,
3215                                     const IdentifierInfo *Name);
3216 
3217   enum TagUseKind {
3218     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
3219     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
3220     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
3221     TUK_Friend       // Friend declaration:  'friend struct foo;'
3222   };
3223 
3224   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3225                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3226                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3227                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3228                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3229                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3230                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3231                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3232                  SkipBodyInfo *SkipBody = nullptr);
3233 
3234   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3235                                 unsigned TagSpec, SourceLocation TagLoc,
3236                                 CXXScopeSpec &SS, IdentifierInfo *Name,
3237                                 SourceLocation NameLoc,
3238                                 const ParsedAttributesView &Attr,
3239                                 MultiTemplateParamsArg TempParamLists);
3240 
3241   TypeResult ActOnDependentTag(Scope *S,
3242                                unsigned TagSpec,
3243                                TagUseKind TUK,
3244                                const CXXScopeSpec &SS,
3245                                IdentifierInfo *Name,
3246                                SourceLocation TagLoc,
3247                                SourceLocation NameLoc);
3248 
3249   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3250                  IdentifierInfo *ClassName,
3251                  SmallVectorImpl<Decl *> &Decls);
3252   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3253                    Declarator &D, Expr *BitfieldWidth);
3254 
3255   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3256                          Declarator &D, Expr *BitfieldWidth,
3257                          InClassInitStyle InitStyle,
3258                          AccessSpecifier AS);
3259   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3260                                    SourceLocation DeclStart, Declarator &D,
3261                                    Expr *BitfieldWidth,
3262                                    InClassInitStyle InitStyle,
3263                                    AccessSpecifier AS,
3264                                    const ParsedAttr &MSPropertyAttr);
3265 
3266   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3267                             TypeSourceInfo *TInfo,
3268                             RecordDecl *Record, SourceLocation Loc,
3269                             bool Mutable, Expr *BitfieldWidth,
3270                             InClassInitStyle InitStyle,
3271                             SourceLocation TSSL,
3272                             AccessSpecifier AS, NamedDecl *PrevDecl,
3273                             Declarator *D = nullptr);
3274 
3275   bool CheckNontrivialField(FieldDecl *FD);
3276   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3277 
3278   enum TrivialABIHandling {
3279     /// The triviality of a method unaffected by "trivial_abi".
3280     TAH_IgnoreTrivialABI,
3281 
3282     /// The triviality of a method affected by "trivial_abi".
3283     TAH_ConsiderTrivialABI
3284   };
3285 
3286   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3287                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3288                               bool Diagnose = false);
3289 
3290   /// For a defaulted function, the kind of defaulted function that it is.
3291   class DefaultedFunctionKind {
3292     CXXSpecialMember SpecialMember : 8;
3293     DefaultedComparisonKind Comparison : 8;
3294 
3295   public:
3296     DefaultedFunctionKind()
3297         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3298     }
3299     DefaultedFunctionKind(CXXSpecialMember CSM)
3300         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3301     DefaultedFunctionKind(DefaultedComparisonKind Comp)
3302         : SpecialMember(CXXInvalid), Comparison(Comp) {}
3303 
3304     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3305     bool isComparison() const {
3306       return Comparison != DefaultedComparisonKind::None;
3307     }
3308 
3309     explicit operator bool() const {
3310       return isSpecialMember() || isComparison();
3311     }
3312 
3313     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3314     DefaultedComparisonKind asComparison() const { return Comparison; }
3315 
3316     /// Get the index of this function kind for use in diagnostics.
3317     unsigned getDiagnosticIndex() const {
3318       static_assert(CXXInvalid > CXXDestructor,
3319                     "invalid should have highest index");
3320       static_assert((unsigned)DefaultedComparisonKind::None == 0,
3321                     "none should be equal to zero");
3322       return SpecialMember + (unsigned)Comparison;
3323     }
3324   };
3325 
3326   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3327 
3328   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3329     return getDefaultedFunctionKind(MD).asSpecialMember();
3330   }
3331   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3332     return getDefaultedFunctionKind(FD).asComparison();
3333   }
3334 
3335   void ActOnLastBitfield(SourceLocation DeclStart,
3336                          SmallVectorImpl<Decl *> &AllIvarDecls);
3337   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3338                   Declarator &D, Expr *BitfieldWidth,
3339                   tok::ObjCKeywordKind visibility);
3340 
3341   // This is used for both record definitions and ObjC interface declarations.
3342   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3343                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
3344                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
3345 
3346   /// ActOnTagStartDefinition - Invoked when we have entered the
3347   /// scope of a tag's definition (e.g., for an enumeration, class,
3348   /// struct, or union).
3349   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3350 
3351   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3352   /// Differently from C++, actually parse the body and reject / error out
3353   /// in case of a structural mismatch.
3354   bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3355 
3356   typedef void *SkippedDefinitionContext;
3357 
3358   /// Invoked when we enter a tag definition that we're skipping.
3359   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3360 
3361   void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3362 
3363   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3364   /// C++ record definition's base-specifiers clause and are starting its
3365   /// member declarations.
3366   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3367                                        SourceLocation FinalLoc,
3368                                        bool IsFinalSpelledSealed,
3369                                        bool IsAbstract,
3370                                        SourceLocation LBraceLoc);
3371 
3372   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3373   /// the definition of a tag (enumeration, class, struct, or union).
3374   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3375                                 SourceRange BraceRange);
3376 
3377   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3378 
3379   void ActOnObjCContainerFinishDefinition();
3380 
3381   /// Invoked when we must temporarily exit the objective-c container
3382   /// scope for parsing/looking-up C constructs.
3383   ///
3384   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3385   void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3386   void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3387 
3388   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3389   /// error parsing the definition of a tag.
3390   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3391 
3392   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3393                                       EnumConstantDecl *LastEnumConst,
3394                                       SourceLocation IdLoc,
3395                                       IdentifierInfo *Id,
3396                                       Expr *val);
3397   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3398   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3399                               QualType EnumUnderlyingTy, bool IsFixed,
3400                               const EnumDecl *Prev);
3401 
3402   /// Determine whether the body of an anonymous enumeration should be skipped.
3403   /// \param II The name of the first enumerator.
3404   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3405                                       SourceLocation IILoc);
3406 
3407   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3408                           SourceLocation IdLoc, IdentifierInfo *Id,
3409                           const ParsedAttributesView &Attrs,
3410                           SourceLocation EqualLoc, Expr *Val);
3411   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3412                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3413                      const ParsedAttributesView &Attr);
3414 
3415   /// Set the current declaration context until it gets popped.
3416   void PushDeclContext(Scope *S, DeclContext *DC);
3417   void PopDeclContext();
3418 
3419   /// EnterDeclaratorContext - Used when we must lookup names in the context
3420   /// of a declarator's nested name specifier.
3421   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3422   void ExitDeclaratorContext(Scope *S);
3423 
3424   /// Enter a template parameter scope, after it's been associated with a particular
3425   /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3426   /// in the correct order.
3427   void EnterTemplatedContext(Scope *S, DeclContext *DC);
3428 
3429   /// Push the parameters of D, which must be a function, into scope.
3430   void ActOnReenterFunctionContext(Scope* S, Decl* D);
3431   void ActOnExitFunctionContext();
3432 
3433   /// If \p AllowLambda is true, treat lambda as function.
3434   DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3435 
3436   /// Returns a pointer to the innermost enclosing function, or nullptr if the
3437   /// current context is not inside a function. If \p AllowLambda is true,
3438   /// this can return the call operator of an enclosing lambda, otherwise
3439   /// lambdas are skipped when looking for an enclosing function.
3440   FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3441 
3442   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3443   /// the method decl for the method being parsed.  If we're currently
3444   /// in a 'block', this returns the containing context.
3445   ObjCMethodDecl *getCurMethodDecl();
3446 
3447   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3448   /// or C function we're in, otherwise return null.  If we're currently
3449   /// in a 'block', this returns the containing context.
3450   NamedDecl *getCurFunctionOrMethodDecl();
3451 
3452   /// Add this decl to the scope shadowed decl chains.
3453   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3454 
3455   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3456   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3457   /// true if 'D' belongs to the given declaration context.
3458   ///
3459   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3460   ///        enclosing namespace set of the context, rather than contained
3461   ///        directly within it.
3462   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3463                      bool AllowInlineNamespace = false);
3464 
3465   /// Finds the scope corresponding to the given decl context, if it
3466   /// happens to be an enclosing scope.  Otherwise return NULL.
3467   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3468 
3469   /// Subroutines of ActOnDeclarator().
3470   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3471                                 TypeSourceInfo *TInfo);
3472   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3473 
3474   /// Describes the kind of merge to perform for availability
3475   /// attributes (including "deprecated", "unavailable", and "availability").
3476   enum AvailabilityMergeKind {
3477     /// Don't merge availability attributes at all.
3478     AMK_None,
3479     /// Merge availability attributes for a redeclaration, which requires
3480     /// an exact match.
3481     AMK_Redeclaration,
3482     /// Merge availability attributes for an override, which requires
3483     /// an exact match or a weakening of constraints.
3484     AMK_Override,
3485     /// Merge availability attributes for an implementation of
3486     /// a protocol requirement.
3487     AMK_ProtocolImplementation,
3488     /// Merge availability attributes for an implementation of
3489     /// an optional protocol requirement.
3490     AMK_OptionalProtocolImplementation
3491   };
3492 
3493   /// Describes the kind of priority given to an availability attribute.
3494   ///
3495   /// The sum of priorities deteremines the final priority of the attribute.
3496   /// The final priority determines how the attribute will be merged.
3497   /// An attribute with a lower priority will always remove higher priority
3498   /// attributes for the specified platform when it is being applied. An
3499   /// attribute with a higher priority will not be applied if the declaration
3500   /// already has an availability attribute with a lower priority for the
3501   /// specified platform. The final prirority values are not expected to match
3502   /// the values in this enumeration, but instead should be treated as a plain
3503   /// integer value. This enumeration just names the priority weights that are
3504   /// used to calculate that final vaue.
3505   enum AvailabilityPriority : int {
3506     /// The availability attribute was specified explicitly next to the
3507     /// declaration.
3508     AP_Explicit = 0,
3509 
3510     /// The availability attribute was applied using '#pragma clang attribute'.
3511     AP_PragmaClangAttribute = 1,
3512 
3513     /// The availability attribute for a specific platform was inferred from
3514     /// an availability attribute for another platform.
3515     AP_InferredFromOtherPlatform = 2
3516   };
3517 
3518   /// Attribute merging methods. Return true if a new attribute was added.
3519   AvailabilityAttr *
3520   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3521                         IdentifierInfo *Platform, bool Implicit,
3522                         VersionTuple Introduced, VersionTuple Deprecated,
3523                         VersionTuple Obsoleted, bool IsUnavailable,
3524                         StringRef Message, bool IsStrict, StringRef Replacement,
3525                         AvailabilityMergeKind AMK, int Priority);
3526   TypeVisibilityAttr *
3527   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3528                           TypeVisibilityAttr::VisibilityType Vis);
3529   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3530                                       VisibilityAttr::VisibilityType Vis);
3531   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3532                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3533   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3534   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3535   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3536                                             const AttributeCommonInfo &CI,
3537                                             bool BestCase,
3538                                             MSInheritanceModel Model);
3539   ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3540                             StringRef NewUserDiagnostic);
3541   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3542                               IdentifierInfo *Format, int FormatIdx,
3543                               int FirstArg);
3544   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3545                                 StringRef Name);
3546   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3547                                 StringRef Name);
3548   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3549                                           const AttributeCommonInfo &CI,
3550                                           const IdentifierInfo *Ident);
3551   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3552   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3553                                     StringRef Name);
3554   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3555                                           const AttributeCommonInfo &CI);
3556   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3557   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3558                                                 const InternalLinkageAttr &AL);
3559   WebAssemblyImportNameAttr *mergeImportNameAttr(
3560       Decl *D, const WebAssemblyImportNameAttr &AL);
3561   WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3562       Decl *D, const WebAssemblyImportModuleAttr &AL);
3563   EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3564   EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3565                                               const EnforceTCBLeafAttr &AL);
3566   BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3567   HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3568                                               const AttributeCommonInfo &AL,
3569                                               int X, int Y, int Z);
3570   HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3571                                       HLSLShaderAttr::ShaderType ShaderType);
3572 
3573   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3574                            AvailabilityMergeKind AMK = AMK_Redeclaration);
3575   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3576                             LookupResult &OldDecls);
3577   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3578                          bool MergeTypeWithOld, bool NewDeclIsDefn);
3579   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3580                                     Scope *S, bool MergeTypeWithOld);
3581   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3582   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3583   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3584   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3585   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3586   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3587   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3588 
3589   // AssignmentAction - This is used by all the assignment diagnostic functions
3590   // to represent what is actually causing the operation
3591   enum AssignmentAction {
3592     AA_Assigning,
3593     AA_Passing,
3594     AA_Returning,
3595     AA_Converting,
3596     AA_Initializing,
3597     AA_Sending,
3598     AA_Casting,
3599     AA_Passing_CFAudited
3600   };
3601 
3602   /// C++ Overloading.
3603   enum OverloadKind {
3604     /// This is a legitimate overload: the existing declarations are
3605     /// functions or function templates with different signatures.
3606     Ovl_Overload,
3607 
3608     /// This is not an overload because the signature exactly matches
3609     /// an existing declaration.
3610     Ovl_Match,
3611 
3612     /// This is not an overload because the lookup results contain a
3613     /// non-function.
3614     Ovl_NonFunction
3615   };
3616   OverloadKind CheckOverload(Scope *S,
3617                              FunctionDecl *New,
3618                              const LookupResult &OldDecls,
3619                              NamedDecl *&OldDecl,
3620                              bool IsForUsingDecl);
3621   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3622                   bool ConsiderCudaAttrs = true,
3623                   bool ConsiderRequiresClauses = true);
3624 
3625   enum class AllowedExplicit {
3626     /// Allow no explicit functions to be used.
3627     None,
3628     /// Allow explicit conversion functions but not explicit constructors.
3629     Conversions,
3630     /// Allow both explicit conversion functions and explicit constructors.
3631     All
3632   };
3633 
3634   ImplicitConversionSequence
3635   TryImplicitConversion(Expr *From, QualType ToType,
3636                         bool SuppressUserConversions,
3637                         AllowedExplicit AllowExplicit,
3638                         bool InOverloadResolution,
3639                         bool CStyle,
3640                         bool AllowObjCWritebackConversion);
3641 
3642   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3643   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3644   bool IsComplexPromotion(QualType FromType, QualType ToType);
3645   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3646                            bool InOverloadResolution,
3647                            QualType& ConvertedType, bool &IncompatibleObjC);
3648   bool isObjCPointerConversion(QualType FromType, QualType ToType,
3649                                QualType& ConvertedType, bool &IncompatibleObjC);
3650   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3651                                  QualType &ConvertedType);
3652   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3653                                 QualType& ConvertedType);
3654   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3655                                   const FunctionProtoType *NewType,
3656                                   unsigned *ArgPos = nullptr,
3657                                   bool Reversed = false);
3658   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3659                                   QualType FromType, QualType ToType);
3660 
3661   void maybeExtendBlockObject(ExprResult &E);
3662   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3663   bool CheckPointerConversion(Expr *From, QualType ToType,
3664                               CastKind &Kind,
3665                               CXXCastPath& BasePath,
3666                               bool IgnoreBaseAccess,
3667                               bool Diagnose = true);
3668   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3669                                  bool InOverloadResolution,
3670                                  QualType &ConvertedType);
3671   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3672                                     CastKind &Kind,
3673                                     CXXCastPath &BasePath,
3674                                     bool IgnoreBaseAccess);
3675   bool IsQualificationConversion(QualType FromType, QualType ToType,
3676                                  bool CStyle, bool &ObjCLifetimeConversion);
3677   bool IsFunctionConversion(QualType FromType, QualType ToType,
3678                             QualType &ResultTy);
3679   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3680   bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
3681 
3682   bool CanPerformAggregateInitializationForOverloadResolution(
3683       const InitializedEntity &Entity, InitListExpr *From);
3684 
3685   bool IsStringInit(Expr *Init, const ArrayType *AT);
3686 
3687   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3688                                     ExprResult Init);
3689   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3690                                        SourceLocation EqualLoc,
3691                                        ExprResult Init,
3692                                        bool TopLevelOfInitList = false,
3693                                        bool AllowExplicit = false);
3694   ExprResult PerformObjectArgumentInitialization(Expr *From,
3695                                                  NestedNameSpecifier *Qualifier,
3696                                                  NamedDecl *FoundDecl,
3697                                                  CXXMethodDecl *Method);
3698 
3699   /// Check that the lifetime of the initializer (and its subobjects) is
3700   /// sufficient for initializing the entity, and perform lifetime extension
3701   /// (when permitted) if not.
3702   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3703 
3704   ExprResult PerformContextuallyConvertToBool(Expr *From);
3705   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3706 
3707   /// Contexts in which a converted constant expression is required.
3708   enum CCEKind {
3709     CCEK_CaseValue,    ///< Expression in a case label.
3710     CCEK_Enumerator,   ///< Enumerator value with fixed underlying type.
3711     CCEK_TemplateArg,  ///< Value of a non-type template parameter.
3712     CCEK_ArrayBound,   ///< Array bound in array declarator or new-expression.
3713     CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3714     CCEK_Noexcept      ///< Condition in a noexcept(bool) specifier.
3715   };
3716   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3717                                               llvm::APSInt &Value, CCEKind CCE);
3718   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3719                                               APValue &Value, CCEKind CCE,
3720                                               NamedDecl *Dest = nullptr);
3721 
3722   /// Abstract base class used to perform a contextual implicit
3723   /// conversion from an expression to any type passing a filter.
3724   class ContextualImplicitConverter {
3725   public:
3726     bool Suppress;
3727     bool SuppressConversion;
3728 
3729     ContextualImplicitConverter(bool Suppress = false,
3730                                 bool SuppressConversion = false)
3731         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3732 
3733     /// Determine whether the specified type is a valid destination type
3734     /// for this conversion.
3735     virtual bool match(QualType T) = 0;
3736 
3737     /// Emits a diagnostic complaining that the expression does not have
3738     /// integral or enumeration type.
3739     virtual SemaDiagnosticBuilder
3740     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3741 
3742     /// Emits a diagnostic when the expression has incomplete class type.
3743     virtual SemaDiagnosticBuilder
3744     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3745 
3746     /// Emits a diagnostic when the only matching conversion function
3747     /// is explicit.
3748     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3749         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3750 
3751     /// Emits a note for the explicit conversion function.
3752     virtual SemaDiagnosticBuilder
3753     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3754 
3755     /// Emits a diagnostic when there are multiple possible conversion
3756     /// functions.
3757     virtual SemaDiagnosticBuilder
3758     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3759 
3760     /// Emits a note for one of the candidate conversions.
3761     virtual SemaDiagnosticBuilder
3762     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3763 
3764     /// Emits a diagnostic when we picked a conversion function
3765     /// (for cases when we are not allowed to pick a conversion function).
3766     virtual SemaDiagnosticBuilder diagnoseConversion(
3767         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3768 
3769     virtual ~ContextualImplicitConverter() {}
3770   };
3771 
3772   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3773     bool AllowScopedEnumerations;
3774 
3775   public:
3776     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3777                         bool Suppress, bool SuppressConversion)
3778         : ContextualImplicitConverter(Suppress, SuppressConversion),
3779           AllowScopedEnumerations(AllowScopedEnumerations) {}
3780 
3781     /// Match an integral or (possibly scoped) enumeration type.
3782     bool match(QualType T) override;
3783 
3784     SemaDiagnosticBuilder
3785     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3786       return diagnoseNotInt(S, Loc, T);
3787     }
3788 
3789     /// Emits a diagnostic complaining that the expression does not have
3790     /// integral or enumeration type.
3791     virtual SemaDiagnosticBuilder
3792     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3793   };
3794 
3795   /// Perform a contextual implicit conversion.
3796   ExprResult PerformContextualImplicitConversion(
3797       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3798 
3799 
3800   enum ObjCSubscriptKind {
3801     OS_Array,
3802     OS_Dictionary,
3803     OS_Error
3804   };
3805   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3806 
3807   // Note that LK_String is intentionally after the other literals, as
3808   // this is used for diagnostics logic.
3809   enum ObjCLiteralKind {
3810     LK_Array,
3811     LK_Dictionary,
3812     LK_Numeric,
3813     LK_Boxed,
3814     LK_String,
3815     LK_Block,
3816     LK_None
3817   };
3818   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3819 
3820   ExprResult PerformObjectMemberConversion(Expr *From,
3821                                            NestedNameSpecifier *Qualifier,
3822                                            NamedDecl *FoundDecl,
3823                                            NamedDecl *Member);
3824 
3825   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3826   // TODO: make this is a typesafe union.
3827   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3828   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3829 
3830   using ADLCallKind = CallExpr::ADLCallKind;
3831 
3832   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3833                             ArrayRef<Expr *> Args,
3834                             OverloadCandidateSet &CandidateSet,
3835                             bool SuppressUserConversions = false,
3836                             bool PartialOverloading = false,
3837                             bool AllowExplicit = true,
3838                             bool AllowExplicitConversion = false,
3839                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3840                             ConversionSequenceList EarlyConversions = None,
3841                             OverloadCandidateParamOrder PO = {});
3842   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3843                       ArrayRef<Expr *> Args,
3844                       OverloadCandidateSet &CandidateSet,
3845                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3846                       bool SuppressUserConversions = false,
3847                       bool PartialOverloading = false,
3848                       bool FirstArgumentIsBase = false);
3849   void AddMethodCandidate(DeclAccessPair FoundDecl,
3850                           QualType ObjectType,
3851                           Expr::Classification ObjectClassification,
3852                           ArrayRef<Expr *> Args,
3853                           OverloadCandidateSet& CandidateSet,
3854                           bool SuppressUserConversion = false,
3855                           OverloadCandidateParamOrder PO = {});
3856   void AddMethodCandidate(CXXMethodDecl *Method,
3857                           DeclAccessPair FoundDecl,
3858                           CXXRecordDecl *ActingContext, QualType ObjectType,
3859                           Expr::Classification ObjectClassification,
3860                           ArrayRef<Expr *> Args,
3861                           OverloadCandidateSet& CandidateSet,
3862                           bool SuppressUserConversions = false,
3863                           bool PartialOverloading = false,
3864                           ConversionSequenceList EarlyConversions = None,
3865                           OverloadCandidateParamOrder PO = {});
3866   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3867                                   DeclAccessPair FoundDecl,
3868                                   CXXRecordDecl *ActingContext,
3869                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3870                                   QualType ObjectType,
3871                                   Expr::Classification ObjectClassification,
3872                                   ArrayRef<Expr *> Args,
3873                                   OverloadCandidateSet& CandidateSet,
3874                                   bool SuppressUserConversions = false,
3875                                   bool PartialOverloading = false,
3876                                   OverloadCandidateParamOrder PO = {});
3877   void AddTemplateOverloadCandidate(
3878       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3879       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3880       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3881       bool PartialOverloading = false, bool AllowExplicit = true,
3882       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3883       OverloadCandidateParamOrder PO = {});
3884   bool CheckNonDependentConversions(
3885       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3886       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3887       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3888       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3889       Expr::Classification ObjectClassification = {},
3890       OverloadCandidateParamOrder PO = {});
3891   void AddConversionCandidate(
3892       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3893       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3894       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3895       bool AllowExplicit, bool AllowResultConversion = true);
3896   void AddTemplateConversionCandidate(
3897       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3898       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3899       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3900       bool AllowExplicit, bool AllowResultConversion = true);
3901   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3902                              DeclAccessPair FoundDecl,
3903                              CXXRecordDecl *ActingContext,
3904                              const FunctionProtoType *Proto,
3905                              Expr *Object, ArrayRef<Expr *> Args,
3906                              OverloadCandidateSet& CandidateSet);
3907   void AddNonMemberOperatorCandidates(
3908       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3909       OverloadCandidateSet &CandidateSet,
3910       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3911   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3912                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3913                                    OverloadCandidateSet &CandidateSet,
3914                                    OverloadCandidateParamOrder PO = {});
3915   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3916                            OverloadCandidateSet& CandidateSet,
3917                            bool IsAssignmentOperator = false,
3918                            unsigned NumContextualBoolArguments = 0);
3919   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3920                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3921                                     OverloadCandidateSet& CandidateSet);
3922   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3923                                             SourceLocation Loc,
3924                                             ArrayRef<Expr *> Args,
3925                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3926                                             OverloadCandidateSet& CandidateSet,
3927                                             bool PartialOverloading = false);
3928 
3929   // Emit as a 'note' the specific overload candidate
3930   void NoteOverloadCandidate(
3931       NamedDecl *Found, FunctionDecl *Fn,
3932       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3933       QualType DestType = QualType(), bool TakingAddress = false);
3934 
3935   // Emit as a series of 'note's all template and non-templates identified by
3936   // the expression Expr
3937   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3938                                  bool TakingAddress = false);
3939 
3940   /// Check the enable_if expressions on the given function. Returns the first
3941   /// failing attribute, or NULL if they were all successful.
3942   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3943                               ArrayRef<Expr *> Args,
3944                               bool MissingImplicitThis = false);
3945 
3946   /// Find the failed Boolean condition within a given Boolean
3947   /// constant expression, and describe it with a string.
3948   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3949 
3950   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3951   /// non-ArgDependent DiagnoseIfAttrs.
3952   ///
3953   /// Argument-dependent diagnose_if attributes should be checked each time a
3954   /// function is used as a direct callee of a function call.
3955   ///
3956   /// Returns true if any errors were emitted.
3957   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3958                                            const Expr *ThisArg,
3959                                            ArrayRef<const Expr *> Args,
3960                                            SourceLocation Loc);
3961 
3962   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3963   /// ArgDependent DiagnoseIfAttrs.
3964   ///
3965   /// Argument-independent diagnose_if attributes should be checked on every use
3966   /// of a function.
3967   ///
3968   /// Returns true if any errors were emitted.
3969   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3970                                              SourceLocation Loc);
3971 
3972   /// Returns whether the given function's address can be taken or not,
3973   /// optionally emitting a diagnostic if the address can't be taken.
3974   ///
3975   /// Returns false if taking the address of the function is illegal.
3976   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3977                                          bool Complain = false,
3978                                          SourceLocation Loc = SourceLocation());
3979 
3980   // [PossiblyAFunctionType]  -->   [Return]
3981   // NonFunctionType --> NonFunctionType
3982   // R (A) --> R(A)
3983   // R (*)(A) --> R (A)
3984   // R (&)(A) --> R (A)
3985   // R (S::*)(A) --> R (A)
3986   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3987 
3988   FunctionDecl *
3989   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3990                                      QualType TargetType,
3991                                      bool Complain,
3992                                      DeclAccessPair &Found,
3993                                      bool *pHadMultipleCandidates = nullptr);
3994 
3995   FunctionDecl *
3996   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3997 
3998   bool resolveAndFixAddressOfSingleOverloadCandidate(
3999       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
4000 
4001   FunctionDecl *
4002   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
4003                                               bool Complain = false,
4004                                               DeclAccessPair *Found = nullptr);
4005 
4006   bool ResolveAndFixSingleFunctionTemplateSpecialization(
4007                       ExprResult &SrcExpr,
4008                       bool DoFunctionPointerConverion = false,
4009                       bool Complain = false,
4010                       SourceRange OpRangeForComplaining = SourceRange(),
4011                       QualType DestTypeForComplaining = QualType(),
4012                       unsigned DiagIDForComplaining = 0);
4013 
4014 
4015   Expr *FixOverloadedFunctionReference(Expr *E,
4016                                        DeclAccessPair FoundDecl,
4017                                        FunctionDecl *Fn);
4018   ExprResult FixOverloadedFunctionReference(ExprResult,
4019                                             DeclAccessPair FoundDecl,
4020                                             FunctionDecl *Fn);
4021 
4022   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
4023                                    ArrayRef<Expr *> Args,
4024                                    OverloadCandidateSet &CandidateSet,
4025                                    bool PartialOverloading = false);
4026   void AddOverloadedCallCandidates(
4027       LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
4028       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
4029 
4030   // An enum used to represent the different possible results of building a
4031   // range-based for loop.
4032   enum ForRangeStatus {
4033     FRS_Success,
4034     FRS_NoViableFunction,
4035     FRS_DiagnosticIssued
4036   };
4037 
4038   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
4039                                            SourceLocation RangeLoc,
4040                                            const DeclarationNameInfo &NameInfo,
4041                                            LookupResult &MemberLookup,
4042                                            OverloadCandidateSet *CandidateSet,
4043                                            Expr *Range, ExprResult *CallExpr);
4044 
4045   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
4046                                      UnresolvedLookupExpr *ULE,
4047                                      SourceLocation LParenLoc,
4048                                      MultiExprArg Args,
4049                                      SourceLocation RParenLoc,
4050                                      Expr *ExecConfig,
4051                                      bool AllowTypoCorrection=true,
4052                                      bool CalleesAddressIsTaken=false);
4053 
4054   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
4055                               MultiExprArg Args, SourceLocation RParenLoc,
4056                               OverloadCandidateSet *CandidateSet,
4057                               ExprResult *Result);
4058 
4059   ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
4060                                         NestedNameSpecifierLoc NNSLoc,
4061                                         DeclarationNameInfo DNI,
4062                                         const UnresolvedSetImpl &Fns,
4063                                         bool PerformADL = true);
4064 
4065   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
4066                                      UnaryOperatorKind Opc,
4067                                      const UnresolvedSetImpl &Fns,
4068                                      Expr *input, bool RequiresADL = true);
4069 
4070   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4071                              OverloadedOperatorKind Op,
4072                              const UnresolvedSetImpl &Fns,
4073                              ArrayRef<Expr *> Args, bool RequiresADL = true);
4074   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
4075                                    BinaryOperatorKind Opc,
4076                                    const UnresolvedSetImpl &Fns,
4077                                    Expr *LHS, Expr *RHS,
4078                                    bool RequiresADL = true,
4079                                    bool AllowRewrittenCandidates = true,
4080                                    FunctionDecl *DefaultedFn = nullptr);
4081   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
4082                                                 const UnresolvedSetImpl &Fns,
4083                                                 Expr *LHS, Expr *RHS,
4084                                                 FunctionDecl *DefaultedFn);
4085 
4086   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4087                                                 SourceLocation RLoc, Expr *Base,
4088                                                 MultiExprArg Args);
4089 
4090   ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
4091                                        SourceLocation LParenLoc,
4092                                        MultiExprArg Args,
4093                                        SourceLocation RParenLoc,
4094                                        Expr *ExecConfig = nullptr,
4095                                        bool IsExecConfig = false,
4096                                        bool AllowRecovery = false);
4097   ExprResult
4098   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4099                                MultiExprArg Args,
4100                                SourceLocation RParenLoc);
4101 
4102   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
4103                                       SourceLocation OpLoc,
4104                                       bool *NoArrowOperatorFound = nullptr);
4105 
4106   /// CheckCallReturnType - Checks that a call expression's return type is
4107   /// complete. Returns true on failure. The location passed in is the location
4108   /// that best represents the call.
4109   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4110                            CallExpr *CE, FunctionDecl *FD);
4111 
4112   /// Helpers for dealing with blocks and functions.
4113   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
4114                                 bool CheckParameterNames);
4115   void CheckCXXDefaultArguments(FunctionDecl *FD);
4116   void CheckExtraCXXDefaultArguments(Declarator &D);
4117   Scope *getNonFieldDeclScope(Scope *S);
4118 
4119   /// \name Name lookup
4120   ///
4121   /// These routines provide name lookup that is used during semantic
4122   /// analysis to resolve the various kinds of names (identifiers,
4123   /// overloaded operator names, constructor names, etc.) into zero or
4124   /// more declarations within a particular scope. The major entry
4125   /// points are LookupName, which performs unqualified name lookup,
4126   /// and LookupQualifiedName, which performs qualified name lookup.
4127   ///
4128   /// All name lookup is performed based on some specific criteria,
4129   /// which specify what names will be visible to name lookup and how
4130   /// far name lookup should work. These criteria are important both
4131   /// for capturing language semantics (certain lookups will ignore
4132   /// certain names, for example) and for performance, since name
4133   /// lookup is often a bottleneck in the compilation of C++. Name
4134   /// lookup criteria is specified via the LookupCriteria enumeration.
4135   ///
4136   /// The results of name lookup can vary based on the kind of name
4137   /// lookup performed, the current language, and the translation
4138   /// unit. In C, for example, name lookup will either return nothing
4139   /// (no entity found) or a single declaration. In C++, name lookup
4140   /// can additionally refer to a set of overloaded functions or
4141   /// result in an ambiguity. All of the possible results of name
4142   /// lookup are captured by the LookupResult class, which provides
4143   /// the ability to distinguish among them.
4144   //@{
4145 
4146   /// Describes the kind of name lookup to perform.
4147   enum LookupNameKind {
4148     /// Ordinary name lookup, which finds ordinary names (functions,
4149     /// variables, typedefs, etc.) in C and most kinds of names
4150     /// (functions, variables, members, types, etc.) in C++.
4151     LookupOrdinaryName = 0,
4152     /// Tag name lookup, which finds the names of enums, classes,
4153     /// structs, and unions.
4154     LookupTagName,
4155     /// Label name lookup.
4156     LookupLabel,
4157     /// Member name lookup, which finds the names of
4158     /// class/struct/union members.
4159     LookupMemberName,
4160     /// Look up of an operator name (e.g., operator+) for use with
4161     /// operator overloading. This lookup is similar to ordinary name
4162     /// lookup, but will ignore any declarations that are class members.
4163     LookupOperatorName,
4164     /// Look up a name following ~ in a destructor name. This is an ordinary
4165     /// lookup, but prefers tags to typedefs.
4166     LookupDestructorName,
4167     /// Look up of a name that precedes the '::' scope resolution
4168     /// operator in C++. This lookup completely ignores operator, object,
4169     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4170     LookupNestedNameSpecifierName,
4171     /// Look up a namespace name within a C++ using directive or
4172     /// namespace alias definition, ignoring non-namespace names (C++
4173     /// [basic.lookup.udir]p1).
4174     LookupNamespaceName,
4175     /// Look up all declarations in a scope with the given name,
4176     /// including resolved using declarations.  This is appropriate
4177     /// for checking redeclarations for a using declaration.
4178     LookupUsingDeclName,
4179     /// Look up an ordinary name that is going to be redeclared as a
4180     /// name with linkage. This lookup ignores any declarations that
4181     /// are outside of the current scope unless they have linkage. See
4182     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4183     LookupRedeclarationWithLinkage,
4184     /// Look up a friend of a local class. This lookup does not look
4185     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4186     LookupLocalFriendName,
4187     /// Look up the name of an Objective-C protocol.
4188     LookupObjCProtocolName,
4189     /// Look up implicit 'self' parameter of an objective-c method.
4190     LookupObjCImplicitSelfParam,
4191     /// Look up the name of an OpenMP user-defined reduction operation.
4192     LookupOMPReductionName,
4193     /// Look up the name of an OpenMP user-defined mapper.
4194     LookupOMPMapperName,
4195     /// Look up any declaration with any name.
4196     LookupAnyName
4197   };
4198 
4199   /// Specifies whether (or how) name lookup is being performed for a
4200   /// redeclaration (vs. a reference).
4201   enum RedeclarationKind {
4202     /// The lookup is a reference to this name that is not for the
4203     /// purpose of redeclaring the name.
4204     NotForRedeclaration = 0,
4205     /// The lookup results will be used for redeclaration of a name,
4206     /// if an entity by that name already exists and is visible.
4207     ForVisibleRedeclaration,
4208     /// The lookup results will be used for redeclaration of a name
4209     /// with external linkage; non-visible lookup results with external linkage
4210     /// may also be found.
4211     ForExternalRedeclaration
4212   };
4213 
4214   RedeclarationKind forRedeclarationInCurContext() {
4215     // A declaration with an owning module for linkage can never link against
4216     // anything that is not visible. We don't need to check linkage here; if
4217     // the context has internal linkage, redeclaration lookup won't find things
4218     // from other TUs, and we can't safely compute linkage yet in general.
4219     if (cast<Decl>(CurContext)
4220             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4221       return ForVisibleRedeclaration;
4222     return ForExternalRedeclaration;
4223   }
4224 
4225   /// The possible outcomes of name lookup for a literal operator.
4226   enum LiteralOperatorLookupResult {
4227     /// The lookup resulted in an error.
4228     LOLR_Error,
4229     /// The lookup found no match but no diagnostic was issued.
4230     LOLR_ErrorNoDiagnostic,
4231     /// The lookup found a single 'cooked' literal operator, which
4232     /// expects a normal literal to be built and passed to it.
4233     LOLR_Cooked,
4234     /// The lookup found a single 'raw' literal operator, which expects
4235     /// a string literal containing the spelling of the literal token.
4236     LOLR_Raw,
4237     /// The lookup found an overload set of literal operator templates,
4238     /// which expect the characters of the spelling of the literal token to be
4239     /// passed as a non-type template argument pack.
4240     LOLR_Template,
4241     /// The lookup found an overload set of literal operator templates,
4242     /// which expect the character type and characters of the spelling of the
4243     /// string literal token to be passed as template arguments.
4244     LOLR_StringTemplatePack,
4245   };
4246 
4247   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4248                                                   CXXSpecialMember SM,
4249                                                   bool ConstArg,
4250                                                   bool VolatileArg,
4251                                                   bool RValueThis,
4252                                                   bool ConstThis,
4253                                                   bool VolatileThis);
4254 
4255   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4256   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4257       TypoRecoveryCallback;
4258 
4259 private:
4260   bool CppLookupName(LookupResult &R, Scope *S);
4261 
4262   struct TypoExprState {
4263     std::unique_ptr<TypoCorrectionConsumer> Consumer;
4264     TypoDiagnosticGenerator DiagHandler;
4265     TypoRecoveryCallback RecoveryHandler;
4266     TypoExprState();
4267     TypoExprState(TypoExprState &&other) noexcept;
4268     TypoExprState &operator=(TypoExprState &&other) noexcept;
4269   };
4270 
4271   /// The set of unhandled TypoExprs and their associated state.
4272   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4273 
4274   /// Creates a new TypoExpr AST node.
4275   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4276                               TypoDiagnosticGenerator TDG,
4277                               TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4278 
4279   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4280   //
4281   // The boolean value will be true to indicate that the namespace was loaded
4282   // from an AST/PCH file, or false otherwise.
4283   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4284 
4285   /// Whether we have already loaded known namespaces from an extenal
4286   /// source.
4287   bool LoadedExternalKnownNamespaces;
4288 
4289   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4290   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4291   /// should be skipped entirely.
4292   std::unique_ptr<TypoCorrectionConsumer>
4293   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4294                              Sema::LookupNameKind LookupKind, Scope *S,
4295                              CXXScopeSpec *SS,
4296                              CorrectionCandidateCallback &CCC,
4297                              DeclContext *MemberContext, bool EnteringContext,
4298                              const ObjCObjectPointerType *OPT,
4299                              bool ErrorRecovery);
4300 
4301 public:
4302   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4303 
4304   /// Clears the state of the given TypoExpr.
4305   void clearDelayedTypo(TypoExpr *TE);
4306 
4307   /// Look up a name, looking for a single declaration.  Return
4308   /// null if the results were absent, ambiguous, or overloaded.
4309   ///
4310   /// It is preferable to use the elaborated form and explicitly handle
4311   /// ambiguity and overloaded.
4312   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4313                               SourceLocation Loc,
4314                               LookupNameKind NameKind,
4315                               RedeclarationKind Redecl
4316                                 = NotForRedeclaration);
4317   bool LookupBuiltin(LookupResult &R);
4318   void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4319   bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4320                   bool ForceNoCPlusPlus = false);
4321   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4322                            bool InUnqualifiedLookup = false);
4323   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4324                            CXXScopeSpec &SS);
4325   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4326                         bool AllowBuiltinCreation = false,
4327                         bool EnteringContext = false);
4328   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4329                                    RedeclarationKind Redecl
4330                                      = NotForRedeclaration);
4331   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4332 
4333   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4334                                     UnresolvedSetImpl &Functions);
4335 
4336   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4337                                  SourceLocation GnuLabelLoc = SourceLocation());
4338 
4339   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4340   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4341   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4342                                                unsigned Quals);
4343   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4344                                          bool RValueThis, unsigned ThisQuals);
4345   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4346                                               unsigned Quals);
4347   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4348                                         bool RValueThis, unsigned ThisQuals);
4349   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4350 
4351   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4352                               bool IsUDSuffix);
4353   LiteralOperatorLookupResult
4354   LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4355                         bool AllowRaw, bool AllowTemplate,
4356                         bool AllowStringTemplate, bool DiagnoseMissing,
4357                         StringLiteral *StringLit = nullptr);
4358   bool isKnownName(StringRef name);
4359 
4360   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4361   enum class FunctionEmissionStatus {
4362     Emitted,
4363     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
4364     OMPDiscarded,      // Discarded due to OpenMP hostness
4365     TemplateDiscarded, // Discarded due to uninstantiated templates
4366     Unknown,
4367   };
4368   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4369                                            bool Final = false);
4370 
4371   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4372   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4373 
4374   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4375                                ArrayRef<Expr *> Args, ADLResult &Functions);
4376 
4377   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4378                           VisibleDeclConsumer &Consumer,
4379                           bool IncludeGlobalScope = true,
4380                           bool LoadExternal = true);
4381   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4382                           VisibleDeclConsumer &Consumer,
4383                           bool IncludeGlobalScope = true,
4384                           bool IncludeDependentBases = false,
4385                           bool LoadExternal = true);
4386 
4387   enum CorrectTypoKind {
4388     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
4389     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4390   };
4391 
4392   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4393                              Sema::LookupNameKind LookupKind,
4394                              Scope *S, CXXScopeSpec *SS,
4395                              CorrectionCandidateCallback &CCC,
4396                              CorrectTypoKind Mode,
4397                              DeclContext *MemberContext = nullptr,
4398                              bool EnteringContext = false,
4399                              const ObjCObjectPointerType *OPT = nullptr,
4400                              bool RecordFailure = true);
4401 
4402   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4403                                Sema::LookupNameKind LookupKind, Scope *S,
4404                                CXXScopeSpec *SS,
4405                                CorrectionCandidateCallback &CCC,
4406                                TypoDiagnosticGenerator TDG,
4407                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4408                                DeclContext *MemberContext = nullptr,
4409                                bool EnteringContext = false,
4410                                const ObjCObjectPointerType *OPT = nullptr);
4411 
4412   /// Process any TypoExprs in the given Expr and its children,
4413   /// generating diagnostics as appropriate and returning a new Expr if there
4414   /// were typos that were all successfully corrected and ExprError if one or
4415   /// more typos could not be corrected.
4416   ///
4417   /// \param E The Expr to check for TypoExprs.
4418   ///
4419   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4420   /// initializer.
4421   ///
4422   /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4423   /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4424   ///
4425   /// \param Filter A function applied to a newly rebuilt Expr to determine if
4426   /// it is an acceptable/usable result from a single combination of typo
4427   /// corrections. As long as the filter returns ExprError, different
4428   /// combinations of corrections will be tried until all are exhausted.
4429   ExprResult CorrectDelayedTyposInExpr(
4430       Expr *E, VarDecl *InitDecl = nullptr,
4431       bool RecoverUncorrectedTypos = false,
4432       llvm::function_ref<ExprResult(Expr *)> Filter =
4433           [](Expr *E) -> ExprResult { return E; });
4434 
4435   ExprResult CorrectDelayedTyposInExpr(
4436       ExprResult ER, VarDecl *InitDecl = nullptr,
4437       bool RecoverUncorrectedTypos = false,
4438       llvm::function_ref<ExprResult(Expr *)> Filter =
4439           [](Expr *E) -> ExprResult { return E; }) {
4440     return ER.isInvalid()
4441                ? ER
4442                : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4443                                            RecoverUncorrectedTypos, Filter);
4444   }
4445 
4446   void diagnoseTypo(const TypoCorrection &Correction,
4447                     const PartialDiagnostic &TypoDiag,
4448                     bool ErrorRecovery = true);
4449 
4450   void diagnoseTypo(const TypoCorrection &Correction,
4451                     const PartialDiagnostic &TypoDiag,
4452                     const PartialDiagnostic &PrevNote,
4453                     bool ErrorRecovery = true);
4454 
4455   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4456 
4457   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4458                                           ArrayRef<Expr *> Args,
4459                                    AssociatedNamespaceSet &AssociatedNamespaces,
4460                                    AssociatedClassSet &AssociatedClasses);
4461 
4462   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4463                             bool ConsiderLinkage, bool AllowInlineNamespace);
4464 
4465   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4466   bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4467   bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4468 
4469   void DiagnoseAmbiguousLookup(LookupResult &Result);
4470   //@}
4471 
4472   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4473   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4474                                 ArrayRef<Expr *> SubExprs,
4475                                 QualType T = QualType());
4476 
4477   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4478                                           SourceLocation IdLoc,
4479                                           bool TypoCorrection = false);
4480   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4481                               SourceLocation Loc);
4482   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4483                                  Scope *S, bool ForRedeclaration,
4484                                  SourceLocation Loc);
4485   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4486                                       Scope *S);
4487   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4488       FunctionDecl *FD);
4489   void AddKnownFunctionAttributes(FunctionDecl *FD);
4490 
4491   // More parsing and symbol table subroutines.
4492 
4493   void ProcessPragmaWeak(Scope *S, Decl *D);
4494   // Decl attributes - this routine is the top level dispatcher.
4495   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4496   // Helper for delayed processing of attributes.
4497   void ProcessDeclAttributeDelayed(Decl *D,
4498                                    const ParsedAttributesView &AttrList);
4499 
4500   // Options for ProcessDeclAttributeList().
4501   struct ProcessDeclAttributeOptions {
4502     ProcessDeclAttributeOptions()
4503         : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
4504 
4505     ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
4506       ProcessDeclAttributeOptions Result = *this;
4507       Result.IncludeCXX11Attributes = Val;
4508       return Result;
4509     }
4510 
4511     ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
4512       ProcessDeclAttributeOptions Result = *this;
4513       Result.IgnoreTypeAttributes = Val;
4514       return Result;
4515     }
4516 
4517     // Should C++11 attributes be processed?
4518     bool IncludeCXX11Attributes;
4519 
4520     // Should any type attributes encountered be ignored?
4521     // If this option is false, a diagnostic will be emitted for any type
4522     // attributes of a kind that does not "slide" from the declaration to
4523     // the decl-specifier-seq.
4524     bool IgnoreTypeAttributes;
4525   };
4526 
4527   void ProcessDeclAttributeList(Scope *S, Decl *D,
4528                                 const ParsedAttributesView &AttrList,
4529                                 const ProcessDeclAttributeOptions &Options =
4530                                     ProcessDeclAttributeOptions());
4531   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4532                                    const ParsedAttributesView &AttrList);
4533 
4534   void checkUnusedDeclAttributes(Declarator &D);
4535 
4536   /// Handles semantic checking for features that are common to all attributes,
4537   /// such as checking whether a parameter was properly specified, or the
4538   /// correct number of arguments were passed, etc. Returns true if the
4539   /// attribute has been diagnosed.
4540   bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4541                                     bool SkipArgCountCheck = false);
4542   bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4543                                     bool SkipArgCountCheck = false);
4544 
4545   /// Determine if type T is a valid subject for a nonnull and similar
4546   /// attributes. By default, we look through references (the behavior used by
4547   /// nonnull), but if the second parameter is true, then we treat a reference
4548   /// type as valid.
4549   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4550 
4551   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4552   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4553                             const FunctionDecl *FD = nullptr);
4554   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4555   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4556   bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4557                                       const Expr *E, StringRef &Str,
4558                                       SourceLocation *ArgLocation = nullptr);
4559   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4560                                       StringRef &Str,
4561                                       SourceLocation *ArgLocation = nullptr);
4562   llvm::Error isValidSectionSpecifier(StringRef Str);
4563   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4564   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4565   bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4566                                    const StringLiteral *Literal,
4567                                    bool &HasDefault, bool &HasCommas,
4568                                    SmallVectorImpl<StringRef> &Strings);
4569   bool checkMSInheritanceAttrOnDefinition(
4570       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4571       MSInheritanceModel SemanticSpelling);
4572 
4573   void CheckAlignasUnderalignment(Decl *D);
4574 
4575   /// Adjust the calling convention of a method to be the ABI default if it
4576   /// wasn't specified explicitly.  This handles method types formed from
4577   /// function type typedefs and typename template arguments.
4578   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4579                               SourceLocation Loc);
4580 
4581   // Check if there is an explicit attribute, but only look through parens.
4582   // The intent is to look for an attribute on the current declarator, but not
4583   // one that came from a typedef.
4584   bool hasExplicitCallingConv(QualType T);
4585 
4586   /// Get the outermost AttributedType node that sets a calling convention.
4587   /// Valid types should not have multiple attributes with different CCs.
4588   const AttributedType *getCallingConvAttributedType(QualType T) const;
4589 
4590   /// Process the attributes before creating an attributed statement. Returns
4591   /// the semantic attributes that have been processed.
4592   void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4593                              SmallVectorImpl<const Attr *> &OutAttrs);
4594 
4595   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4596                                    ObjCMethodDecl *MethodDecl,
4597                                    bool IsProtocolMethodDecl);
4598 
4599   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4600                                    ObjCMethodDecl *Overridden,
4601                                    bool IsProtocolMethodDecl);
4602 
4603   /// WarnExactTypedMethods - This routine issues a warning if method
4604   /// implementation declaration matches exactly that of its declaration.
4605   void WarnExactTypedMethods(ObjCMethodDecl *Method,
4606                              ObjCMethodDecl *MethodDecl,
4607                              bool IsProtocolMethodDecl);
4608 
4609   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4610 
4611   /// CheckImplementationIvars - This routine checks if the instance variables
4612   /// listed in the implelementation match those listed in the interface.
4613   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4614                                 ObjCIvarDecl **Fields, unsigned nIvars,
4615                                 SourceLocation Loc);
4616 
4617   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4618   /// remains unimplemented in the class or category \@implementation.
4619   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4620                                  ObjCContainerDecl* IDecl,
4621                                  bool IncompleteImpl = false);
4622 
4623   /// DiagnoseUnimplementedProperties - This routine warns on those properties
4624   /// which must be implemented by this implementation.
4625   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4626                                        ObjCContainerDecl *CDecl,
4627                                        bool SynthesizeProperties);
4628 
4629   /// Diagnose any null-resettable synthesized setters.
4630   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4631 
4632   /// DefaultSynthesizeProperties - This routine default synthesizes all
4633   /// properties which must be synthesized in the class's \@implementation.
4634   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4635                                    ObjCInterfaceDecl *IDecl,
4636                                    SourceLocation AtEnd);
4637   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4638 
4639   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4640   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4641   /// declared in class 'IFace'.
4642   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4643                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4644 
4645   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4646   /// backs the property is not used in the property's accessor.
4647   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4648                                            const ObjCImplementationDecl *ImplD);
4649 
4650   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4651   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4652   /// It also returns ivar's property on success.
4653   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4654                                                const ObjCPropertyDecl *&PDecl) const;
4655 
4656   /// Called by ActOnProperty to handle \@property declarations in
4657   /// class extensions.
4658   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4659                       SourceLocation AtLoc,
4660                       SourceLocation LParenLoc,
4661                       FieldDeclarator &FD,
4662                       Selector GetterSel,
4663                       SourceLocation GetterNameLoc,
4664                       Selector SetterSel,
4665                       SourceLocation SetterNameLoc,
4666                       const bool isReadWrite,
4667                       unsigned &Attributes,
4668                       const unsigned AttributesAsWritten,
4669                       QualType T,
4670                       TypeSourceInfo *TSI,
4671                       tok::ObjCKeywordKind MethodImplKind);
4672 
4673   /// Called by ActOnProperty and HandlePropertyInClassExtension to
4674   /// handle creating the ObjcPropertyDecl for a category or \@interface.
4675   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4676                                        ObjCContainerDecl *CDecl,
4677                                        SourceLocation AtLoc,
4678                                        SourceLocation LParenLoc,
4679                                        FieldDeclarator &FD,
4680                                        Selector GetterSel,
4681                                        SourceLocation GetterNameLoc,
4682                                        Selector SetterSel,
4683                                        SourceLocation SetterNameLoc,
4684                                        const bool isReadWrite,
4685                                        const unsigned Attributes,
4686                                        const unsigned AttributesAsWritten,
4687                                        QualType T,
4688                                        TypeSourceInfo *TSI,
4689                                        tok::ObjCKeywordKind MethodImplKind,
4690                                        DeclContext *lexicalDC = nullptr);
4691 
4692   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4693   /// warning) when atomic property has one but not the other user-declared
4694   /// setter or getter.
4695   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4696                                        ObjCInterfaceDecl* IDecl);
4697 
4698   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4699 
4700   void DiagnoseMissingDesignatedInitOverrides(
4701                                           const ObjCImplementationDecl *ImplD,
4702                                           const ObjCInterfaceDecl *IFD);
4703 
4704   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4705 
4706   enum MethodMatchStrategy {
4707     MMS_loose,
4708     MMS_strict
4709   };
4710 
4711   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4712   /// true, or false, accordingly.
4713   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4714                                   const ObjCMethodDecl *PrevMethod,
4715                                   MethodMatchStrategy strategy = MMS_strict);
4716 
4717   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4718   /// or protocol against those declared in their implementations.
4719   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4720                                   const SelectorSet &ClsMap,
4721                                   SelectorSet &InsMapSeen,
4722                                   SelectorSet &ClsMapSeen,
4723                                   ObjCImplDecl* IMPDecl,
4724                                   ObjCContainerDecl* IDecl,
4725                                   bool &IncompleteImpl,
4726                                   bool ImmediateClass,
4727                                   bool WarnCategoryMethodImpl=false);
4728 
4729   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4730   /// category matches with those implemented in its primary class and
4731   /// warns each time an exact match is found.
4732   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4733 
4734   /// Add the given method to the list of globally-known methods.
4735   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4736 
4737   /// Returns default addr space for method qualifiers.
4738   LangAS getDefaultCXXMethodAddrSpace() const;
4739 
4740 private:
4741   /// AddMethodToGlobalPool - Add an instance or factory method to the global
4742   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4743   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4744 
4745   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4746   /// optionally warns if there are multiple signatures.
4747   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4748                                            bool receiverIdOrClass,
4749                                            bool instance);
4750 
4751 public:
4752   /// - Returns instance or factory methods in global method pool for
4753   /// given selector. It checks the desired kind first, if none is found, and
4754   /// parameter checkTheOther is set, it then checks the other kind. If no such
4755   /// method or only one method is found, function returns false; otherwise, it
4756   /// returns true.
4757   bool
4758   CollectMultipleMethodsInGlobalPool(Selector Sel,
4759                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4760                                      bool InstanceFirst, bool CheckTheOther,
4761                                      const ObjCObjectType *TypeBound = nullptr);
4762 
4763   bool
4764   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4765                                  SourceRange R, bool receiverIdOrClass,
4766                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4767 
4768   void
4769   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4770                                      Selector Sel, SourceRange R,
4771                                      bool receiverIdOrClass);
4772 
4773 private:
4774   /// - Returns a selector which best matches given argument list or
4775   /// nullptr if none could be found
4776   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4777                                    bool IsInstance,
4778                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4779 
4780 
4781   /// Record the typo correction failure and return an empty correction.
4782   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4783                                   bool RecordFailure = true) {
4784     if (RecordFailure)
4785       TypoCorrectionFailures[Typo].insert(TypoLoc);
4786     return TypoCorrection();
4787   }
4788 
4789 public:
4790   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4791   /// unit are added to a global pool. This allows us to efficiently associate
4792   /// a selector with a method declaraation for purposes of typechecking
4793   /// messages sent to "id" (where the class of the object is unknown).
4794   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4795     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4796   }
4797 
4798   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4799   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4800     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4801   }
4802 
4803   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4804   /// pool.
4805   void AddAnyMethodToGlobalPool(Decl *D);
4806 
4807   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4808   /// there are multiple signatures.
4809   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4810                                                    bool receiverIdOrClass=false) {
4811     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4812                                     /*instance*/true);
4813   }
4814 
4815   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4816   /// there are multiple signatures.
4817   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4818                                                   bool receiverIdOrClass=false) {
4819     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4820                                     /*instance*/false);
4821   }
4822 
4823   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4824                               QualType ObjectType=QualType());
4825   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4826   /// implementation.
4827   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4828 
4829   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4830   /// initialization.
4831   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4832                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4833 
4834   //===--------------------------------------------------------------------===//
4835   // Statement Parsing Callbacks: SemaStmt.cpp.
4836 public:
4837   class FullExprArg {
4838   public:
4839     FullExprArg() : E(nullptr) { }
4840     FullExprArg(Sema &actions) : E(nullptr) { }
4841 
4842     ExprResult release() {
4843       return E;
4844     }
4845 
4846     Expr *get() const { return E; }
4847 
4848     Expr *operator->() {
4849       return E;
4850     }
4851 
4852   private:
4853     // FIXME: No need to make the entire Sema class a friend when it's just
4854     // Sema::MakeFullExpr that needs access to the constructor below.
4855     friend class Sema;
4856 
4857     explicit FullExprArg(Expr *expr) : E(expr) {}
4858 
4859     Expr *E;
4860   };
4861 
4862   FullExprArg MakeFullExpr(Expr *Arg) {
4863     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4864   }
4865   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4866     return FullExprArg(
4867         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4868   }
4869   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4870     ExprResult FE =
4871         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4872                             /*DiscardedValue*/ true);
4873     return FullExprArg(FE.get());
4874   }
4875 
4876   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4877   StmtResult ActOnExprStmtError();
4878 
4879   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4880                            bool HasLeadingEmptyMacro = false);
4881 
4882   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4883   void ActOnAfterCompoundStatementLeadingPragmas();
4884   void ActOnFinishOfCompoundStmt();
4885   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4886                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4887 
4888   /// A RAII object to enter scope of a compound statement.
4889   class CompoundScopeRAII {
4890   public:
4891     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4892       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4893     }
4894 
4895     ~CompoundScopeRAII() {
4896       S.ActOnFinishOfCompoundStmt();
4897     }
4898 
4899   private:
4900     Sema &S;
4901   };
4902 
4903   /// An RAII helper that pops function a function scope on exit.
4904   struct FunctionScopeRAII {
4905     Sema &S;
4906     bool Active;
4907     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4908     ~FunctionScopeRAII() {
4909       if (Active)
4910         S.PopFunctionScopeInfo();
4911     }
4912     void disable() { Active = false; }
4913   };
4914 
4915   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4916                                    SourceLocation StartLoc,
4917                                    SourceLocation EndLoc);
4918   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4919   StmtResult ActOnForEachLValueExpr(Expr *E);
4920   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4921   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4922                            SourceLocation DotDotDotLoc, ExprResult RHS,
4923                            SourceLocation ColonLoc);
4924   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4925 
4926   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4927                                       SourceLocation ColonLoc,
4928                                       Stmt *SubStmt, Scope *CurScope);
4929   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4930                             SourceLocation ColonLoc, Stmt *SubStmt);
4931 
4932   StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
4933                                  ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
4934   StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
4935                                  Stmt *SubStmt);
4936 
4937   class ConditionResult;
4938 
4939   StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4940                          SourceLocation LParenLoc, Stmt *InitStmt,
4941                          ConditionResult Cond, SourceLocation RParenLoc,
4942                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4943   StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4944                          SourceLocation LParenLoc, Stmt *InitStmt,
4945                          ConditionResult Cond, SourceLocation RParenLoc,
4946                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4947   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4948                                     SourceLocation LParenLoc, Stmt *InitStmt,
4949                                     ConditionResult Cond,
4950                                     SourceLocation RParenLoc);
4951   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4952                                            Stmt *Switch, Stmt *Body);
4953   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4954                             ConditionResult Cond, SourceLocation RParenLoc,
4955                             Stmt *Body);
4956   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4957                          SourceLocation WhileLoc, SourceLocation CondLParen,
4958                          Expr *Cond, SourceLocation CondRParen);
4959 
4960   StmtResult ActOnForStmt(SourceLocation ForLoc,
4961                           SourceLocation LParenLoc,
4962                           Stmt *First,
4963                           ConditionResult Second,
4964                           FullExprArg Third,
4965                           SourceLocation RParenLoc,
4966                           Stmt *Body);
4967   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4968                                            Expr *collection);
4969   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4970                                         Stmt *First, Expr *collection,
4971                                         SourceLocation RParenLoc);
4972   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4973 
4974   enum BuildForRangeKind {
4975     /// Initial building of a for-range statement.
4976     BFRK_Build,
4977     /// Instantiation or recovery rebuild of a for-range statement. Don't
4978     /// attempt any typo-correction.
4979     BFRK_Rebuild,
4980     /// Determining whether a for-range statement could be built. Avoid any
4981     /// unnecessary or irreversible actions.
4982     BFRK_Check
4983   };
4984 
4985   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4986                                   SourceLocation CoawaitLoc,
4987                                   Stmt *InitStmt,
4988                                   Stmt *LoopVar,
4989                                   SourceLocation ColonLoc, Expr *Collection,
4990                                   SourceLocation RParenLoc,
4991                                   BuildForRangeKind Kind);
4992   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4993                                   SourceLocation CoawaitLoc,
4994                                   Stmt *InitStmt,
4995                                   SourceLocation ColonLoc,
4996                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4997                                   Expr *Cond, Expr *Inc,
4998                                   Stmt *LoopVarDecl,
4999                                   SourceLocation RParenLoc,
5000                                   BuildForRangeKind Kind);
5001   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
5002 
5003   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
5004                            SourceLocation LabelLoc,
5005                            LabelDecl *TheDecl);
5006   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
5007                                    SourceLocation StarLoc,
5008                                    Expr *DestExp);
5009   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
5010   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
5011 
5012   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5013                                 CapturedRegionKind Kind, unsigned NumParams);
5014   typedef std::pair<StringRef, QualType> CapturedParamNameType;
5015   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
5016                                 CapturedRegionKind Kind,
5017                                 ArrayRef<CapturedParamNameType> Params,
5018                                 unsigned OpenMPCaptureLevel = 0);
5019   StmtResult ActOnCapturedRegionEnd(Stmt *S);
5020   void ActOnCapturedRegionError();
5021   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
5022                                            SourceLocation Loc,
5023                                            unsigned NumParams);
5024 
5025   struct NamedReturnInfo {
5026     const VarDecl *Candidate;
5027 
5028     enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
5029     Status S;
5030 
5031     bool isMoveEligible() const { return S != None; };
5032     bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
5033   };
5034   enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
5035   NamedReturnInfo getNamedReturnInfo(
5036       Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
5037   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
5038   const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
5039                                          QualType ReturnType);
5040 
5041   ExprResult
5042   PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
5043                                   const NamedReturnInfo &NRInfo, Expr *Value,
5044                                   bool SupressSimplerImplicitMoves = false);
5045 
5046   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5047                              Scope *CurScope);
5048   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5049                              bool AllowRecovery = false);
5050   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
5051                                      NamedReturnInfo &NRInfo,
5052                                      bool SupressSimplerImplicitMoves);
5053 
5054   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
5055                              bool IsVolatile, unsigned NumOutputs,
5056                              unsigned NumInputs, IdentifierInfo **Names,
5057                              MultiExprArg Constraints, MultiExprArg Exprs,
5058                              Expr *AsmString, MultiExprArg Clobbers,
5059                              unsigned NumLabels,
5060                              SourceLocation RParenLoc);
5061 
5062   void FillInlineAsmIdentifierInfo(Expr *Res,
5063                                    llvm::InlineAsmIdentifierInfo &Info);
5064   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
5065                                        SourceLocation TemplateKWLoc,
5066                                        UnqualifiedId &Id,
5067                                        bool IsUnevaluatedContext);
5068   bool LookupInlineAsmField(StringRef Base, StringRef Member,
5069                             unsigned &Offset, SourceLocation AsmLoc);
5070   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
5071                                          SourceLocation AsmLoc);
5072   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
5073                             ArrayRef<Token> AsmToks,
5074                             StringRef AsmString,
5075                             unsigned NumOutputs, unsigned NumInputs,
5076                             ArrayRef<StringRef> Constraints,
5077                             ArrayRef<StringRef> Clobbers,
5078                             ArrayRef<Expr*> Exprs,
5079                             SourceLocation EndLoc);
5080   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
5081                                    SourceLocation Location,
5082                                    bool AlwaysCreate);
5083 
5084   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
5085                                   SourceLocation StartLoc,
5086                                   SourceLocation IdLoc, IdentifierInfo *Id,
5087                                   bool Invalid = false);
5088 
5089   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
5090 
5091   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
5092                                   Decl *Parm, Stmt *Body);
5093 
5094   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
5095 
5096   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
5097                                 MultiStmtArg Catch, Stmt *Finally);
5098 
5099   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
5100   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
5101                                   Scope *CurScope);
5102   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
5103                                             Expr *operand);
5104   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
5105                                          Expr *SynchExpr,
5106                                          Stmt *SynchBody);
5107 
5108   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
5109 
5110   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
5111                                      SourceLocation StartLoc,
5112                                      SourceLocation IdLoc,
5113                                      IdentifierInfo *Id);
5114 
5115   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
5116 
5117   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
5118                                 Decl *ExDecl, Stmt *HandlerBlock);
5119   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
5120                               ArrayRef<Stmt *> Handlers);
5121 
5122   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
5123                               SourceLocation TryLoc, Stmt *TryBlock,
5124                               Stmt *Handler);
5125   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
5126                                  Expr *FilterExpr,
5127                                  Stmt *Block);
5128   void ActOnStartSEHFinallyBlock();
5129   void ActOnAbortSEHFinallyBlock();
5130   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
5131   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
5132 
5133   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
5134 
5135   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
5136 
5137   /// If it's a file scoped decl that must warn if not used, keep track
5138   /// of it.
5139   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
5140 
5141   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
5142   /// whose result is unused, warn.
5143   void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
5144   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
5145   void DiagnoseUnusedDecl(const NamedDecl *ND);
5146 
5147   /// If VD is set but not otherwise used, diagnose, for a parameter or a
5148   /// variable.
5149   void DiagnoseUnusedButSetDecl(const VarDecl *VD);
5150 
5151   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
5152   /// statement as a \p Body, and it is located on the same line.
5153   ///
5154   /// This helps prevent bugs due to typos, such as:
5155   ///     if (condition);
5156   ///       do_stuff();
5157   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5158                              const Stmt *Body,
5159                              unsigned DiagID);
5160 
5161   /// Warn if a for/while loop statement \p S, which is followed by
5162   /// \p PossibleBody, has a suspicious null statement as a body.
5163   void DiagnoseEmptyLoopBody(const Stmt *S,
5164                              const Stmt *PossibleBody);
5165 
5166   /// Warn if a value is moved to itself.
5167   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
5168                         SourceLocation OpLoc);
5169 
5170   /// Warn if we're implicitly casting from a _Nullable pointer type to a
5171   /// _Nonnull one.
5172   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
5173                                            SourceLocation Loc);
5174 
5175   /// Warn when implicitly casting 0 to nullptr.
5176   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
5177 
5178   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
5179     return DelayedDiagnostics.push(pool);
5180   }
5181   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5182 
5183   typedef ProcessingContextState ParsingClassState;
5184   ParsingClassState PushParsingClass() {
5185     ParsingClassDepth++;
5186     return DelayedDiagnostics.pushUndelayed();
5187   }
5188   void PopParsingClass(ParsingClassState state) {
5189     ParsingClassDepth--;
5190     DelayedDiagnostics.popUndelayed(state);
5191   }
5192 
5193   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5194 
5195   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5196                                   const ObjCInterfaceDecl *UnknownObjCClass,
5197                                   bool ObjCPropertyAccess,
5198                                   bool AvoidPartialAvailabilityChecks = false,
5199                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
5200 
5201   bool makeUnavailableInSystemHeader(SourceLocation loc,
5202                                      UnavailableAttr::ImplicitReason reason);
5203 
5204   /// Issue any -Wunguarded-availability warnings in \c FD
5205   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
5206 
5207   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5208 
5209   //===--------------------------------------------------------------------===//
5210   // Expression Parsing Callbacks: SemaExpr.cpp.
5211 
5212   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
5213   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5214                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
5215                          bool ObjCPropertyAccess = false,
5216                          bool AvoidPartialAvailabilityChecks = false,
5217                          ObjCInterfaceDecl *ClassReciever = nullptr);
5218   void NoteDeletedFunction(FunctionDecl *FD);
5219   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5220   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5221                                         ObjCMethodDecl *Getter,
5222                                         SourceLocation Loc);
5223   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5224                              ArrayRef<Expr *> Args);
5225 
5226   void PushExpressionEvaluationContext(
5227       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5228       ExpressionEvaluationContextRecord::ExpressionKind Type =
5229           ExpressionEvaluationContextRecord::EK_Other);
5230   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5231   void PushExpressionEvaluationContext(
5232       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5233       ExpressionEvaluationContextRecord::ExpressionKind Type =
5234           ExpressionEvaluationContextRecord::EK_Other);
5235   void PopExpressionEvaluationContext();
5236 
5237   void DiscardCleanupsInEvaluationContext();
5238 
5239   ExprResult TransformToPotentiallyEvaluated(Expr *E);
5240   TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
5241   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5242 
5243   ExprResult CheckUnevaluatedOperand(Expr *E);
5244   void CheckUnusedVolatileAssignment(Expr *E);
5245 
5246   ExprResult ActOnConstantExpression(ExprResult Res);
5247 
5248   // Functions for marking a declaration referenced.  These functions also
5249   // contain the relevant logic for marking if a reference to a function or
5250   // variable is an odr-use (in the C++11 sense).  There are separate variants
5251   // for expressions referring to a decl; these exist because odr-use marking
5252   // needs to be delayed for some constant variables when we build one of the
5253   // named expressions.
5254   //
5255   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5256   // should usually be true. This only needs to be set to false if the lack of
5257   // odr-use cannot be determined from the current context (for instance,
5258   // because the name denotes a virtual function and was written without an
5259   // explicit nested-name-specifier).
5260   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5261   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5262                               bool MightBeOdrUse = true);
5263   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5264   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5265   void MarkMemberReferenced(MemberExpr *E);
5266   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5267   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
5268                                          unsigned CapturingScopeIndex);
5269 
5270   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5271   void CleanupVarDeclMarking();
5272 
5273   enum TryCaptureKind {
5274     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5275   };
5276 
5277   /// Try to capture the given variable.
5278   ///
5279   /// \param Var The variable to capture.
5280   ///
5281   /// \param Loc The location at which the capture occurs.
5282   ///
5283   /// \param Kind The kind of capture, which may be implicit (for either a
5284   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5285   ///
5286   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5287   /// an explicit lambda capture.
5288   ///
5289   /// \param BuildAndDiagnose Whether we are actually supposed to add the
5290   /// captures or diagnose errors. If false, this routine merely check whether
5291   /// the capture can occur without performing the capture itself or complaining
5292   /// if the variable cannot be captured.
5293   ///
5294   /// \param CaptureType Will be set to the type of the field used to capture
5295   /// this variable in the innermost block or lambda. Only valid when the
5296   /// variable can be captured.
5297   ///
5298   /// \param DeclRefType Will be set to the type of a reference to the capture
5299   /// from within the current scope. Only valid when the variable can be
5300   /// captured.
5301   ///
5302   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5303   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5304   /// This is useful when enclosing lambdas must speculatively capture
5305   /// variables that may or may not be used in certain specializations of
5306   /// a nested generic lambda.
5307   ///
5308   /// \returns true if an error occurred (i.e., the variable cannot be
5309   /// captured) and false if the capture succeeded.
5310   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
5311                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
5312                           QualType &CaptureType,
5313                           QualType &DeclRefType,
5314                           const unsigned *const FunctionScopeIndexToStopAt);
5315 
5316   /// Try to capture the given variable.
5317   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
5318                           TryCaptureKind Kind = TryCapture_Implicit,
5319                           SourceLocation EllipsisLoc = SourceLocation());
5320 
5321   /// Checks if the variable must be captured.
5322   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
5323 
5324   /// Given a variable, determine the type that a reference to that
5325   /// variable will have in the given scope.
5326   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
5327 
5328   /// Mark all of the declarations referenced within a particular AST node as
5329   /// referenced. Used when template instantiation instantiates a non-dependent
5330   /// type -- entities referenced by the type are now referenced.
5331   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5332   void MarkDeclarationsReferencedInExpr(Expr *E,
5333                                         bool SkipLocalVariables = false,
5334                                         ArrayRef<const Expr *> StopAt = None);
5335 
5336   /// Try to recover by turning the given expression into a
5337   /// call.  Returns true if recovery was attempted or an error was
5338   /// emitted; this may also leave the ExprResult invalid.
5339   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5340                             bool ForceComplain = false,
5341                             bool (*IsPlausibleResult)(QualType) = nullptr);
5342 
5343   /// Figure out if an expression could be turned into a call.
5344   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5345                      UnresolvedSetImpl &NonTemplateOverloads);
5346 
5347   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5348   /// conversion.
5349   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5350 
5351   /// Conditionally issue a diagnostic based on the statements's reachability
5352   /// analysis.
5353   ///
5354   /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5355   /// the function body is parsed, and then do a basic reachability analysis to
5356   /// determine if the statement is reachable. If it is unreachable, the
5357   /// diagnostic will not be emitted.
5358   bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5359                        const PartialDiagnostic &PD);
5360 
5361   /// Conditionally issue a diagnostic based on the current
5362   /// evaluation context.
5363   ///
5364   /// \param Statement If Statement is non-null, delay reporting the
5365   /// diagnostic until the function body is parsed, and then do a basic
5366   /// reachability analysis to determine if the statement is reachable.
5367   /// If it is unreachable, the diagnostic will not be emitted.
5368   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5369                            const PartialDiagnostic &PD);
5370   /// Similar, but diagnostic is only produced if all the specified statements
5371   /// are reachable.
5372   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5373                            const PartialDiagnostic &PD);
5374 
5375   // Primary Expressions.
5376   SourceRange getExprRange(Expr *E) const;
5377 
5378   ExprResult ActOnIdExpression(
5379       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5380       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5381       CorrectionCandidateCallback *CCC = nullptr,
5382       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5383 
5384   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5385                               TemplateArgumentListInfo &Buffer,
5386                               DeclarationNameInfo &NameInfo,
5387                               const TemplateArgumentListInfo *&TemplateArgs);
5388 
5389   bool DiagnoseDependentMemberLookup(LookupResult &R);
5390 
5391   bool
5392   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5393                       CorrectionCandidateCallback &CCC,
5394                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5395                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
5396 
5397   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5398                                     IdentifierInfo *II);
5399   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5400 
5401   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5402                                 IdentifierInfo *II,
5403                                 bool AllowBuiltinCreation=false);
5404 
5405   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5406                                         SourceLocation TemplateKWLoc,
5407                                         const DeclarationNameInfo &NameInfo,
5408                                         bool isAddressOfOperand,
5409                                 const TemplateArgumentListInfo *TemplateArgs);
5410 
5411   /// If \p D cannot be odr-used in the current expression evaluation context,
5412   /// return a reason explaining why. Otherwise, return NOUR_None.
5413   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5414 
5415   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5416                                 SourceLocation Loc,
5417                                 const CXXScopeSpec *SS = nullptr);
5418   DeclRefExpr *
5419   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5420                    const DeclarationNameInfo &NameInfo,
5421                    const CXXScopeSpec *SS = nullptr,
5422                    NamedDecl *FoundD = nullptr,
5423                    SourceLocation TemplateKWLoc = SourceLocation(),
5424                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5425   DeclRefExpr *
5426   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5427                    const DeclarationNameInfo &NameInfo,
5428                    NestedNameSpecifierLoc NNS,
5429                    NamedDecl *FoundD = nullptr,
5430                    SourceLocation TemplateKWLoc = SourceLocation(),
5431                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5432 
5433   ExprResult
5434   BuildAnonymousStructUnionMemberReference(
5435       const CXXScopeSpec &SS,
5436       SourceLocation nameLoc,
5437       IndirectFieldDecl *indirectField,
5438       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5439       Expr *baseObjectExpr = nullptr,
5440       SourceLocation opLoc = SourceLocation());
5441 
5442   ExprResult BuildPossibleImplicitMemberExpr(
5443       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5444       const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5445       UnresolvedLookupExpr *AsULE = nullptr);
5446   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5447                                      SourceLocation TemplateKWLoc,
5448                                      LookupResult &R,
5449                                 const TemplateArgumentListInfo *TemplateArgs,
5450                                      bool IsDefiniteInstance,
5451                                      const Scope *S);
5452   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5453                                   const LookupResult &R,
5454                                   bool HasTrailingLParen);
5455 
5456   ExprResult
5457   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5458                                     const DeclarationNameInfo &NameInfo,
5459                                     bool IsAddressOfOperand, const Scope *S,
5460                                     TypeSourceInfo **RecoveryTSI = nullptr);
5461 
5462   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5463                                        SourceLocation TemplateKWLoc,
5464                                 const DeclarationNameInfo &NameInfo,
5465                                 const TemplateArgumentListInfo *TemplateArgs);
5466 
5467   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5468                                       LookupResult &R,
5469                                       bool NeedsADL,
5470                                       bool AcceptInvalidDecl = false);
5471   ExprResult BuildDeclarationNameExpr(
5472       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5473       NamedDecl *FoundD = nullptr,
5474       const TemplateArgumentListInfo *TemplateArgs = nullptr,
5475       bool AcceptInvalidDecl = false);
5476 
5477   ExprResult BuildLiteralOperatorCall(LookupResult &R,
5478                       DeclarationNameInfo &SuffixInfo,
5479                       ArrayRef<Expr *> Args,
5480                       SourceLocation LitEndLoc,
5481                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5482 
5483   ExprResult BuildPredefinedExpr(SourceLocation Loc,
5484                                  PredefinedExpr::IdentKind IK);
5485   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5486   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5487 
5488   ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5489                                            SourceLocation LParen,
5490                                            SourceLocation RParen,
5491                                            TypeSourceInfo *TSI);
5492   ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5493                                            SourceLocation LParen,
5494                                            SourceLocation RParen,
5495                                            ParsedType ParsedTy);
5496 
5497   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5498 
5499   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5500   ExprResult ActOnCharacterConstant(const Token &Tok,
5501                                     Scope *UDLScope = nullptr);
5502   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5503   ExprResult ActOnParenListExpr(SourceLocation L,
5504                                 SourceLocation R,
5505                                 MultiExprArg Val);
5506 
5507   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5508   /// fragments (e.g. "foo" "bar" L"baz").
5509   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5510                                 Scope *UDLScope = nullptr);
5511 
5512   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5513                                        SourceLocation DefaultLoc,
5514                                        SourceLocation RParenLoc,
5515                                        Expr *ControllingExpr,
5516                                        ArrayRef<ParsedType> ArgTypes,
5517                                        ArrayRef<Expr *> ArgExprs);
5518   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5519                                         SourceLocation DefaultLoc,
5520                                         SourceLocation RParenLoc,
5521                                         Expr *ControllingExpr,
5522                                         ArrayRef<TypeSourceInfo *> Types,
5523                                         ArrayRef<Expr *> Exprs);
5524 
5525   // Binary/Unary Operators.  'Tok' is the token for the operator.
5526   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5527                                   Expr *InputExpr);
5528   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5529                           UnaryOperatorKind Opc, Expr *Input);
5530   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5531                           tok::TokenKind Op, Expr *Input);
5532 
5533   bool isQualifiedMemberAccess(Expr *E);
5534   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5535 
5536   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5537                                             SourceLocation OpLoc,
5538                                             UnaryExprOrTypeTrait ExprKind,
5539                                             SourceRange R);
5540   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5541                                             UnaryExprOrTypeTrait ExprKind);
5542   ExprResult
5543     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5544                                   UnaryExprOrTypeTrait ExprKind,
5545                                   bool IsType, void *TyOrEx,
5546                                   SourceRange ArgRange);
5547 
5548   ExprResult CheckPlaceholderExpr(Expr *E);
5549   bool CheckVecStepExpr(Expr *E);
5550 
5551   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5552   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5553                                         SourceRange ExprRange,
5554                                         UnaryExprOrTypeTrait ExprKind);
5555   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5556                                           SourceLocation OpLoc,
5557                                           IdentifierInfo &Name,
5558                                           SourceLocation NameLoc,
5559                                           SourceLocation RParenLoc);
5560   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5561                                  tok::TokenKind Kind, Expr *Input);
5562 
5563   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5564                                      MultiExprArg ArgExprs,
5565                                      SourceLocation RLoc);
5566   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5567                                              Expr *Idx, SourceLocation RLoc);
5568 
5569   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5570                                               Expr *ColumnIdx,
5571                                               SourceLocation RBLoc);
5572 
5573   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5574                                       Expr *LowerBound,
5575                                       SourceLocation ColonLocFirst,
5576                                       SourceLocation ColonLocSecond,
5577                                       Expr *Length, Expr *Stride,
5578                                       SourceLocation RBLoc);
5579   ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5580                                       SourceLocation RParenLoc,
5581                                       ArrayRef<Expr *> Dims,
5582                                       ArrayRef<SourceRange> Brackets);
5583 
5584   /// Data structure for iterator expression.
5585   struct OMPIteratorData {
5586     IdentifierInfo *DeclIdent = nullptr;
5587     SourceLocation DeclIdentLoc;
5588     ParsedType Type;
5589     OMPIteratorExpr::IteratorRange Range;
5590     SourceLocation AssignLoc;
5591     SourceLocation ColonLoc;
5592     SourceLocation SecColonLoc;
5593   };
5594 
5595   ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5596                                   SourceLocation LLoc, SourceLocation RLoc,
5597                                   ArrayRef<OMPIteratorData> Data);
5598 
5599   // This struct is for use by ActOnMemberAccess to allow
5600   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5601   // changing the access operator from a '.' to a '->' (to see if that is the
5602   // change needed to fix an error about an unknown member, e.g. when the class
5603   // defines a custom operator->).
5604   struct ActOnMemberAccessExtraArgs {
5605     Scope *S;
5606     UnqualifiedId &Id;
5607     Decl *ObjCImpDecl;
5608   };
5609 
5610   ExprResult BuildMemberReferenceExpr(
5611       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5612       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5613       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5614       const TemplateArgumentListInfo *TemplateArgs,
5615       const Scope *S,
5616       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5617 
5618   ExprResult
5619   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5620                            bool IsArrow, const CXXScopeSpec &SS,
5621                            SourceLocation TemplateKWLoc,
5622                            NamedDecl *FirstQualifierInScope, LookupResult &R,
5623                            const TemplateArgumentListInfo *TemplateArgs,
5624                            const Scope *S,
5625                            bool SuppressQualifierCheck = false,
5626                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5627 
5628   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5629                                      SourceLocation OpLoc,
5630                                      const CXXScopeSpec &SS, FieldDecl *Field,
5631                                      DeclAccessPair FoundDecl,
5632                                      const DeclarationNameInfo &MemberNameInfo);
5633 
5634   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5635 
5636   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5637                                      const CXXScopeSpec &SS,
5638                                      const LookupResult &R);
5639 
5640   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5641                                       bool IsArrow, SourceLocation OpLoc,
5642                                       const CXXScopeSpec &SS,
5643                                       SourceLocation TemplateKWLoc,
5644                                       NamedDecl *FirstQualifierInScope,
5645                                const DeclarationNameInfo &NameInfo,
5646                                const TemplateArgumentListInfo *TemplateArgs);
5647 
5648   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5649                                    SourceLocation OpLoc,
5650                                    tok::TokenKind OpKind,
5651                                    CXXScopeSpec &SS,
5652                                    SourceLocation TemplateKWLoc,
5653                                    UnqualifiedId &Member,
5654                                    Decl *ObjCImpDecl);
5655 
5656   MemberExpr *
5657   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5658                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5659                   ValueDecl *Member, DeclAccessPair FoundDecl,
5660                   bool HadMultipleCandidates,
5661                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5662                   ExprValueKind VK, ExprObjectKind OK,
5663                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5664   MemberExpr *
5665   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5666                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5667                   ValueDecl *Member, DeclAccessPair FoundDecl,
5668                   bool HadMultipleCandidates,
5669                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5670                   ExprValueKind VK, ExprObjectKind OK,
5671                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5672 
5673   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5674   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5675                                FunctionDecl *FDecl,
5676                                const FunctionProtoType *Proto,
5677                                ArrayRef<Expr *> Args,
5678                                SourceLocation RParenLoc,
5679                                bool ExecConfig = false);
5680   void CheckStaticArrayArgument(SourceLocation CallLoc,
5681                                 ParmVarDecl *Param,
5682                                 const Expr *ArgExpr);
5683 
5684   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5685   /// This provides the location of the left/right parens and a list of comma
5686   /// locations.
5687   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5688                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5689                            Expr *ExecConfig = nullptr);
5690   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5691                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5692                            Expr *ExecConfig = nullptr,
5693                            bool IsExecConfig = false,
5694                            bool AllowRecovery = false);
5695   Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5696                              MultiExprArg CallArgs);
5697   enum class AtomicArgumentOrder { API, AST };
5698   ExprResult
5699   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5700                   SourceLocation RParenLoc, MultiExprArg Args,
5701                   AtomicExpr::AtomicOp Op,
5702                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5703   ExprResult
5704   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5705                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5706                         Expr *Config = nullptr, bool IsExecConfig = false,
5707                         ADLCallKind UsesADL = ADLCallKind::NotADL);
5708 
5709   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5710                                      MultiExprArg ExecConfig,
5711                                      SourceLocation GGGLoc);
5712 
5713   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5714                            Declarator &D, ParsedType &Ty,
5715                            SourceLocation RParenLoc, Expr *CastExpr);
5716   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5717                                  TypeSourceInfo *Ty,
5718                                  SourceLocation RParenLoc,
5719                                  Expr *Op);
5720   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5721 
5722   /// Build an altivec or OpenCL literal.
5723   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5724                                 SourceLocation RParenLoc, Expr *E,
5725                                 TypeSourceInfo *TInfo);
5726 
5727   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5728 
5729   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5730                                   ParsedType Ty,
5731                                   SourceLocation RParenLoc,
5732                                   Expr *InitExpr);
5733 
5734   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5735                                       TypeSourceInfo *TInfo,
5736                                       SourceLocation RParenLoc,
5737                                       Expr *LiteralExpr);
5738 
5739   ExprResult ActOnInitList(SourceLocation LBraceLoc,
5740                            MultiExprArg InitArgList,
5741                            SourceLocation RBraceLoc);
5742 
5743   ExprResult BuildInitList(SourceLocation LBraceLoc,
5744                            MultiExprArg InitArgList,
5745                            SourceLocation RBraceLoc);
5746 
5747   ExprResult ActOnDesignatedInitializer(Designation &Desig,
5748                                         SourceLocation EqualOrColonLoc,
5749                                         bool GNUSyntax,
5750                                         ExprResult Init);
5751 
5752 private:
5753   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5754 
5755 public:
5756   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5757                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5758   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5759                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5760   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5761                                 Expr *LHSExpr, Expr *RHSExpr);
5762   void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5763                    UnresolvedSetImpl &Functions);
5764 
5765   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5766 
5767   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5768   /// in the case of a the GNU conditional expr extension.
5769   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5770                                 SourceLocation ColonLoc,
5771                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5772 
5773   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5774   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5775                             LabelDecl *TheDecl);
5776 
5777   void ActOnStartStmtExpr();
5778   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5779                            SourceLocation RPLoc);
5780   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5781                            SourceLocation RPLoc, unsigned TemplateDepth);
5782   // Handle the final expression in a statement expression.
5783   ExprResult ActOnStmtExprResult(ExprResult E);
5784   void ActOnStmtExprError();
5785 
5786   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5787   struct OffsetOfComponent {
5788     SourceLocation LocStart, LocEnd;
5789     bool isBrackets;  // true if [expr], false if .ident
5790     union {
5791       IdentifierInfo *IdentInfo;
5792       Expr *E;
5793     } U;
5794   };
5795 
5796   /// __builtin_offsetof(type, a.b[123][456].c)
5797   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5798                                   TypeSourceInfo *TInfo,
5799                                   ArrayRef<OffsetOfComponent> Components,
5800                                   SourceLocation RParenLoc);
5801   ExprResult ActOnBuiltinOffsetOf(Scope *S,
5802                                   SourceLocation BuiltinLoc,
5803                                   SourceLocation TypeLoc,
5804                                   ParsedType ParsedArgTy,
5805                                   ArrayRef<OffsetOfComponent> Components,
5806                                   SourceLocation RParenLoc);
5807 
5808   // __builtin_choose_expr(constExpr, expr1, expr2)
5809   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5810                              Expr *CondExpr, Expr *LHSExpr,
5811                              Expr *RHSExpr, SourceLocation RPLoc);
5812 
5813   // __builtin_va_arg(expr, type)
5814   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5815                         SourceLocation RPLoc);
5816   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5817                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
5818 
5819   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5820   // __builtin_COLUMN(), __builtin_source_location()
5821   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5822                                 SourceLocation BuiltinLoc,
5823                                 SourceLocation RPLoc);
5824 
5825   // Build a potentially resolved SourceLocExpr.
5826   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5827                                 QualType ResultTy, SourceLocation BuiltinLoc,
5828                                 SourceLocation RPLoc,
5829                                 DeclContext *ParentContext);
5830 
5831   // __null
5832   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5833 
5834   bool CheckCaseExpression(Expr *E);
5835 
5836   /// Describes the result of an "if-exists" condition check.
5837   enum IfExistsResult {
5838     /// The symbol exists.
5839     IER_Exists,
5840 
5841     /// The symbol does not exist.
5842     IER_DoesNotExist,
5843 
5844     /// The name is a dependent name, so the results will differ
5845     /// from one instantiation to the next.
5846     IER_Dependent,
5847 
5848     /// An error occurred.
5849     IER_Error
5850   };
5851 
5852   IfExistsResult
5853   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5854                                const DeclarationNameInfo &TargetNameInfo);
5855 
5856   IfExistsResult
5857   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5858                                bool IsIfExists, CXXScopeSpec &SS,
5859                                UnqualifiedId &Name);
5860 
5861   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5862                                         bool IsIfExists,
5863                                         NestedNameSpecifierLoc QualifierLoc,
5864                                         DeclarationNameInfo NameInfo,
5865                                         Stmt *Nested);
5866   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5867                                         bool IsIfExists,
5868                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5869                                         Stmt *Nested);
5870 
5871   //===------------------------- "Block" Extension ------------------------===//
5872 
5873   /// ActOnBlockStart - This callback is invoked when a block literal is
5874   /// started.
5875   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5876 
5877   /// ActOnBlockArguments - This callback allows processing of block arguments.
5878   /// If there are no arguments, this is still invoked.
5879   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5880                            Scope *CurScope);
5881 
5882   /// ActOnBlockError - If there is an error parsing a block, this callback
5883   /// is invoked to pop the information about the block from the action impl.
5884   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5885 
5886   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5887   /// literal was successfully completed.  ^(int x){...}
5888   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5889                                 Scope *CurScope);
5890 
5891   //===---------------------------- Clang Extensions ----------------------===//
5892 
5893   /// __builtin_convertvector(...)
5894   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5895                                     SourceLocation BuiltinLoc,
5896                                     SourceLocation RParenLoc);
5897 
5898   //===---------------------------- OpenCL Features -----------------------===//
5899 
5900   /// __builtin_astype(...)
5901   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5902                              SourceLocation BuiltinLoc,
5903                              SourceLocation RParenLoc);
5904   ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
5905                              SourceLocation BuiltinLoc,
5906                              SourceLocation RParenLoc);
5907 
5908   //===---------------------------- C++ Features --------------------------===//
5909 
5910   // Act on C++ namespaces
5911   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5912                                SourceLocation NamespaceLoc,
5913                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5914                                SourceLocation LBrace,
5915                                const ParsedAttributesView &AttrList,
5916                                UsingDirectiveDecl *&UsingDecl);
5917   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5918 
5919   NamespaceDecl *getStdNamespace() const;
5920   NamespaceDecl *getOrCreateStdNamespace();
5921 
5922   NamespaceDecl *lookupStdExperimentalNamespace();
5923   NamespaceDecl *getCachedCoroNamespace() { return CoroTraitsNamespaceCache; }
5924 
5925   CXXRecordDecl *getStdBadAlloc() const;
5926   EnumDecl *getStdAlignValT() const;
5927 
5928 private:
5929   // A cache representing if we've fully checked the various comparison category
5930   // types stored in ASTContext. The bit-index corresponds to the integer value
5931   // of a ComparisonCategoryType enumerator.
5932   llvm::SmallBitVector FullyCheckedComparisonCategories;
5933 
5934   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5935                                          CXXScopeSpec &SS,
5936                                          ParsedType TemplateTypeTy,
5937                                          IdentifierInfo *MemberOrBase);
5938 
5939 public:
5940   enum class ComparisonCategoryUsage {
5941     /// The '<=>' operator was used in an expression and a builtin operator
5942     /// was selected.
5943     OperatorInExpression,
5944     /// A defaulted 'operator<=>' needed the comparison category. This
5945     /// typically only applies to 'std::strong_ordering', due to the implicit
5946     /// fallback return value.
5947     DefaultedOperator,
5948   };
5949 
5950   /// Lookup the specified comparison category types in the standard
5951   ///   library, an check the VarDecls possibly returned by the operator<=>
5952   ///   builtins for that type.
5953   ///
5954   /// \return The type of the comparison category type corresponding to the
5955   ///   specified Kind, or a null type if an error occurs
5956   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5957                                        SourceLocation Loc,
5958                                        ComparisonCategoryUsage Usage);
5959 
5960   /// Tests whether Ty is an instance of std::initializer_list and, if
5961   /// it is and Element is not NULL, assigns the element type to Element.
5962   bool isStdInitializerList(QualType Ty, QualType *Element);
5963 
5964   /// Looks for the std::initializer_list template and instantiates it
5965   /// with Element, or emits an error if it's not found.
5966   ///
5967   /// \returns The instantiated template, or null on error.
5968   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5969 
5970   /// Determine whether Ctor is an initializer-list constructor, as
5971   /// defined in [dcl.init.list]p2.
5972   bool isInitListConstructor(const FunctionDecl *Ctor);
5973 
5974   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5975                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5976                             SourceLocation IdentLoc,
5977                             IdentifierInfo *NamespcName,
5978                             const ParsedAttributesView &AttrList);
5979 
5980   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5981 
5982   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5983                                SourceLocation NamespaceLoc,
5984                                SourceLocation AliasLoc,
5985                                IdentifierInfo *Alias,
5986                                CXXScopeSpec &SS,
5987                                SourceLocation IdentLoc,
5988                                IdentifierInfo *Ident);
5989 
5990   void FilterUsingLookup(Scope *S, LookupResult &lookup);
5991   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5992   bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5993                             const LookupResult &PreviousDecls,
5994                             UsingShadowDecl *&PrevShadow);
5995   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5996                                         NamedDecl *Target,
5997                                         UsingShadowDecl *PrevDecl);
5998 
5999   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6000                                    bool HasTypenameKeyword,
6001                                    const CXXScopeSpec &SS,
6002                                    SourceLocation NameLoc,
6003                                    const LookupResult &Previous);
6004   bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
6005                                const CXXScopeSpec &SS,
6006                                const DeclarationNameInfo &NameInfo,
6007                                SourceLocation NameLoc,
6008                                const LookupResult *R = nullptr,
6009                                const UsingDecl *UD = nullptr);
6010 
6011   NamedDecl *BuildUsingDeclaration(
6012       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
6013       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
6014       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
6015       const ParsedAttributesView &AttrList, bool IsInstantiation,
6016       bool IsUsingIfExists);
6017   NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
6018                                        SourceLocation UsingLoc,
6019                                        SourceLocation EnumLoc,
6020                                        SourceLocation NameLoc, EnumDecl *ED);
6021   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
6022                                 ArrayRef<NamedDecl *> Expansions);
6023 
6024   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
6025 
6026   /// Given a derived-class using shadow declaration for a constructor and the
6027   /// correspnding base class constructor, find or create the implicit
6028   /// synthesized derived class constructor to use for this initialization.
6029   CXXConstructorDecl *
6030   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
6031                             ConstructorUsingShadowDecl *DerivedShadow);
6032 
6033   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
6034                               SourceLocation UsingLoc,
6035                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
6036                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
6037                               const ParsedAttributesView &AttrList);
6038   Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
6039                                   SourceLocation UsingLoc,
6040                                   SourceLocation EnumLoc, const DeclSpec &);
6041   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
6042                               MultiTemplateParamsArg TemplateParams,
6043                               SourceLocation UsingLoc, UnqualifiedId &Name,
6044                               const ParsedAttributesView &AttrList,
6045                               TypeResult Type, Decl *DeclFromDeclSpec);
6046 
6047   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
6048   /// including handling of its default argument expressions.
6049   ///
6050   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
6051   ExprResult
6052   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6053                         NamedDecl *FoundDecl,
6054                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
6055                         bool HadMultipleCandidates, bool IsListInitialization,
6056                         bool IsStdInitListInitialization,
6057                         bool RequiresZeroInit, unsigned ConstructKind,
6058                         SourceRange ParenRange);
6059 
6060   /// Build a CXXConstructExpr whose constructor has already been resolved if
6061   /// it denotes an inherited constructor.
6062   ExprResult
6063   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6064                         CXXConstructorDecl *Constructor, bool Elidable,
6065                         MultiExprArg Exprs,
6066                         bool HadMultipleCandidates, bool IsListInitialization,
6067                         bool IsStdInitListInitialization,
6068                         bool RequiresZeroInit, unsigned ConstructKind,
6069                         SourceRange ParenRange);
6070 
6071   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
6072   // the constructor can be elidable?
6073   ExprResult
6074   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6075                         NamedDecl *FoundDecl,
6076                         CXXConstructorDecl *Constructor, bool Elidable,
6077                         MultiExprArg Exprs, bool HadMultipleCandidates,
6078                         bool IsListInitialization,
6079                         bool IsStdInitListInitialization, bool RequiresZeroInit,
6080                         unsigned ConstructKind, SourceRange ParenRange);
6081 
6082   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
6083 
6084 
6085   /// Instantiate or parse a C++ default argument expression as necessary.
6086   /// Return true on error.
6087   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6088                               ParmVarDecl *Param);
6089 
6090   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
6091   /// the default expr if needed.
6092   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6093                                     FunctionDecl *FD,
6094                                     ParmVarDecl *Param);
6095 
6096   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
6097   /// constructed variable.
6098   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
6099 
6100   /// Helper class that collects exception specifications for
6101   /// implicitly-declared special member functions.
6102   class ImplicitExceptionSpecification {
6103     // Pointer to allow copying
6104     Sema *Self;
6105     // We order exception specifications thus:
6106     // noexcept is the most restrictive, but is only used in C++11.
6107     // throw() comes next.
6108     // Then a throw(collected exceptions)
6109     // Finally no specification, which is expressed as noexcept(false).
6110     // throw(...) is used instead if any called function uses it.
6111     ExceptionSpecificationType ComputedEST;
6112     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
6113     SmallVector<QualType, 4> Exceptions;
6114 
6115     void ClearExceptions() {
6116       ExceptionsSeen.clear();
6117       Exceptions.clear();
6118     }
6119 
6120   public:
6121     explicit ImplicitExceptionSpecification(Sema &Self)
6122       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
6123       if (!Self.getLangOpts().CPlusPlus11)
6124         ComputedEST = EST_DynamicNone;
6125     }
6126 
6127     /// Get the computed exception specification type.
6128     ExceptionSpecificationType getExceptionSpecType() const {
6129       assert(!isComputedNoexcept(ComputedEST) &&
6130              "noexcept(expr) should not be a possible result");
6131       return ComputedEST;
6132     }
6133 
6134     /// The number of exceptions in the exception specification.
6135     unsigned size() const { return Exceptions.size(); }
6136 
6137     /// The set of exceptions in the exception specification.
6138     const QualType *data() const { return Exceptions.data(); }
6139 
6140     /// Integrate another called method into the collected data.
6141     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
6142 
6143     /// Integrate an invoked expression into the collected data.
6144     void CalledExpr(Expr *E) { CalledStmt(E); }
6145 
6146     /// Integrate an invoked statement into the collected data.
6147     void CalledStmt(Stmt *S);
6148 
6149     /// Overwrite an EPI's exception specification with this
6150     /// computed exception specification.
6151     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
6152       FunctionProtoType::ExceptionSpecInfo ESI;
6153       ESI.Type = getExceptionSpecType();
6154       if (ESI.Type == EST_Dynamic) {
6155         ESI.Exceptions = Exceptions;
6156       } else if (ESI.Type == EST_None) {
6157         /// C++11 [except.spec]p14:
6158         ///   The exception-specification is noexcept(false) if the set of
6159         ///   potential exceptions of the special member function contains "any"
6160         ESI.Type = EST_NoexceptFalse;
6161         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
6162                                                      tok::kw_false).get();
6163       }
6164       return ESI;
6165     }
6166   };
6167 
6168   /// Evaluate the implicit exception specification for a defaulted
6169   /// special member function.
6170   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
6171 
6172   /// Check the given noexcept-specifier, convert its expression, and compute
6173   /// the appropriate ExceptionSpecificationType.
6174   ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6175                                ExceptionSpecificationType &EST);
6176 
6177   /// Check the given exception-specification and update the
6178   /// exception specification information with the results.
6179   void checkExceptionSpecification(bool IsTopLevel,
6180                                    ExceptionSpecificationType EST,
6181                                    ArrayRef<ParsedType> DynamicExceptions,
6182                                    ArrayRef<SourceRange> DynamicExceptionRanges,
6183                                    Expr *NoexceptExpr,
6184                                    SmallVectorImpl<QualType> &Exceptions,
6185                                    FunctionProtoType::ExceptionSpecInfo &ESI);
6186 
6187   /// Determine if we're in a case where we need to (incorrectly) eagerly
6188   /// parse an exception specification to work around a libstdc++ bug.
6189   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6190 
6191   /// Add an exception-specification to the given member function
6192   /// (or member function template). The exception-specification was parsed
6193   /// after the method itself was declared.
6194   void actOnDelayedExceptionSpecification(Decl *Method,
6195          ExceptionSpecificationType EST,
6196          SourceRange SpecificationRange,
6197          ArrayRef<ParsedType> DynamicExceptions,
6198          ArrayRef<SourceRange> DynamicExceptionRanges,
6199          Expr *NoexceptExpr);
6200 
6201   class InheritedConstructorInfo;
6202 
6203   /// Determine if a special member function should have a deleted
6204   /// definition when it is defaulted.
6205   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6206                                  InheritedConstructorInfo *ICI = nullptr,
6207                                  bool Diagnose = false);
6208 
6209   /// Produce notes explaining why a defaulted function was defined as deleted.
6210   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
6211 
6212   /// Declare the implicit default constructor for the given class.
6213   ///
6214   /// \param ClassDecl The class declaration into which the implicit
6215   /// default constructor will be added.
6216   ///
6217   /// \returns The implicitly-declared default constructor.
6218   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
6219                                                      CXXRecordDecl *ClassDecl);
6220 
6221   /// DefineImplicitDefaultConstructor - Checks for feasibility of
6222   /// defining this constructor as the default constructor.
6223   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6224                                         CXXConstructorDecl *Constructor);
6225 
6226   /// Declare the implicit destructor for the given class.
6227   ///
6228   /// \param ClassDecl The class declaration into which the implicit
6229   /// destructor will be added.
6230   ///
6231   /// \returns The implicitly-declared destructor.
6232   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6233 
6234   /// DefineImplicitDestructor - Checks for feasibility of
6235   /// defining this destructor as the default destructor.
6236   void DefineImplicitDestructor(SourceLocation CurrentLocation,
6237                                 CXXDestructorDecl *Destructor);
6238 
6239   /// Build an exception spec for destructors that don't have one.
6240   ///
6241   /// C++11 says that user-defined destructors with no exception spec get one
6242   /// that looks as if the destructor was implicitly declared.
6243   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6244 
6245   /// Define the specified inheriting constructor.
6246   void DefineInheritingConstructor(SourceLocation UseLoc,
6247                                    CXXConstructorDecl *Constructor);
6248 
6249   /// Declare the implicit copy constructor for the given class.
6250   ///
6251   /// \param ClassDecl The class declaration into which the implicit
6252   /// copy constructor will be added.
6253   ///
6254   /// \returns The implicitly-declared copy constructor.
6255   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6256 
6257   /// DefineImplicitCopyConstructor - Checks for feasibility of
6258   /// defining this constructor as the copy constructor.
6259   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6260                                      CXXConstructorDecl *Constructor);
6261 
6262   /// Declare the implicit move constructor for the given class.
6263   ///
6264   /// \param ClassDecl The Class declaration into which the implicit
6265   /// move constructor will be added.
6266   ///
6267   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6268   /// declared.
6269   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6270 
6271   /// DefineImplicitMoveConstructor - Checks for feasibility of
6272   /// defining this constructor as the move constructor.
6273   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6274                                      CXXConstructorDecl *Constructor);
6275 
6276   /// Declare the implicit copy assignment operator for the given class.
6277   ///
6278   /// \param ClassDecl The class declaration into which the implicit
6279   /// copy assignment operator will be added.
6280   ///
6281   /// \returns The implicitly-declared copy assignment operator.
6282   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6283 
6284   /// Defines an implicitly-declared copy assignment operator.
6285   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6286                                     CXXMethodDecl *MethodDecl);
6287 
6288   /// Declare the implicit move assignment operator for the given class.
6289   ///
6290   /// \param ClassDecl The Class declaration into which the implicit
6291   /// move assignment operator will be added.
6292   ///
6293   /// \returns The implicitly-declared move assignment operator, or NULL if it
6294   /// wasn't declared.
6295   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6296 
6297   /// Defines an implicitly-declared move assignment operator.
6298   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6299                                     CXXMethodDecl *MethodDecl);
6300 
6301   /// Force the declaration of any implicitly-declared members of this
6302   /// class.
6303   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6304 
6305   /// Check a completed declaration of an implicit special member.
6306   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6307 
6308   /// Determine whether the given function is an implicitly-deleted
6309   /// special member function.
6310   bool isImplicitlyDeleted(FunctionDecl *FD);
6311 
6312   /// Check whether 'this' shows up in the type of a static member
6313   /// function after the (naturally empty) cv-qualifier-seq would be.
6314   ///
6315   /// \returns true if an error occurred.
6316   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6317 
6318   /// Whether this' shows up in the exception specification of a static
6319   /// member function.
6320   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6321 
6322   /// Check whether 'this' shows up in the attributes of the given
6323   /// static member function.
6324   ///
6325   /// \returns true if an error occurred.
6326   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6327 
6328   /// MaybeBindToTemporary - If the passed in expression has a record type with
6329   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6330   /// it simply returns the passed in expression.
6331   ExprResult MaybeBindToTemporary(Expr *E);
6332 
6333   /// Wrap the expression in a ConstantExpr if it is a potential immediate
6334   /// invocation.
6335   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6336 
6337   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6338                                QualType DeclInitType, MultiExprArg ArgsPtr,
6339                                SourceLocation Loc,
6340                                SmallVectorImpl<Expr *> &ConvertedArgs,
6341                                bool AllowExplicit = false,
6342                                bool IsListInitialization = false);
6343 
6344   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6345                                           SourceLocation NameLoc,
6346                                           IdentifierInfo &Name);
6347 
6348   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6349                                 Scope *S, CXXScopeSpec &SS,
6350                                 bool EnteringContext);
6351   ParsedType getDestructorName(SourceLocation TildeLoc,
6352                                IdentifierInfo &II, SourceLocation NameLoc,
6353                                Scope *S, CXXScopeSpec &SS,
6354                                ParsedType ObjectType,
6355                                bool EnteringContext);
6356 
6357   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6358                                           ParsedType ObjectType);
6359 
6360   // Checks that reinterpret casts don't have undefined behavior.
6361   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6362                                       bool IsDereference, SourceRange Range);
6363 
6364   // Checks that the vector type should be initialized from a scalar
6365   // by splatting the value rather than populating a single element.
6366   // This is the case for AltiVecVector types as well as with
6367   // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6368   bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6369 
6370   // Checks if the -faltivec-src-compat=gcc option is specified.
6371   // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6372   // treated the same way as they are when trying to initialize
6373   // these vectors on gcc (an error is emitted).
6374   bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6375                                   QualType SrcTy);
6376 
6377   /// ActOnCXXNamedCast - Parse
6378   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6379   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6380                                tok::TokenKind Kind,
6381                                SourceLocation LAngleBracketLoc,
6382                                Declarator &D,
6383                                SourceLocation RAngleBracketLoc,
6384                                SourceLocation LParenLoc,
6385                                Expr *E,
6386                                SourceLocation RParenLoc);
6387 
6388   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6389                                tok::TokenKind Kind,
6390                                TypeSourceInfo *Ty,
6391                                Expr *E,
6392                                SourceRange AngleBrackets,
6393                                SourceRange Parens);
6394 
6395   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6396                                      ExprResult Operand,
6397                                      SourceLocation RParenLoc);
6398 
6399   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6400                                      Expr *Operand, SourceLocation RParenLoc);
6401 
6402   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6403                             SourceLocation TypeidLoc,
6404                             TypeSourceInfo *Operand,
6405                             SourceLocation RParenLoc);
6406   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6407                             SourceLocation TypeidLoc,
6408                             Expr *Operand,
6409                             SourceLocation RParenLoc);
6410 
6411   /// ActOnCXXTypeid - Parse typeid( something ).
6412   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6413                             SourceLocation LParenLoc, bool isType,
6414                             void *TyOrExpr,
6415                             SourceLocation RParenLoc);
6416 
6417   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6418                             SourceLocation TypeidLoc,
6419                             TypeSourceInfo *Operand,
6420                             SourceLocation RParenLoc);
6421   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6422                             SourceLocation TypeidLoc,
6423                             Expr *Operand,
6424                             SourceLocation RParenLoc);
6425 
6426   /// ActOnCXXUuidof - Parse __uuidof( something ).
6427   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6428                             SourceLocation LParenLoc, bool isType,
6429                             void *TyOrExpr,
6430                             SourceLocation RParenLoc);
6431 
6432   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6433   ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6434                               tok::TokenKind Operator,
6435                               SourceLocation EllipsisLoc, Expr *RHS,
6436                               SourceLocation RParenLoc);
6437   ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6438                               SourceLocation LParenLoc, Expr *LHS,
6439                               BinaryOperatorKind Operator,
6440                               SourceLocation EllipsisLoc, Expr *RHS,
6441                               SourceLocation RParenLoc,
6442                               Optional<unsigned> NumExpansions);
6443   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6444                                    BinaryOperatorKind Operator);
6445 
6446   //// ActOnCXXThis -  Parse 'this' pointer.
6447   ExprResult ActOnCXXThis(SourceLocation loc);
6448 
6449   /// Build a CXXThisExpr and mark it referenced in the current context.
6450   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6451   void MarkThisReferenced(CXXThisExpr *This);
6452 
6453   /// Try to retrieve the type of the 'this' pointer.
6454   ///
6455   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6456   QualType getCurrentThisType();
6457 
6458   /// When non-NULL, the C++ 'this' expression is allowed despite the
6459   /// current context not being a non-static member function. In such cases,
6460   /// this provides the type used for 'this'.
6461   QualType CXXThisTypeOverride;
6462 
6463   /// RAII object used to temporarily allow the C++ 'this' expression
6464   /// to be used, with the given qualifiers on the current class type.
6465   class CXXThisScopeRAII {
6466     Sema &S;
6467     QualType OldCXXThisTypeOverride;
6468     bool Enabled;
6469 
6470   public:
6471     /// Introduce a new scope where 'this' may be allowed (when enabled),
6472     /// using the given declaration (which is either a class template or a
6473     /// class) along with the given qualifiers.
6474     /// along with the qualifiers placed on '*this'.
6475     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6476                      bool Enabled = true);
6477 
6478     ~CXXThisScopeRAII();
6479   };
6480 
6481   /// Make sure the value of 'this' is actually available in the current
6482   /// context, if it is a potentially evaluated context.
6483   ///
6484   /// \param Loc The location at which the capture of 'this' occurs.
6485   ///
6486   /// \param Explicit Whether 'this' is explicitly captured in a lambda
6487   /// capture list.
6488   ///
6489   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6490   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6491   /// This is useful when enclosing lambdas must speculatively capture
6492   /// 'this' that may or may not be used in certain specializations of
6493   /// a nested generic lambda (depending on whether the name resolves to
6494   /// a non-static member function or a static function).
6495   /// \return returns 'true' if failed, 'false' if success.
6496   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6497       bool BuildAndDiagnose = true,
6498       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6499       bool ByCopy = false);
6500 
6501   /// Determine whether the given type is the type of *this that is used
6502   /// outside of the body of a member function for a type that is currently
6503   /// being defined.
6504   bool isThisOutsideMemberFunctionBody(QualType BaseType);
6505 
6506   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6507   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6508 
6509 
6510   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6511   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6512 
6513   ExprResult
6514   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6515                                  SourceLocation AtLoc, SourceLocation RParen);
6516 
6517   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6518   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6519 
6520   //// ActOnCXXThrow -  Parse throw expressions.
6521   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6522   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6523                            bool IsThrownVarInScope);
6524   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6525 
6526   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6527   /// Can be interpreted either as function-style casting ("int(x)")
6528   /// or class type construction ("ClassType(x,y,z)")
6529   /// or creation of a value-initialized type ("int()").
6530   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6531                                        SourceLocation LParenOrBraceLoc,
6532                                        MultiExprArg Exprs,
6533                                        SourceLocation RParenOrBraceLoc,
6534                                        bool ListInitialization);
6535 
6536   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6537                                        SourceLocation LParenLoc,
6538                                        MultiExprArg Exprs,
6539                                        SourceLocation RParenLoc,
6540                                        bool ListInitialization);
6541 
6542   /// ActOnCXXNew - Parsed a C++ 'new' expression.
6543   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6544                          SourceLocation PlacementLParen,
6545                          MultiExprArg PlacementArgs,
6546                          SourceLocation PlacementRParen,
6547                          SourceRange TypeIdParens, Declarator &D,
6548                          Expr *Initializer);
6549   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6550                          SourceLocation PlacementLParen,
6551                          MultiExprArg PlacementArgs,
6552                          SourceLocation PlacementRParen,
6553                          SourceRange TypeIdParens,
6554                          QualType AllocType,
6555                          TypeSourceInfo *AllocTypeInfo,
6556                          Optional<Expr *> ArraySize,
6557                          SourceRange DirectInitRange,
6558                          Expr *Initializer);
6559 
6560   /// Determine whether \p FD is an aligned allocation or deallocation
6561   /// function that is unavailable.
6562   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6563 
6564   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6565   /// function that is unavailable.
6566   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6567                                             SourceLocation Loc);
6568 
6569   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6570                           SourceRange R);
6571 
6572   /// The scope in which to find allocation functions.
6573   enum AllocationFunctionScope {
6574     /// Only look for allocation functions in the global scope.
6575     AFS_Global,
6576     /// Only look for allocation functions in the scope of the
6577     /// allocated class.
6578     AFS_Class,
6579     /// Look for allocation functions in both the global scope
6580     /// and in the scope of the allocated class.
6581     AFS_Both
6582   };
6583 
6584   /// Finds the overloads of operator new and delete that are appropriate
6585   /// for the allocation.
6586   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6587                                AllocationFunctionScope NewScope,
6588                                AllocationFunctionScope DeleteScope,
6589                                QualType AllocType, bool IsArray,
6590                                bool &PassAlignment, MultiExprArg PlaceArgs,
6591                                FunctionDecl *&OperatorNew,
6592                                FunctionDecl *&OperatorDelete,
6593                                bool Diagnose = true);
6594   void DeclareGlobalNewDelete();
6595   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6596                                        ArrayRef<QualType> Params);
6597 
6598   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6599                                 DeclarationName Name, FunctionDecl* &Operator,
6600                                 bool Diagnose = true);
6601   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6602                                               bool CanProvideSize,
6603                                               bool Overaligned,
6604                                               DeclarationName Name);
6605   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6606                                                       CXXRecordDecl *RD);
6607 
6608   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6609   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6610                             bool UseGlobal, bool ArrayForm,
6611                             Expr *Operand);
6612   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6613                             bool IsDelete, bool CallCanBeVirtual,
6614                             bool WarnOnNonAbstractTypes,
6615                             SourceLocation DtorLoc);
6616 
6617   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6618                                Expr *Operand, SourceLocation RParen);
6619   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6620                                   SourceLocation RParen);
6621 
6622   /// Parsed one of the type trait support pseudo-functions.
6623   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6624                             ArrayRef<ParsedType> Args,
6625                             SourceLocation RParenLoc);
6626   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6627                             ArrayRef<TypeSourceInfo *> Args,
6628                             SourceLocation RParenLoc);
6629 
6630   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6631   /// pseudo-functions.
6632   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6633                                  SourceLocation KWLoc,
6634                                  ParsedType LhsTy,
6635                                  Expr *DimExpr,
6636                                  SourceLocation RParen);
6637 
6638   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6639                                  SourceLocation KWLoc,
6640                                  TypeSourceInfo *TSInfo,
6641                                  Expr *DimExpr,
6642                                  SourceLocation RParen);
6643 
6644   /// ActOnExpressionTrait - Parsed one of the unary type trait support
6645   /// pseudo-functions.
6646   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6647                                   SourceLocation KWLoc,
6648                                   Expr *Queried,
6649                                   SourceLocation RParen);
6650 
6651   ExprResult BuildExpressionTrait(ExpressionTrait OET,
6652                                   SourceLocation KWLoc,
6653                                   Expr *Queried,
6654                                   SourceLocation RParen);
6655 
6656   ExprResult ActOnStartCXXMemberReference(Scope *S,
6657                                           Expr *Base,
6658                                           SourceLocation OpLoc,
6659                                           tok::TokenKind OpKind,
6660                                           ParsedType &ObjectType,
6661                                           bool &MayBePseudoDestructor);
6662 
6663   ExprResult BuildPseudoDestructorExpr(Expr *Base,
6664                                        SourceLocation OpLoc,
6665                                        tok::TokenKind OpKind,
6666                                        const CXXScopeSpec &SS,
6667                                        TypeSourceInfo *ScopeType,
6668                                        SourceLocation CCLoc,
6669                                        SourceLocation TildeLoc,
6670                                      PseudoDestructorTypeStorage DestroyedType);
6671 
6672   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6673                                        SourceLocation OpLoc,
6674                                        tok::TokenKind OpKind,
6675                                        CXXScopeSpec &SS,
6676                                        UnqualifiedId &FirstTypeName,
6677                                        SourceLocation CCLoc,
6678                                        SourceLocation TildeLoc,
6679                                        UnqualifiedId &SecondTypeName);
6680 
6681   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6682                                        SourceLocation OpLoc,
6683                                        tok::TokenKind OpKind,
6684                                        SourceLocation TildeLoc,
6685                                        const DeclSpec& DS);
6686 
6687   /// MaybeCreateExprWithCleanups - If the current full-expression
6688   /// requires any cleanups, surround it with a ExprWithCleanups node.
6689   /// Otherwise, just returns the passed-in expression.
6690   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6691   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6692   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6693 
6694   MaterializeTemporaryExpr *
6695   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6696                                  bool BoundToLvalueReference);
6697 
6698   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6699     return ActOnFinishFullExpr(
6700         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6701   }
6702   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6703                                  bool DiscardedValue, bool IsConstexpr = false);
6704   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6705 
6706   // Marks SS invalid if it represents an incomplete type.
6707   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6708   // Complete an enum decl, maybe without a scope spec.
6709   bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6710                                CXXScopeSpec *SS = nullptr);
6711 
6712   DeclContext *computeDeclContext(QualType T);
6713   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6714                                   bool EnteringContext = false);
6715   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6716   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6717 
6718   /// The parser has parsed a global nested-name-specifier '::'.
6719   ///
6720   /// \param CCLoc The location of the '::'.
6721   ///
6722   /// \param SS The nested-name-specifier, which will be updated in-place
6723   /// to reflect the parsed nested-name-specifier.
6724   ///
6725   /// \returns true if an error occurred, false otherwise.
6726   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6727 
6728   /// The parser has parsed a '__super' nested-name-specifier.
6729   ///
6730   /// \param SuperLoc The location of the '__super' keyword.
6731   ///
6732   /// \param ColonColonLoc The location of the '::'.
6733   ///
6734   /// \param SS The nested-name-specifier, which will be updated in-place
6735   /// to reflect the parsed nested-name-specifier.
6736   ///
6737   /// \returns true if an error occurred, false otherwise.
6738   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6739                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6740 
6741   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6742                                        bool *CanCorrect = nullptr);
6743   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6744 
6745   /// Keeps information about an identifier in a nested-name-spec.
6746   ///
6747   struct NestedNameSpecInfo {
6748     /// The type of the object, if we're parsing nested-name-specifier in
6749     /// a member access expression.
6750     ParsedType ObjectType;
6751 
6752     /// The identifier preceding the '::'.
6753     IdentifierInfo *Identifier;
6754 
6755     /// The location of the identifier.
6756     SourceLocation IdentifierLoc;
6757 
6758     /// The location of the '::'.
6759     SourceLocation CCLoc;
6760 
6761     /// Creates info object for the most typical case.
6762     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6763              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6764       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6765         CCLoc(ColonColonLoc) {
6766     }
6767 
6768     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6769                        SourceLocation ColonColonLoc, QualType ObjectType)
6770       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6771         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6772     }
6773   };
6774 
6775   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6776                                     NestedNameSpecInfo &IdInfo);
6777 
6778   bool BuildCXXNestedNameSpecifier(Scope *S,
6779                                    NestedNameSpecInfo &IdInfo,
6780                                    bool EnteringContext,
6781                                    CXXScopeSpec &SS,
6782                                    NamedDecl *ScopeLookupResult,
6783                                    bool ErrorRecoveryLookup,
6784                                    bool *IsCorrectedToColon = nullptr,
6785                                    bool OnlyNamespace = false);
6786 
6787   /// The parser has parsed a nested-name-specifier 'identifier::'.
6788   ///
6789   /// \param S The scope in which this nested-name-specifier occurs.
6790   ///
6791   /// \param IdInfo Parser information about an identifier in the
6792   /// nested-name-spec.
6793   ///
6794   /// \param EnteringContext Whether we're entering the context nominated by
6795   /// this nested-name-specifier.
6796   ///
6797   /// \param SS The nested-name-specifier, which is both an input
6798   /// parameter (the nested-name-specifier before this type) and an
6799   /// output parameter (containing the full nested-name-specifier,
6800   /// including this new type).
6801   ///
6802   /// \param ErrorRecoveryLookup If true, then this method is called to improve
6803   /// error recovery. In this case do not emit error message.
6804   ///
6805   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6806   /// are allowed.  The bool value pointed by this parameter is set to 'true'
6807   /// if the identifier is treated as if it was followed by ':', not '::'.
6808   ///
6809   /// \param OnlyNamespace If true, only considers namespaces in lookup.
6810   ///
6811   /// \returns true if an error occurred, false otherwise.
6812   bool ActOnCXXNestedNameSpecifier(Scope *S,
6813                                    NestedNameSpecInfo &IdInfo,
6814                                    bool EnteringContext,
6815                                    CXXScopeSpec &SS,
6816                                    bool *IsCorrectedToColon = nullptr,
6817                                    bool OnlyNamespace = false);
6818 
6819   ExprResult ActOnDecltypeExpression(Expr *E);
6820 
6821   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6822                                            const DeclSpec &DS,
6823                                            SourceLocation ColonColonLoc);
6824 
6825   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6826                                  NestedNameSpecInfo &IdInfo,
6827                                  bool EnteringContext);
6828 
6829   /// The parser has parsed a nested-name-specifier
6830   /// 'template[opt] template-name < template-args >::'.
6831   ///
6832   /// \param S The scope in which this nested-name-specifier occurs.
6833   ///
6834   /// \param SS The nested-name-specifier, which is both an input
6835   /// parameter (the nested-name-specifier before this type) and an
6836   /// output parameter (containing the full nested-name-specifier,
6837   /// including this new type).
6838   ///
6839   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6840   /// \param TemplateName the template name.
6841   /// \param TemplateNameLoc The location of the template name.
6842   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6843   /// \param TemplateArgs The template arguments.
6844   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6845   /// \param CCLoc The location of the '::'.
6846   ///
6847   /// \param EnteringContext Whether we're entering the context of the
6848   /// nested-name-specifier.
6849   ///
6850   ///
6851   /// \returns true if an error occurred, false otherwise.
6852   bool ActOnCXXNestedNameSpecifier(Scope *S,
6853                                    CXXScopeSpec &SS,
6854                                    SourceLocation TemplateKWLoc,
6855                                    TemplateTy TemplateName,
6856                                    SourceLocation TemplateNameLoc,
6857                                    SourceLocation LAngleLoc,
6858                                    ASTTemplateArgsPtr TemplateArgs,
6859                                    SourceLocation RAngleLoc,
6860                                    SourceLocation CCLoc,
6861                                    bool EnteringContext);
6862 
6863   /// Given a C++ nested-name-specifier, produce an annotation value
6864   /// that the parser can use later to reconstruct the given
6865   /// nested-name-specifier.
6866   ///
6867   /// \param SS A nested-name-specifier.
6868   ///
6869   /// \returns A pointer containing all of the information in the
6870   /// nested-name-specifier \p SS.
6871   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6872 
6873   /// Given an annotation pointer for a nested-name-specifier, restore
6874   /// the nested-name-specifier structure.
6875   ///
6876   /// \param Annotation The annotation pointer, produced by
6877   /// \c SaveNestedNameSpecifierAnnotation().
6878   ///
6879   /// \param AnnotationRange The source range corresponding to the annotation.
6880   ///
6881   /// \param SS The nested-name-specifier that will be updated with the contents
6882   /// of the annotation pointer.
6883   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6884                                             SourceRange AnnotationRange,
6885                                             CXXScopeSpec &SS);
6886 
6887   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6888 
6889   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6890   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6891   /// After this method is called, according to [C++ 3.4.3p3], names should be
6892   /// looked up in the declarator-id's scope, until the declarator is parsed and
6893   /// ActOnCXXExitDeclaratorScope is called.
6894   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6895   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6896 
6897   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6898   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6899   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6900   /// Used to indicate that names should revert to being looked up in the
6901   /// defining scope.
6902   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6903 
6904   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6905   /// initializer for the declaration 'Dcl'.
6906   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6907   /// static data member of class X, names should be looked up in the scope of
6908   /// class X.
6909   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6910 
6911   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6912   /// initializer for the declaration 'Dcl'.
6913   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6914 
6915   /// Create a new lambda closure type.
6916   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6917                                          TypeSourceInfo *Info,
6918                                          unsigned LambdaDependencyKind,
6919                                          LambdaCaptureDefault CaptureDefault);
6920 
6921   /// Start the definition of a lambda expression.
6922   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6923                                        SourceRange IntroducerRange,
6924                                        TypeSourceInfo *MethodType,
6925                                        SourceLocation EndLoc,
6926                                        ArrayRef<ParmVarDecl *> Params,
6927                                        ConstexprSpecKind ConstexprKind,
6928                                        Expr *TrailingRequiresClause);
6929 
6930   /// Number lambda for linkage purposes if necessary.
6931   void handleLambdaNumbering(
6932       CXXRecordDecl *Class, CXXMethodDecl *Method,
6933       Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
6934 
6935   /// Endow the lambda scope info with the relevant properties.
6936   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6937                         CXXMethodDecl *CallOperator,
6938                         SourceRange IntroducerRange,
6939                         LambdaCaptureDefault CaptureDefault,
6940                         SourceLocation CaptureDefaultLoc,
6941                         bool ExplicitParams,
6942                         bool ExplicitResultType,
6943                         bool Mutable);
6944 
6945   /// Perform initialization analysis of the init-capture and perform
6946   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6947   /// not being used to initialize a reference.
6948   ParsedType actOnLambdaInitCaptureInitialization(
6949       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6950       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6951     return ParsedType::make(buildLambdaInitCaptureInitialization(
6952         Loc, ByRef, EllipsisLoc, None, Id,
6953         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6954   }
6955   QualType buildLambdaInitCaptureInitialization(
6956       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6957       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6958       Expr *&Init);
6959 
6960   /// Create a dummy variable within the declcontext of the lambda's
6961   ///  call operator, for name lookup purposes for a lambda init capture.
6962   ///
6963   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6964   ///  variables appropriately.
6965   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6966                                           QualType InitCaptureType,
6967                                           SourceLocation EllipsisLoc,
6968                                           IdentifierInfo *Id,
6969                                           unsigned InitStyle, Expr *Init);
6970 
6971   /// Add an init-capture to a lambda scope.
6972   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6973 
6974   /// Note that we have finished the explicit captures for the
6975   /// given lambda.
6976   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6977 
6978   /// \brief This is called after parsing the explicit template parameter list
6979   /// on a lambda (if it exists) in C++2a.
6980   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6981                                                 ArrayRef<NamedDecl *> TParams,
6982                                                 SourceLocation RAngleLoc,
6983                                                 ExprResult RequiresClause);
6984 
6985   /// Introduce the lambda parameters into scope.
6986   void addLambdaParameters(
6987       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6988       CXXMethodDecl *CallOperator, Scope *CurScope);
6989 
6990   /// Deduce a block or lambda's return type based on the return
6991   /// statements present in the body.
6992   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6993 
6994   /// ActOnStartOfLambdaDefinition - This is called just before we start
6995   /// parsing the body of a lambda; it analyzes the explicit captures and
6996   /// arguments, and sets up various data-structures for the body of the
6997   /// lambda.
6998   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6999                                     Declarator &ParamInfo, Scope *CurScope);
7000 
7001   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
7002   /// is invoked to pop the information about the lambda.
7003   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
7004                         bool IsInstantiation = false);
7005 
7006   /// ActOnLambdaExpr - This is called when the body of a lambda expression
7007   /// was successfully completed.
7008   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
7009                              Scope *CurScope);
7010 
7011   /// Does copying/destroying the captured variable have side effects?
7012   bool CaptureHasSideEffects(const sema::Capture &From);
7013 
7014   /// Diagnose if an explicit lambda capture is unused. Returns true if a
7015   /// diagnostic is emitted.
7016   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
7017                                    const sema::Capture &From);
7018 
7019   /// Build a FieldDecl suitable to hold the given capture.
7020   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
7021 
7022   /// Initialize the given capture with a suitable expression.
7023   ExprResult BuildCaptureInit(const sema::Capture &Capture,
7024                               SourceLocation ImplicitCaptureLoc,
7025                               bool IsOpenMPMapping = false);
7026 
7027   /// Complete a lambda-expression having processed and attached the
7028   /// lambda body.
7029   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
7030                              sema::LambdaScopeInfo *LSI);
7031 
7032   /// Get the return type to use for a lambda's conversion function(s) to
7033   /// function pointer type, given the type of the call operator.
7034   QualType
7035   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
7036                                         CallingConv CC);
7037 
7038   /// Define the "body" of the conversion from a lambda object to a
7039   /// function pointer.
7040   ///
7041   /// This routine doesn't actually define a sensible body; rather, it fills
7042   /// in the initialization expression needed to copy the lambda object into
7043   /// the block, and IR generation actually generates the real body of the
7044   /// block pointer conversion.
7045   void DefineImplicitLambdaToFunctionPointerConversion(
7046          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
7047 
7048   /// Define the "body" of the conversion from a lambda object to a
7049   /// block pointer.
7050   ///
7051   /// This routine doesn't actually define a sensible body; rather, it fills
7052   /// in the initialization expression needed to copy the lambda object into
7053   /// the block, and IR generation actually generates the real body of the
7054   /// block pointer conversion.
7055   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
7056                                                     CXXConversionDecl *Conv);
7057 
7058   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
7059                                            SourceLocation ConvLocation,
7060                                            CXXConversionDecl *Conv,
7061                                            Expr *Src);
7062 
7063   /// Check whether the given expression is a valid constraint expression.
7064   /// A diagnostic is emitted if it is not, false is returned, and
7065   /// PossibleNonPrimary will be set to true if the failure might be due to a
7066   /// non-primary expression being used as an atomic constraint.
7067   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
7068                                  bool *PossibleNonPrimary = nullptr,
7069                                  bool IsTrailingRequiresClause = false);
7070 
7071 private:
7072   /// Caches pairs of template-like decls whose associated constraints were
7073   /// checked for subsumption and whether or not the first's constraints did in
7074   /// fact subsume the second's.
7075   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
7076   /// Caches the normalized associated constraints of declarations (concepts or
7077   /// constrained declarations). If an error occurred while normalizing the
7078   /// associated constraints of the template or concept, nullptr will be cached
7079   /// here.
7080   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
7081       NormalizationCache;
7082 
7083   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
7084       SatisfactionCache;
7085 
7086   /// Introduce the instantiated function parameters into the local
7087   /// instantiation scope, and set the parameter names to those used
7088   /// in the template.
7089   bool addInstantiatedParametersToScope(
7090       FunctionDecl *Function, const FunctionDecl *PatternDecl,
7091       LocalInstantiationScope &Scope,
7092       const MultiLevelTemplateArgumentList &TemplateArgs);
7093 
7094 public:
7095   const NormalizedConstraint *
7096   getNormalizedAssociatedConstraints(
7097       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
7098 
7099   /// \brief Check whether the given declaration's associated constraints are
7100   /// at least as constrained than another declaration's according to the
7101   /// partial ordering of constraints.
7102   ///
7103   /// \param Result If no error occurred, receives the result of true if D1 is
7104   /// at least constrained than D2, and false otherwise.
7105   ///
7106   /// \returns true if an error occurred, false otherwise.
7107   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
7108                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
7109                               bool &Result);
7110 
7111   /// If D1 was not at least as constrained as D2, but would've been if a pair
7112   /// of atomic constraints involved had been declared in a concept and not
7113   /// repeated in two separate places in code.
7114   /// \returns true if such a diagnostic was emitted, false otherwise.
7115   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
7116       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
7117 
7118   /// \brief Check whether the given list of constraint expressions are
7119   /// satisfied (as if in a 'conjunction') given template arguments.
7120   /// \param Template the template-like entity that triggered the constraints
7121   /// check (either a concept or a constrained entity).
7122   /// \param ConstraintExprs a list of constraint expressions, treated as if
7123   /// they were 'AND'ed together.
7124   /// \param TemplateArgs the list of template arguments to substitute into the
7125   /// constraint expression.
7126   /// \param TemplateIDRange The source range of the template id that
7127   /// caused the constraints check.
7128   /// \param Satisfaction if true is returned, will contain details of the
7129   /// satisfaction, with enough information to diagnose an unsatisfied
7130   /// expression.
7131   /// \returns true if an error occurred and satisfaction could not be checked,
7132   /// false otherwise.
7133   bool CheckConstraintSatisfaction(
7134       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7135       ArrayRef<TemplateArgument> TemplateArgs,
7136       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
7137 
7138   /// \brief Check whether the given non-dependent constraint expression is
7139   /// satisfied. Returns false and updates Satisfaction with the satisfaction
7140   /// verdict if successful, emits a diagnostic and returns true if an error
7141   /// occurred and satisfaction could not be determined.
7142   ///
7143   /// \returns true if an error occurred, false otherwise.
7144   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
7145                                    ConstraintSatisfaction &Satisfaction);
7146 
7147   /// Check whether the given function decl's trailing requires clause is
7148   /// satisfied, if any. Returns false and updates Satisfaction with the
7149   /// satisfaction verdict if successful, emits a diagnostic and returns true if
7150   /// an error occurred and satisfaction could not be determined.
7151   ///
7152   /// \returns true if an error occurred, false otherwise.
7153   bool CheckFunctionConstraints(const FunctionDecl *FD,
7154                                 ConstraintSatisfaction &Satisfaction,
7155                                 SourceLocation UsageLoc = SourceLocation());
7156 
7157 
7158   /// \brief Ensure that the given template arguments satisfy the constraints
7159   /// associated with the given template, emitting a diagnostic if they do not.
7160   ///
7161   /// \param Template The template to which the template arguments are being
7162   /// provided.
7163   ///
7164   /// \param TemplateArgs The converted, canonicalized template arguments.
7165   ///
7166   /// \param TemplateIDRange The source range of the template id that
7167   /// caused the constraints check.
7168   ///
7169   /// \returns true if the constrains are not satisfied or could not be checked
7170   /// for satisfaction, false if the constraints are satisfied.
7171   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
7172                                        ArrayRef<TemplateArgument> TemplateArgs,
7173                                              SourceRange TemplateIDRange);
7174 
7175   /// \brief Emit diagnostics explaining why a constraint expression was deemed
7176   /// unsatisfied.
7177   /// \param First whether this is the first time an unsatisfied constraint is
7178   /// diagnosed for this error.
7179   void
7180   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
7181                                 bool First = true);
7182 
7183   /// \brief Emit diagnostics explaining why a constraint expression was deemed
7184   /// unsatisfied.
7185   void
7186   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
7187                                 bool First = true);
7188 
7189   // ParseObjCStringLiteral - Parse Objective-C string literals.
7190   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
7191                                     ArrayRef<Expr *> Strings);
7192 
7193   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
7194 
7195   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
7196   /// numeric literal expression. Type of the expression will be "NSNumber *"
7197   /// or "id" if NSNumber is unavailable.
7198   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
7199   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
7200                                   bool Value);
7201   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
7202 
7203   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
7204   /// '@' prefixed parenthesized expression. The type of the expression will
7205   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
7206   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
7207   /// "const char *" or C structure with attribute 'objc_boxable'.
7208   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
7209 
7210   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
7211                                           Expr *IndexExpr,
7212                                           ObjCMethodDecl *getterMethod,
7213                                           ObjCMethodDecl *setterMethod);
7214 
7215   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
7216                                MutableArrayRef<ObjCDictionaryElement> Elements);
7217 
7218   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
7219                                   TypeSourceInfo *EncodedTypeInfo,
7220                                   SourceLocation RParenLoc);
7221   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
7222                                     CXXConversionDecl *Method,
7223                                     bool HadMultipleCandidates);
7224 
7225   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
7226                                        SourceLocation EncodeLoc,
7227                                        SourceLocation LParenLoc,
7228                                        ParsedType Ty,
7229                                        SourceLocation RParenLoc);
7230 
7231   /// ParseObjCSelectorExpression - Build selector expression for \@selector
7232   ExprResult ParseObjCSelectorExpression(Selector Sel,
7233                                          SourceLocation AtLoc,
7234                                          SourceLocation SelLoc,
7235                                          SourceLocation LParenLoc,
7236                                          SourceLocation RParenLoc,
7237                                          bool WarnMultipleSelectors);
7238 
7239   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7240   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7241                                          SourceLocation AtLoc,
7242                                          SourceLocation ProtoLoc,
7243                                          SourceLocation LParenLoc,
7244                                          SourceLocation ProtoIdLoc,
7245                                          SourceLocation RParenLoc);
7246 
7247   //===--------------------------------------------------------------------===//
7248   // C++ Declarations
7249   //
7250   Decl *ActOnStartLinkageSpecification(Scope *S,
7251                                        SourceLocation ExternLoc,
7252                                        Expr *LangStr,
7253                                        SourceLocation LBraceLoc);
7254   Decl *ActOnFinishLinkageSpecification(Scope *S,
7255                                         Decl *LinkageSpec,
7256                                         SourceLocation RBraceLoc);
7257 
7258 
7259   //===--------------------------------------------------------------------===//
7260   // C++ Classes
7261   //
7262   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7263   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7264                           const CXXScopeSpec *SS = nullptr);
7265   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7266 
7267   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7268                             SourceLocation ColonLoc,
7269                             const ParsedAttributesView &Attrs);
7270 
7271   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7272                                  Declarator &D,
7273                                  MultiTemplateParamsArg TemplateParameterLists,
7274                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
7275                                  InClassInitStyle InitStyle);
7276 
7277   void ActOnStartCXXInClassMemberInitializer();
7278   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7279                                               SourceLocation EqualLoc,
7280                                               Expr *Init);
7281 
7282   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7283                                     Scope *S,
7284                                     CXXScopeSpec &SS,
7285                                     IdentifierInfo *MemberOrBase,
7286                                     ParsedType TemplateTypeTy,
7287                                     const DeclSpec &DS,
7288                                     SourceLocation IdLoc,
7289                                     SourceLocation LParenLoc,
7290                                     ArrayRef<Expr *> Args,
7291                                     SourceLocation RParenLoc,
7292                                     SourceLocation EllipsisLoc);
7293 
7294   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7295                                     Scope *S,
7296                                     CXXScopeSpec &SS,
7297                                     IdentifierInfo *MemberOrBase,
7298                                     ParsedType TemplateTypeTy,
7299                                     const DeclSpec &DS,
7300                                     SourceLocation IdLoc,
7301                                     Expr *InitList,
7302                                     SourceLocation EllipsisLoc);
7303 
7304   MemInitResult BuildMemInitializer(Decl *ConstructorD,
7305                                     Scope *S,
7306                                     CXXScopeSpec &SS,
7307                                     IdentifierInfo *MemberOrBase,
7308                                     ParsedType TemplateTypeTy,
7309                                     const DeclSpec &DS,
7310                                     SourceLocation IdLoc,
7311                                     Expr *Init,
7312                                     SourceLocation EllipsisLoc);
7313 
7314   MemInitResult BuildMemberInitializer(ValueDecl *Member,
7315                                        Expr *Init,
7316                                        SourceLocation IdLoc);
7317 
7318   MemInitResult BuildBaseInitializer(QualType BaseType,
7319                                      TypeSourceInfo *BaseTInfo,
7320                                      Expr *Init,
7321                                      CXXRecordDecl *ClassDecl,
7322                                      SourceLocation EllipsisLoc);
7323 
7324   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7325                                            Expr *Init,
7326                                            CXXRecordDecl *ClassDecl);
7327 
7328   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7329                                 CXXCtorInitializer *Initializer);
7330 
7331   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
7332                            ArrayRef<CXXCtorInitializer *> Initializers = None);
7333 
7334   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7335 
7336 
7337   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7338   /// mark all the non-trivial destructors of its members and bases as
7339   /// referenced.
7340   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7341                                               CXXRecordDecl *Record);
7342 
7343   /// Mark destructors of virtual bases of this class referenced. In the Itanium
7344   /// C++ ABI, this is done when emitting a destructor for any non-abstract
7345   /// class. In the Microsoft C++ ABI, this is done any time a class's
7346   /// destructor is referenced.
7347   void MarkVirtualBaseDestructorsReferenced(
7348       SourceLocation Location, CXXRecordDecl *ClassDecl,
7349       llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7350 
7351   /// Do semantic checks to allow the complete destructor variant to be emitted
7352   /// when the destructor is defined in another translation unit. In the Itanium
7353   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7354   /// can be emitted in separate TUs. To emit the complete variant, run a subset
7355   /// of the checks performed when emitting a regular destructor.
7356   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7357                                       CXXDestructorDecl *Dtor);
7358 
7359   /// The list of classes whose vtables have been used within
7360   /// this translation unit, and the source locations at which the
7361   /// first use occurred.
7362   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7363 
7364   /// The list of vtables that are required but have not yet been
7365   /// materialized.
7366   SmallVector<VTableUse, 16> VTableUses;
7367 
7368   /// The set of classes whose vtables have been used within
7369   /// this translation unit, and a bit that will be true if the vtable is
7370   /// required to be emitted (otherwise, it should be emitted only if needed
7371   /// by code generation).
7372   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7373 
7374   /// Load any externally-stored vtable uses.
7375   void LoadExternalVTableUses();
7376 
7377   /// Note that the vtable for the given class was used at the
7378   /// given location.
7379   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7380                       bool DefinitionRequired = false);
7381 
7382   /// Mark the exception specifications of all virtual member functions
7383   /// in the given class as needed.
7384   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7385                                              const CXXRecordDecl *RD);
7386 
7387   /// MarkVirtualMembersReferenced - Will mark all members of the given
7388   /// CXXRecordDecl referenced.
7389   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7390                                     bool ConstexprOnly = false);
7391 
7392   /// Define all of the vtables that have been used in this
7393   /// translation unit and reference any virtual members used by those
7394   /// vtables.
7395   ///
7396   /// \returns true if any work was done, false otherwise.
7397   bool DefineUsedVTables();
7398 
7399   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7400 
7401   void ActOnMemInitializers(Decl *ConstructorDecl,
7402                             SourceLocation ColonLoc,
7403                             ArrayRef<CXXCtorInitializer*> MemInits,
7404                             bool AnyErrors);
7405 
7406   /// Check class-level dllimport/dllexport attribute. The caller must
7407   /// ensure that referenceDLLExportedClassMethods is called some point later
7408   /// when all outer classes of Class are complete.
7409   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7410   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7411 
7412   void referenceDLLExportedClassMethods();
7413 
7414   void propagateDLLAttrToBaseClassTemplate(
7415       CXXRecordDecl *Class, Attr *ClassAttr,
7416       ClassTemplateSpecializationDecl *BaseTemplateSpec,
7417       SourceLocation BaseLoc);
7418 
7419   /// Add gsl::Pointer attribute to std::container::iterator
7420   /// \param ND The declaration that introduces the name
7421   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7422   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7423 
7424   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7425   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7426 
7427   /// Add [[gsl::Pointer]] attributes for std:: types.
7428   void inferGslPointerAttribute(TypedefNameDecl *TD);
7429 
7430   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7431 
7432   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7433   /// conditions that are needed for the attribute to have an effect.
7434   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7435 
7436   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7437                                          Decl *TagDecl, SourceLocation LBrac,
7438                                          SourceLocation RBrac,
7439                                          const ParsedAttributesView &AttrList);
7440   void ActOnFinishCXXMemberDecls();
7441   void ActOnFinishCXXNonNestedClass();
7442 
7443   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7444   unsigned ActOnReenterTemplateScope(Decl *Template,
7445                                      llvm::function_ref<Scope *()> EnterScope);
7446   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7447   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7448   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7449   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7450   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7451   void ActOnFinishDelayedMemberInitializers(Decl *Record);
7452   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7453                                 CachedTokens &Toks);
7454   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7455   bool IsInsideALocalClassWithinATemplateFunction();
7456 
7457   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7458                                      Expr *AssertExpr,
7459                                      Expr *AssertMessageExpr,
7460                                      SourceLocation RParenLoc);
7461   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7462                                      Expr *AssertExpr,
7463                                      StringLiteral *AssertMessageExpr,
7464                                      SourceLocation RParenLoc,
7465                                      bool Failed);
7466 
7467   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7468                                   SourceLocation FriendLoc,
7469                                   TypeSourceInfo *TSInfo);
7470   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7471                             MultiTemplateParamsArg TemplateParams);
7472   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7473                                      MultiTemplateParamsArg TemplateParams);
7474 
7475   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7476                                       StorageClass& SC);
7477   void CheckConstructor(CXXConstructorDecl *Constructor);
7478   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7479                                      StorageClass& SC);
7480   bool CheckDestructor(CXXDestructorDecl *Destructor);
7481   void CheckConversionDeclarator(Declarator &D, QualType &R,
7482                                  StorageClass& SC);
7483   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7484   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7485                                      StorageClass &SC);
7486   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7487 
7488   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7489 
7490   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7491                                              CXXSpecialMember CSM);
7492   void CheckDelayedMemberExceptionSpecs();
7493 
7494   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7495                                           DefaultedComparisonKind DCK);
7496   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7497                                          FunctionDecl *Spaceship);
7498   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7499                                  DefaultedComparisonKind DCK);
7500 
7501   //===--------------------------------------------------------------------===//
7502   // C++ Derived Classes
7503   //
7504 
7505   /// ActOnBaseSpecifier - Parsed a base specifier
7506   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7507                                        SourceRange SpecifierRange,
7508                                        bool Virtual, AccessSpecifier Access,
7509                                        TypeSourceInfo *TInfo,
7510                                        SourceLocation EllipsisLoc);
7511 
7512   BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
7513                                 const ParsedAttributesView &Attrs, bool Virtual,
7514                                 AccessSpecifier Access, ParsedType basetype,
7515                                 SourceLocation BaseLoc,
7516                                 SourceLocation EllipsisLoc);
7517 
7518   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7519                             MutableArrayRef<CXXBaseSpecifier *> Bases);
7520   void ActOnBaseSpecifiers(Decl *ClassDecl,
7521                            MutableArrayRef<CXXBaseSpecifier *> Bases);
7522 
7523   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7524   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7525                      CXXBasePaths &Paths);
7526 
7527   // FIXME: I don't like this name.
7528   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7529 
7530   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7531                                     SourceLocation Loc, SourceRange Range,
7532                                     CXXCastPath *BasePath = nullptr,
7533                                     bool IgnoreAccess = false);
7534   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7535                                     unsigned InaccessibleBaseID,
7536                                     unsigned AmbiguousBaseConvID,
7537                                     SourceLocation Loc, SourceRange Range,
7538                                     DeclarationName Name,
7539                                     CXXCastPath *BasePath,
7540                                     bool IgnoreAccess = false);
7541 
7542   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7543 
7544   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7545                                          const CXXMethodDecl *Old);
7546 
7547   /// CheckOverridingFunctionReturnType - Checks whether the return types are
7548   /// covariant, according to C++ [class.virtual]p5.
7549   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7550                                          const CXXMethodDecl *Old);
7551 
7552   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7553   /// spec is a subset of base spec.
7554   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7555                                             const CXXMethodDecl *Old);
7556 
7557   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7558 
7559   /// CheckOverrideControl - Check C++11 override control semantics.
7560   void CheckOverrideControl(NamedDecl *D);
7561 
7562   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7563   /// not used in the declaration of an overriding method.
7564   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7565 
7566   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7567   /// overrides a virtual member function marked 'final', according to
7568   /// C++11 [class.virtual]p4.
7569   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7570                                               const CXXMethodDecl *Old);
7571 
7572 
7573   //===--------------------------------------------------------------------===//
7574   // C++ Access Control
7575   //
7576 
7577   enum AccessResult {
7578     AR_accessible,
7579     AR_inaccessible,
7580     AR_dependent,
7581     AR_delayed
7582   };
7583 
7584   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7585                                 NamedDecl *PrevMemberDecl,
7586                                 AccessSpecifier LexicalAS);
7587 
7588   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7589                                            DeclAccessPair FoundDecl);
7590   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7591                                            DeclAccessPair FoundDecl);
7592   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7593                                      SourceRange PlacementRange,
7594                                      CXXRecordDecl *NamingClass,
7595                                      DeclAccessPair FoundDecl,
7596                                      bool Diagnose = true);
7597   AccessResult CheckConstructorAccess(SourceLocation Loc,
7598                                       CXXConstructorDecl *D,
7599                                       DeclAccessPair FoundDecl,
7600                                       const InitializedEntity &Entity,
7601                                       bool IsCopyBindingRefToTemp = false);
7602   AccessResult CheckConstructorAccess(SourceLocation Loc,
7603                                       CXXConstructorDecl *D,
7604                                       DeclAccessPair FoundDecl,
7605                                       const InitializedEntity &Entity,
7606                                       const PartialDiagnostic &PDiag);
7607   AccessResult CheckDestructorAccess(SourceLocation Loc,
7608                                      CXXDestructorDecl *Dtor,
7609                                      const PartialDiagnostic &PDiag,
7610                                      QualType objectType = QualType());
7611   AccessResult CheckFriendAccess(NamedDecl *D);
7612   AccessResult CheckMemberAccess(SourceLocation UseLoc,
7613                                  CXXRecordDecl *NamingClass,
7614                                  DeclAccessPair Found);
7615   AccessResult
7616   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7617                                      CXXRecordDecl *DecomposedClass,
7618                                      DeclAccessPair Field);
7619   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7620                                          const SourceRange &,
7621                                          DeclAccessPair FoundDecl);
7622   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7623                                          Expr *ObjectExpr,
7624                                          Expr *ArgExpr,
7625                                          DeclAccessPair FoundDecl);
7626   AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7627                                          ArrayRef<Expr *> ArgExprs,
7628                                          DeclAccessPair FoundDecl);
7629   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7630                                           DeclAccessPair FoundDecl);
7631   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7632                                     QualType Base, QualType Derived,
7633                                     const CXXBasePath &Path,
7634                                     unsigned DiagID,
7635                                     bool ForceCheck = false,
7636                                     bool ForceUnprivileged = false);
7637   void CheckLookupAccess(const LookupResult &R);
7638   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7639                           QualType BaseType);
7640   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7641                                      DeclAccessPair Found, QualType ObjectType,
7642                                      SourceLocation Loc,
7643                                      const PartialDiagnostic &Diag);
7644   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7645                                      DeclAccessPair Found,
7646                                      QualType ObjectType) {
7647     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7648                                          SourceLocation(), PDiag());
7649   }
7650 
7651   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7652                          const MultiLevelTemplateArgumentList &TemplateArgs);
7653   void PerformDependentDiagnostics(const DeclContext *Pattern,
7654                         const MultiLevelTemplateArgumentList &TemplateArgs);
7655 
7656   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7657 
7658   /// When true, access checking violations are treated as SFINAE
7659   /// failures rather than hard errors.
7660   bool AccessCheckingSFINAE;
7661 
7662   enum AbstractDiagSelID {
7663     AbstractNone = -1,
7664     AbstractReturnType,
7665     AbstractParamType,
7666     AbstractVariableType,
7667     AbstractFieldType,
7668     AbstractIvarType,
7669     AbstractSynthesizedIvarType,
7670     AbstractArrayType
7671   };
7672 
7673   bool isAbstractType(SourceLocation Loc, QualType T);
7674   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7675                               TypeDiagnoser &Diagnoser);
7676   template <typename... Ts>
7677   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7678                               const Ts &...Args) {
7679     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7680     return RequireNonAbstractType(Loc, T, Diagnoser);
7681   }
7682 
7683   void DiagnoseAbstractType(const CXXRecordDecl *RD);
7684 
7685   //===--------------------------------------------------------------------===//
7686   // C++ Overloaded Operators [C++ 13.5]
7687   //
7688 
7689   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7690 
7691   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7692 
7693   //===--------------------------------------------------------------------===//
7694   // C++ Templates [C++ 14]
7695   //
7696   void FilterAcceptableTemplateNames(LookupResult &R,
7697                                      bool AllowFunctionTemplates = true,
7698                                      bool AllowDependent = true);
7699   bool hasAnyAcceptableTemplateNames(LookupResult &R,
7700                                      bool AllowFunctionTemplates = true,
7701                                      bool AllowDependent = true,
7702                                      bool AllowNonTemplateFunctions = false);
7703   /// Try to interpret the lookup result D as a template-name.
7704   ///
7705   /// \param D A declaration found by name lookup.
7706   /// \param AllowFunctionTemplates Whether function templates should be
7707   ///        considered valid results.
7708   /// \param AllowDependent Whether unresolved using declarations (that might
7709   ///        name templates) should be considered valid results.
7710   static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7711                                           bool AllowFunctionTemplates = true,
7712                                           bool AllowDependent = true);
7713 
7714   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7715   /// Whether and why a template name is required in this lookup.
7716   class RequiredTemplateKind {
7717   public:
7718     /// Template name is required if TemplateKWLoc is valid.
7719     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
7720         : TemplateKW(TemplateKWLoc) {}
7721     /// Template name is unconditionally required.
7722     RequiredTemplateKind(TemplateNameIsRequiredTag) {}
7723 
7724     SourceLocation getTemplateKeywordLoc() const {
7725       return TemplateKW.value_or(SourceLocation());
7726     }
7727     bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
7728     bool isRequired() const { return TemplateKW != SourceLocation(); }
7729     explicit operator bool() const { return isRequired(); }
7730 
7731   private:
7732     llvm::Optional<SourceLocation> TemplateKW;
7733   };
7734 
7735   enum class AssumedTemplateKind {
7736     /// This is not assumed to be a template name.
7737     None,
7738     /// This is assumed to be a template name because lookup found nothing.
7739     FoundNothing,
7740     /// This is assumed to be a template name because lookup found one or more
7741     /// functions (but no function templates).
7742     FoundFunctions,
7743   };
7744   bool LookupTemplateName(
7745       LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7746       bool EnteringContext, bool &MemberOfUnknownSpecialization,
7747       RequiredTemplateKind RequiredTemplate = SourceLocation(),
7748       AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7749 
7750   TemplateNameKind isTemplateName(Scope *S,
7751                                   CXXScopeSpec &SS,
7752                                   bool hasTemplateKeyword,
7753                                   const UnqualifiedId &Name,
7754                                   ParsedType ObjectType,
7755                                   bool EnteringContext,
7756                                   TemplateTy &Template,
7757                                   bool &MemberOfUnknownSpecialization,
7758                                   bool Disambiguation = false);
7759 
7760   /// Try to resolve an undeclared template name as a type template.
7761   ///
7762   /// Sets II to the identifier corresponding to the template name, and updates
7763   /// Name to a corresponding (typo-corrected) type template name and TNK to
7764   /// the corresponding kind, if possible.
7765   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7766                                        TemplateNameKind &TNK,
7767                                        SourceLocation NameLoc,
7768                                        IdentifierInfo *&II);
7769 
7770   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7771                                         SourceLocation NameLoc,
7772                                         bool Diagnose = true);
7773 
7774   /// Determine whether a particular identifier might be the name in a C++1z
7775   /// deduction-guide declaration.
7776   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7777                             SourceLocation NameLoc,
7778                             ParsedTemplateTy *Template = nullptr);
7779 
7780   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7781                                    SourceLocation IILoc,
7782                                    Scope *S,
7783                                    const CXXScopeSpec *SS,
7784                                    TemplateTy &SuggestedTemplate,
7785                                    TemplateNameKind &SuggestedKind);
7786 
7787   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7788                                       NamedDecl *Instantiation,
7789                                       bool InstantiatedFromMember,
7790                                       const NamedDecl *Pattern,
7791                                       const NamedDecl *PatternDef,
7792                                       TemplateSpecializationKind TSK,
7793                                       bool Complain = true);
7794 
7795   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7796   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7797 
7798   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7799                                 SourceLocation EllipsisLoc,
7800                                 SourceLocation KeyLoc,
7801                                 IdentifierInfo *ParamName,
7802                                 SourceLocation ParamNameLoc,
7803                                 unsigned Depth, unsigned Position,
7804                                 SourceLocation EqualLoc,
7805                                 ParsedType DefaultArg, bool HasTypeConstraint);
7806 
7807   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7808                            TemplateIdAnnotation *TypeConstraint,
7809                            TemplateTypeParmDecl *ConstrainedParameter,
7810                            SourceLocation EllipsisLoc);
7811   bool BuildTypeConstraint(const CXXScopeSpec &SS,
7812                            TemplateIdAnnotation *TypeConstraint,
7813                            TemplateTypeParmDecl *ConstrainedParameter,
7814                            SourceLocation EllipsisLoc,
7815                            bool AllowUnexpandedPack);
7816 
7817   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7818                             DeclarationNameInfo NameInfo,
7819                             ConceptDecl *NamedConcept,
7820                             const TemplateArgumentListInfo *TemplateArgs,
7821                             TemplateTypeParmDecl *ConstrainedParameter,
7822                             SourceLocation EllipsisLoc);
7823 
7824   bool AttachTypeConstraint(AutoTypeLoc TL,
7825                             NonTypeTemplateParmDecl *ConstrainedParameter,
7826                             SourceLocation EllipsisLoc);
7827 
7828   bool RequireStructuralType(QualType T, SourceLocation Loc);
7829 
7830   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7831                                              SourceLocation Loc);
7832   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7833 
7834   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7835                                       unsigned Depth,
7836                                       unsigned Position,
7837                                       SourceLocation EqualLoc,
7838                                       Expr *DefaultArg);
7839   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7840                                        SourceLocation TmpLoc,
7841                                        TemplateParameterList *Params,
7842                                        SourceLocation EllipsisLoc,
7843                                        IdentifierInfo *ParamName,
7844                                        SourceLocation ParamNameLoc,
7845                                        unsigned Depth,
7846                                        unsigned Position,
7847                                        SourceLocation EqualLoc,
7848                                        ParsedTemplateArgument DefaultArg);
7849 
7850   TemplateParameterList *
7851   ActOnTemplateParameterList(unsigned Depth,
7852                              SourceLocation ExportLoc,
7853                              SourceLocation TemplateLoc,
7854                              SourceLocation LAngleLoc,
7855                              ArrayRef<NamedDecl *> Params,
7856                              SourceLocation RAngleLoc,
7857                              Expr *RequiresClause);
7858 
7859   /// The context in which we are checking a template parameter list.
7860   enum TemplateParamListContext {
7861     TPC_ClassTemplate,
7862     TPC_VarTemplate,
7863     TPC_FunctionTemplate,
7864     TPC_ClassTemplateMember,
7865     TPC_FriendClassTemplate,
7866     TPC_FriendFunctionTemplate,
7867     TPC_FriendFunctionTemplateDefinition,
7868     TPC_TypeAliasTemplate
7869   };
7870 
7871   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7872                                   TemplateParameterList *OldParams,
7873                                   TemplateParamListContext TPC,
7874                                   SkipBodyInfo *SkipBody = nullptr);
7875   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7876       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7877       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7878       ArrayRef<TemplateParameterList *> ParamLists,
7879       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7880       bool SuppressDiagnostic = false);
7881 
7882   DeclResult CheckClassTemplate(
7883       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7884       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7885       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7886       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7887       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7888       TemplateParameterList **OuterTemplateParamLists,
7889       SkipBodyInfo *SkipBody = nullptr);
7890 
7891   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7892                                                     QualType NTTPType,
7893                                                     SourceLocation Loc);
7894 
7895   /// Get a template argument mapping the given template parameter to itself,
7896   /// e.g. for X in \c template<int X>, this would return an expression template
7897   /// argument referencing X.
7898   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7899                                                      SourceLocation Location);
7900 
7901   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7902                                   TemplateArgumentListInfo &Out);
7903 
7904   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7905 
7906   void NoteAllFoundTemplates(TemplateName Name);
7907 
7908   QualType CheckTemplateIdType(TemplateName Template,
7909                                SourceLocation TemplateLoc,
7910                               TemplateArgumentListInfo &TemplateArgs);
7911 
7912   TypeResult
7913   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7914                       TemplateTy Template, IdentifierInfo *TemplateII,
7915                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7916                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7917                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7918 
7919   /// Parsed an elaborated-type-specifier that refers to a template-id,
7920   /// such as \c class T::template apply<U>.
7921   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7922                                     TypeSpecifierType TagSpec,
7923                                     SourceLocation TagLoc,
7924                                     CXXScopeSpec &SS,
7925                                     SourceLocation TemplateKWLoc,
7926                                     TemplateTy TemplateD,
7927                                     SourceLocation TemplateLoc,
7928                                     SourceLocation LAngleLoc,
7929                                     ASTTemplateArgsPtr TemplateArgsIn,
7930                                     SourceLocation RAngleLoc);
7931 
7932   DeclResult ActOnVarTemplateSpecialization(
7933       Scope *S, Declarator &D, TypeSourceInfo *DI,
7934       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7935       StorageClass SC, bool IsPartialSpecialization);
7936 
7937   /// Get the specialization of the given variable template corresponding to
7938   /// the specified argument list, or a null-but-valid result if the arguments
7939   /// are dependent.
7940   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7941                                 SourceLocation TemplateLoc,
7942                                 SourceLocation TemplateNameLoc,
7943                                 const TemplateArgumentListInfo &TemplateArgs);
7944 
7945   /// Form a reference to the specialization of the given variable template
7946   /// corresponding to the specified argument list, or a null-but-valid result
7947   /// if the arguments are dependent.
7948   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7949                                 const DeclarationNameInfo &NameInfo,
7950                                 VarTemplateDecl *Template,
7951                                 SourceLocation TemplateLoc,
7952                                 const TemplateArgumentListInfo *TemplateArgs);
7953 
7954   ExprResult
7955   CheckConceptTemplateId(const CXXScopeSpec &SS,
7956                          SourceLocation TemplateKWLoc,
7957                          const DeclarationNameInfo &ConceptNameInfo,
7958                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7959                          const TemplateArgumentListInfo *TemplateArgs);
7960 
7961   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7962 
7963   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7964                                  SourceLocation TemplateKWLoc,
7965                                  LookupResult &R,
7966                                  bool RequiresADL,
7967                                const TemplateArgumentListInfo *TemplateArgs);
7968 
7969   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7970                                           SourceLocation TemplateKWLoc,
7971                                const DeclarationNameInfo &NameInfo,
7972                                const TemplateArgumentListInfo *TemplateArgs);
7973 
7974   TemplateNameKind ActOnTemplateName(
7975       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7976       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7977       TemplateTy &Template, bool AllowInjectedClassName = false);
7978 
7979   DeclResult ActOnClassTemplateSpecialization(
7980       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7981       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7982       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7983       MultiTemplateParamsArg TemplateParameterLists,
7984       SkipBodyInfo *SkipBody = nullptr);
7985 
7986   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7987                                               TemplateDecl *PrimaryTemplate,
7988                                               unsigned NumExplicitArgs,
7989                                               ArrayRef<TemplateArgument> Args);
7990   void CheckTemplatePartialSpecialization(
7991       ClassTemplatePartialSpecializationDecl *Partial);
7992   void CheckTemplatePartialSpecialization(
7993       VarTemplatePartialSpecializationDecl *Partial);
7994 
7995   Decl *ActOnTemplateDeclarator(Scope *S,
7996                                 MultiTemplateParamsArg TemplateParameterLists,
7997                                 Declarator &D);
7998 
7999   bool
8000   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8001                                          TemplateSpecializationKind NewTSK,
8002                                          NamedDecl *PrevDecl,
8003                                          TemplateSpecializationKind PrevTSK,
8004                                          SourceLocation PrevPtOfInstantiation,
8005                                          bool &SuppressNew);
8006 
8007   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8008                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
8009                                                     LookupResult &Previous);
8010 
8011   bool CheckFunctionTemplateSpecialization(
8012       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8013       LookupResult &Previous, bool QualifiedFriend = false);
8014   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8015   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
8016 
8017   DeclResult ActOnExplicitInstantiation(
8018       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8019       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8020       TemplateTy Template, SourceLocation TemplateNameLoc,
8021       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
8022       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
8023 
8024   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8025                                         SourceLocation TemplateLoc,
8026                                         unsigned TagSpec, SourceLocation KWLoc,
8027                                         CXXScopeSpec &SS, IdentifierInfo *Name,
8028                                         SourceLocation NameLoc,
8029                                         const ParsedAttributesView &Attr);
8030 
8031   DeclResult ActOnExplicitInstantiation(Scope *S,
8032                                         SourceLocation ExternLoc,
8033                                         SourceLocation TemplateLoc,
8034                                         Declarator &D);
8035 
8036   TemplateArgumentLoc
8037   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
8038                                           SourceLocation TemplateLoc,
8039                                           SourceLocation RAngleLoc,
8040                                           Decl *Param,
8041                                           SmallVectorImpl<TemplateArgument>
8042                                             &Converted,
8043                                           bool &HasDefaultArg);
8044 
8045   /// Specifies the context in which a particular template
8046   /// argument is being checked.
8047   enum CheckTemplateArgumentKind {
8048     /// The template argument was specified in the code or was
8049     /// instantiated with some deduced template arguments.
8050     CTAK_Specified,
8051 
8052     /// The template argument was deduced via template argument
8053     /// deduction.
8054     CTAK_Deduced,
8055 
8056     /// The template argument was deduced from an array bound
8057     /// via template argument deduction.
8058     CTAK_DeducedFromArrayBound
8059   };
8060 
8061   bool CheckTemplateArgument(NamedDecl *Param,
8062                              TemplateArgumentLoc &Arg,
8063                              NamedDecl *Template,
8064                              SourceLocation TemplateLoc,
8065                              SourceLocation RAngleLoc,
8066                              unsigned ArgumentPackIndex,
8067                            SmallVectorImpl<TemplateArgument> &Converted,
8068                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
8069 
8070   /// Check that the given template arguments can be be provided to
8071   /// the given template, converting the arguments along the way.
8072   ///
8073   /// \param Template The template to which the template arguments are being
8074   /// provided.
8075   ///
8076   /// \param TemplateLoc The location of the template name in the source.
8077   ///
8078   /// \param TemplateArgs The list of template arguments. If the template is
8079   /// a template template parameter, this function may extend the set of
8080   /// template arguments to also include substituted, defaulted template
8081   /// arguments.
8082   ///
8083   /// \param PartialTemplateArgs True if the list of template arguments is
8084   /// intentionally partial, e.g., because we're checking just the initial
8085   /// set of template arguments.
8086   ///
8087   /// \param Converted Will receive the converted, canonicalized template
8088   /// arguments.
8089   ///
8090   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
8091   /// contain the converted forms of the template arguments as written.
8092   /// Otherwise, \p TemplateArgs will not be modified.
8093   ///
8094   /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
8095   /// receive true if the cause for the error is the associated constraints of
8096   /// the template not being satisfied by the template arguments.
8097   ///
8098   /// \returns true if an error occurred, false otherwise.
8099   bool CheckTemplateArgumentList(TemplateDecl *Template,
8100                                  SourceLocation TemplateLoc,
8101                                  TemplateArgumentListInfo &TemplateArgs,
8102                                  bool PartialTemplateArgs,
8103                                  SmallVectorImpl<TemplateArgument> &Converted,
8104                                  bool UpdateArgsWithConversions = true,
8105                                  bool *ConstraintsNotSatisfied = nullptr);
8106 
8107   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
8108                                  TemplateArgumentLoc &Arg,
8109                            SmallVectorImpl<TemplateArgument> &Converted);
8110 
8111   bool CheckTemplateArgument(TypeSourceInfo *Arg);
8112   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
8113                                    QualType InstantiatedParamType, Expr *Arg,
8114                                    TemplateArgument &Converted,
8115                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
8116   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8117                                      TemplateParameterList *Params,
8118                                      TemplateArgumentLoc &Arg);
8119 
8120   ExprResult
8121   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8122                                           QualType ParamType,
8123                                           SourceLocation Loc);
8124   ExprResult
8125   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8126                                               SourceLocation Loc);
8127 
8128   /// Enumeration describing how template parameter lists are compared
8129   /// for equality.
8130   enum TemplateParameterListEqualKind {
8131     /// We are matching the template parameter lists of two templates
8132     /// that might be redeclarations.
8133     ///
8134     /// \code
8135     /// template<typename T> struct X;
8136     /// template<typename T> struct X;
8137     /// \endcode
8138     TPL_TemplateMatch,
8139 
8140     /// We are matching the template parameter lists of two template
8141     /// template parameters as part of matching the template parameter lists
8142     /// of two templates that might be redeclarations.
8143     ///
8144     /// \code
8145     /// template<template<int I> class TT> struct X;
8146     /// template<template<int Value> class Other> struct X;
8147     /// \endcode
8148     TPL_TemplateTemplateParmMatch,
8149 
8150     /// We are matching the template parameter lists of a template
8151     /// template argument against the template parameter lists of a template
8152     /// template parameter.
8153     ///
8154     /// \code
8155     /// template<template<int Value> class Metafun> struct X;
8156     /// template<int Value> struct integer_c;
8157     /// X<integer_c> xic;
8158     /// \endcode
8159     TPL_TemplateTemplateArgumentMatch
8160   };
8161 
8162   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
8163                                       TemplateParameterList *Old,
8164                                       bool Complain,
8165                                       TemplateParameterListEqualKind Kind,
8166                                       SourceLocation TemplateArgLoc
8167                                         = SourceLocation());
8168 
8169   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
8170 
8171   /// Called when the parser has parsed a C++ typename
8172   /// specifier, e.g., "typename T::type".
8173   ///
8174   /// \param S The scope in which this typename type occurs.
8175   /// \param TypenameLoc the location of the 'typename' keyword
8176   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8177   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
8178   /// \param IdLoc the location of the identifier.
8179   TypeResult
8180   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8181                     const CXXScopeSpec &SS, const IdentifierInfo &II,
8182                     SourceLocation IdLoc);
8183 
8184   /// Called when the parser has parsed a C++ typename
8185   /// specifier that ends in a template-id, e.g.,
8186   /// "typename MetaFun::template apply<T1, T2>".
8187   ///
8188   /// \param S The scope in which this typename type occurs.
8189   /// \param TypenameLoc the location of the 'typename' keyword
8190   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8191   /// \param TemplateLoc the location of the 'template' keyword, if any.
8192   /// \param TemplateName The template name.
8193   /// \param TemplateII The identifier used to name the template.
8194   /// \param TemplateIILoc The location of the template name.
8195   /// \param LAngleLoc The location of the opening angle bracket  ('<').
8196   /// \param TemplateArgs The template arguments.
8197   /// \param RAngleLoc The location of the closing angle bracket  ('>').
8198   TypeResult
8199   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8200                     const CXXScopeSpec &SS,
8201                     SourceLocation TemplateLoc,
8202                     TemplateTy TemplateName,
8203                     IdentifierInfo *TemplateII,
8204                     SourceLocation TemplateIILoc,
8205                     SourceLocation LAngleLoc,
8206                     ASTTemplateArgsPtr TemplateArgs,
8207                     SourceLocation RAngleLoc);
8208 
8209   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8210                              SourceLocation KeywordLoc,
8211                              NestedNameSpecifierLoc QualifierLoc,
8212                              const IdentifierInfo &II,
8213                              SourceLocation IILoc,
8214                              TypeSourceInfo **TSI,
8215                              bool DeducedTSTContext);
8216 
8217   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8218                              SourceLocation KeywordLoc,
8219                              NestedNameSpecifierLoc QualifierLoc,
8220                              const IdentifierInfo &II,
8221                              SourceLocation IILoc,
8222                              bool DeducedTSTContext = true);
8223 
8224 
8225   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8226                                                     SourceLocation Loc,
8227                                                     DeclarationName Name);
8228   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
8229 
8230   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
8231   bool RebuildTemplateParamsInCurrentInstantiation(
8232                                                 TemplateParameterList *Params);
8233 
8234   std::string
8235   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8236                                   const TemplateArgumentList &Args);
8237 
8238   std::string
8239   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8240                                   const TemplateArgument *Args,
8241                                   unsigned NumArgs);
8242 
8243   //===--------------------------------------------------------------------===//
8244   // C++ Concepts
8245   //===--------------------------------------------------------------------===//
8246   Decl *ActOnConceptDefinition(
8247       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8248       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8249 
8250   RequiresExprBodyDecl *
8251   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8252                          ArrayRef<ParmVarDecl *> LocalParameters,
8253                          Scope *BodyScope);
8254   void ActOnFinishRequiresExpr();
8255   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8256   concepts::Requirement *ActOnTypeRequirement(
8257       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8258       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8259   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8260                                                   SourceLocation NoexceptLoc);
8261   concepts::Requirement *
8262   ActOnCompoundRequirement(
8263       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8264       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8265   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8266   concepts::ExprRequirement *
8267   BuildExprRequirement(
8268       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8269       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8270   concepts::ExprRequirement *
8271   BuildExprRequirement(
8272       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8273       bool IsSatisfied, SourceLocation NoexceptLoc,
8274       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8275   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8276   concepts::TypeRequirement *
8277   BuildTypeRequirement(
8278       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8279   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8280   concepts::NestedRequirement *
8281   BuildNestedRequirement(
8282       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8283   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8284                                RequiresExprBodyDecl *Body,
8285                                ArrayRef<ParmVarDecl *> LocalParameters,
8286                                ArrayRef<concepts::Requirement *> Requirements,
8287                                SourceLocation ClosingBraceLoc);
8288 
8289   //===--------------------------------------------------------------------===//
8290   // C++ Variadic Templates (C++0x [temp.variadic])
8291   //===--------------------------------------------------------------------===//
8292 
8293   /// Determine whether an unexpanded parameter pack might be permitted in this
8294   /// location. Useful for error recovery.
8295   bool isUnexpandedParameterPackPermitted();
8296 
8297   /// The context in which an unexpanded parameter pack is
8298   /// being diagnosed.
8299   ///
8300   /// Note that the values of this enumeration line up with the first
8301   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8302   enum UnexpandedParameterPackContext {
8303     /// An arbitrary expression.
8304     UPPC_Expression = 0,
8305 
8306     /// The base type of a class type.
8307     UPPC_BaseType,
8308 
8309     /// The type of an arbitrary declaration.
8310     UPPC_DeclarationType,
8311 
8312     /// The type of a data member.
8313     UPPC_DataMemberType,
8314 
8315     /// The size of a bit-field.
8316     UPPC_BitFieldWidth,
8317 
8318     /// The expression in a static assertion.
8319     UPPC_StaticAssertExpression,
8320 
8321     /// The fixed underlying type of an enumeration.
8322     UPPC_FixedUnderlyingType,
8323 
8324     /// The enumerator value.
8325     UPPC_EnumeratorValue,
8326 
8327     /// A using declaration.
8328     UPPC_UsingDeclaration,
8329 
8330     /// A friend declaration.
8331     UPPC_FriendDeclaration,
8332 
8333     /// A declaration qualifier.
8334     UPPC_DeclarationQualifier,
8335 
8336     /// An initializer.
8337     UPPC_Initializer,
8338 
8339     /// A default argument.
8340     UPPC_DefaultArgument,
8341 
8342     /// The type of a non-type template parameter.
8343     UPPC_NonTypeTemplateParameterType,
8344 
8345     /// The type of an exception.
8346     UPPC_ExceptionType,
8347 
8348     /// Partial specialization.
8349     UPPC_PartialSpecialization,
8350 
8351     /// Microsoft __if_exists.
8352     UPPC_IfExists,
8353 
8354     /// Microsoft __if_not_exists.
8355     UPPC_IfNotExists,
8356 
8357     /// Lambda expression.
8358     UPPC_Lambda,
8359 
8360     /// Block expression.
8361     UPPC_Block,
8362 
8363     /// A type constraint.
8364     UPPC_TypeConstraint,
8365 
8366     // A requirement in a requires-expression.
8367     UPPC_Requirement,
8368 
8369     // A requires-clause.
8370     UPPC_RequiresClause,
8371   };
8372 
8373   /// Diagnose unexpanded parameter packs.
8374   ///
8375   /// \param Loc The location at which we should emit the diagnostic.
8376   ///
8377   /// \param UPPC The context in which we are diagnosing unexpanded
8378   /// parameter packs.
8379   ///
8380   /// \param Unexpanded the set of unexpanded parameter packs.
8381   ///
8382   /// \returns true if an error occurred, false otherwise.
8383   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8384                                         UnexpandedParameterPackContext UPPC,
8385                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
8386 
8387   /// If the given type contains an unexpanded parameter pack,
8388   /// diagnose the error.
8389   ///
8390   /// \param Loc The source location where a diagnostc should be emitted.
8391   ///
8392   /// \param T The type that is being checked for unexpanded parameter
8393   /// packs.
8394   ///
8395   /// \returns true if an error occurred, false otherwise.
8396   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8397                                        UnexpandedParameterPackContext UPPC);
8398 
8399   /// If the given expression contains an unexpanded parameter
8400   /// pack, diagnose the error.
8401   ///
8402   /// \param E The expression that is being checked for unexpanded
8403   /// parameter packs.
8404   ///
8405   /// \returns true if an error occurred, false otherwise.
8406   bool DiagnoseUnexpandedParameterPack(Expr *E,
8407                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
8408 
8409   /// If the given requirees-expression contains an unexpanded reference to one
8410   /// of its own parameter packs, diagnose the error.
8411   ///
8412   /// \param RE The requiress-expression that is being checked for unexpanded
8413   /// parameter packs.
8414   ///
8415   /// \returns true if an error occurred, false otherwise.
8416   bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8417 
8418   /// If the given nested-name-specifier contains an unexpanded
8419   /// parameter pack, diagnose the error.
8420   ///
8421   /// \param SS The nested-name-specifier that is being checked for
8422   /// unexpanded parameter packs.
8423   ///
8424   /// \returns true if an error occurred, false otherwise.
8425   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8426                                        UnexpandedParameterPackContext UPPC);
8427 
8428   /// If the given name contains an unexpanded parameter pack,
8429   /// diagnose the error.
8430   ///
8431   /// \param NameInfo The name (with source location information) that
8432   /// is being checked for unexpanded parameter packs.
8433   ///
8434   /// \returns true if an error occurred, false otherwise.
8435   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8436                                        UnexpandedParameterPackContext UPPC);
8437 
8438   /// If the given template name contains an unexpanded parameter pack,
8439   /// diagnose the error.
8440   ///
8441   /// \param Loc The location of the template name.
8442   ///
8443   /// \param Template The template name that is being checked for unexpanded
8444   /// parameter packs.
8445   ///
8446   /// \returns true if an error occurred, false otherwise.
8447   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8448                                        TemplateName Template,
8449                                        UnexpandedParameterPackContext UPPC);
8450 
8451   /// If the given template argument contains an unexpanded parameter
8452   /// pack, diagnose the error.
8453   ///
8454   /// \param Arg The template argument that is being checked for unexpanded
8455   /// parameter packs.
8456   ///
8457   /// \returns true if an error occurred, false otherwise.
8458   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8459                                        UnexpandedParameterPackContext UPPC);
8460 
8461   /// Collect the set of unexpanded parameter packs within the given
8462   /// template argument.
8463   ///
8464   /// \param Arg The template argument that will be traversed to find
8465   /// unexpanded parameter packs.
8466   void collectUnexpandedParameterPacks(TemplateArgument Arg,
8467                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8468 
8469   /// Collect the set of unexpanded parameter packs within the given
8470   /// template argument.
8471   ///
8472   /// \param Arg The template argument that will be traversed to find
8473   /// unexpanded parameter packs.
8474   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8475                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8476 
8477   /// Collect the set of unexpanded parameter packs within the given
8478   /// type.
8479   ///
8480   /// \param T The type that will be traversed to find
8481   /// unexpanded parameter packs.
8482   void collectUnexpandedParameterPacks(QualType T,
8483                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8484 
8485   /// Collect the set of unexpanded parameter packs within the given
8486   /// type.
8487   ///
8488   /// \param TL The type that will be traversed to find
8489   /// unexpanded parameter packs.
8490   void collectUnexpandedParameterPacks(TypeLoc TL,
8491                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8492 
8493   /// Collect the set of unexpanded parameter packs within the given
8494   /// nested-name-specifier.
8495   ///
8496   /// \param NNS The nested-name-specifier that will be traversed to find
8497   /// unexpanded parameter packs.
8498   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8499                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8500 
8501   /// Collect the set of unexpanded parameter packs within the given
8502   /// name.
8503   ///
8504   /// \param NameInfo The name that will be traversed to find
8505   /// unexpanded parameter packs.
8506   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8507                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8508 
8509   /// Invoked when parsing a template argument followed by an
8510   /// ellipsis, which creates a pack expansion.
8511   ///
8512   /// \param Arg The template argument preceding the ellipsis, which
8513   /// may already be invalid.
8514   ///
8515   /// \param EllipsisLoc The location of the ellipsis.
8516   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8517                                             SourceLocation EllipsisLoc);
8518 
8519   /// Invoked when parsing a type followed by an ellipsis, which
8520   /// creates a pack expansion.
8521   ///
8522   /// \param Type The type preceding the ellipsis, which will become
8523   /// the pattern of the pack expansion.
8524   ///
8525   /// \param EllipsisLoc The location of the ellipsis.
8526   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8527 
8528   /// Construct a pack expansion type from the pattern of the pack
8529   /// expansion.
8530   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8531                                      SourceLocation EllipsisLoc,
8532                                      Optional<unsigned> NumExpansions);
8533 
8534   /// Construct a pack expansion type from the pattern of the pack
8535   /// expansion.
8536   QualType CheckPackExpansion(QualType Pattern,
8537                               SourceRange PatternRange,
8538                               SourceLocation EllipsisLoc,
8539                               Optional<unsigned> NumExpansions);
8540 
8541   /// Invoked when parsing an expression followed by an ellipsis, which
8542   /// creates a pack expansion.
8543   ///
8544   /// \param Pattern The expression preceding the ellipsis, which will become
8545   /// the pattern of the pack expansion.
8546   ///
8547   /// \param EllipsisLoc The location of the ellipsis.
8548   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8549 
8550   /// Invoked when parsing an expression followed by an ellipsis, which
8551   /// creates a pack expansion.
8552   ///
8553   /// \param Pattern The expression preceding the ellipsis, which will become
8554   /// the pattern of the pack expansion.
8555   ///
8556   /// \param EllipsisLoc The location of the ellipsis.
8557   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8558                                 Optional<unsigned> NumExpansions);
8559 
8560   /// Determine whether we could expand a pack expansion with the
8561   /// given set of parameter packs into separate arguments by repeatedly
8562   /// transforming the pattern.
8563   ///
8564   /// \param EllipsisLoc The location of the ellipsis that identifies the
8565   /// pack expansion.
8566   ///
8567   /// \param PatternRange The source range that covers the entire pattern of
8568   /// the pack expansion.
8569   ///
8570   /// \param Unexpanded The set of unexpanded parameter packs within the
8571   /// pattern.
8572   ///
8573   /// \param ShouldExpand Will be set to \c true if the transformer should
8574   /// expand the corresponding pack expansions into separate arguments. When
8575   /// set, \c NumExpansions must also be set.
8576   ///
8577   /// \param RetainExpansion Whether the caller should add an unexpanded
8578   /// pack expansion after all of the expanded arguments. This is used
8579   /// when extending explicitly-specified template argument packs per
8580   /// C++0x [temp.arg.explicit]p9.
8581   ///
8582   /// \param NumExpansions The number of separate arguments that will be in
8583   /// the expanded form of the corresponding pack expansion. This is both an
8584   /// input and an output parameter, which can be set by the caller if the
8585   /// number of expansions is known a priori (e.g., due to a prior substitution)
8586   /// and will be set by the callee when the number of expansions is known.
8587   /// The callee must set this value when \c ShouldExpand is \c true; it may
8588   /// set this value in other cases.
8589   ///
8590   /// \returns true if an error occurred (e.g., because the parameter packs
8591   /// are to be instantiated with arguments of different lengths), false
8592   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8593   /// must be set.
8594   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8595                                        SourceRange PatternRange,
8596                              ArrayRef<UnexpandedParameterPack> Unexpanded,
8597                              const MultiLevelTemplateArgumentList &TemplateArgs,
8598                                        bool &ShouldExpand,
8599                                        bool &RetainExpansion,
8600                                        Optional<unsigned> &NumExpansions);
8601 
8602   /// Determine the number of arguments in the given pack expansion
8603   /// type.
8604   ///
8605   /// This routine assumes that the number of arguments in the expansion is
8606   /// consistent across all of the unexpanded parameter packs in its pattern.
8607   ///
8608   /// Returns an empty Optional if the type can't be expanded.
8609   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8610       const MultiLevelTemplateArgumentList &TemplateArgs);
8611 
8612   /// Determine whether the given declarator contains any unexpanded
8613   /// parameter packs.
8614   ///
8615   /// This routine is used by the parser to disambiguate function declarators
8616   /// with an ellipsis prior to the ')', e.g.,
8617   ///
8618   /// \code
8619   ///   void f(T...);
8620   /// \endcode
8621   ///
8622   /// To determine whether we have an (unnamed) function parameter pack or
8623   /// a variadic function.
8624   ///
8625   /// \returns true if the declarator contains any unexpanded parameter packs,
8626   /// false otherwise.
8627   bool containsUnexpandedParameterPacks(Declarator &D);
8628 
8629   /// Returns the pattern of the pack expansion for a template argument.
8630   ///
8631   /// \param OrigLoc The template argument to expand.
8632   ///
8633   /// \param Ellipsis Will be set to the location of the ellipsis.
8634   ///
8635   /// \param NumExpansions Will be set to the number of expansions that will
8636   /// be generated from this pack expansion, if known a priori.
8637   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8638       TemplateArgumentLoc OrigLoc,
8639       SourceLocation &Ellipsis,
8640       Optional<unsigned> &NumExpansions) const;
8641 
8642   /// Given a template argument that contains an unexpanded parameter pack, but
8643   /// which has already been substituted, attempt to determine the number of
8644   /// elements that will be produced once this argument is fully-expanded.
8645   ///
8646   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8647   /// avoid actually expanding the pack where possible.
8648   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8649 
8650   //===--------------------------------------------------------------------===//
8651   // C++ Template Argument Deduction (C++ [temp.deduct])
8652   //===--------------------------------------------------------------------===//
8653 
8654   /// Adjust the type \p ArgFunctionType to match the calling convention,
8655   /// noreturn, and optionally the exception specification of \p FunctionType.
8656   /// Deduction often wants to ignore these properties when matching function
8657   /// types.
8658   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8659                                bool AdjustExceptionSpec = false);
8660 
8661   /// Describes the result of template argument deduction.
8662   ///
8663   /// The TemplateDeductionResult enumeration describes the result of
8664   /// template argument deduction, as returned from
8665   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8666   /// structure provides additional information about the results of
8667   /// template argument deduction, e.g., the deduced template argument
8668   /// list (if successful) or the specific template parameters or
8669   /// deduced arguments that were involved in the failure.
8670   enum TemplateDeductionResult {
8671     /// Template argument deduction was successful.
8672     TDK_Success = 0,
8673     /// The declaration was invalid; do nothing.
8674     TDK_Invalid,
8675     /// Template argument deduction exceeded the maximum template
8676     /// instantiation depth (which has already been diagnosed).
8677     TDK_InstantiationDepth,
8678     /// Template argument deduction did not deduce a value
8679     /// for every template parameter.
8680     TDK_Incomplete,
8681     /// Template argument deduction did not deduce a value for every
8682     /// expansion of an expanded template parameter pack.
8683     TDK_IncompletePack,
8684     /// Template argument deduction produced inconsistent
8685     /// deduced values for the given template parameter.
8686     TDK_Inconsistent,
8687     /// Template argument deduction failed due to inconsistent
8688     /// cv-qualifiers on a template parameter type that would
8689     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8690     /// but were given a non-const "X".
8691     TDK_Underqualified,
8692     /// Substitution of the deduced template argument values
8693     /// resulted in an error.
8694     TDK_SubstitutionFailure,
8695     /// After substituting deduced template arguments, a dependent
8696     /// parameter type did not match the corresponding argument.
8697     TDK_DeducedMismatch,
8698     /// After substituting deduced template arguments, an element of
8699     /// a dependent parameter type did not match the corresponding element
8700     /// of the corresponding argument (when deducing from an initializer list).
8701     TDK_DeducedMismatchNested,
8702     /// A non-depnedent component of the parameter did not match the
8703     /// corresponding component of the argument.
8704     TDK_NonDeducedMismatch,
8705     /// When performing template argument deduction for a function
8706     /// template, there were too many call arguments.
8707     TDK_TooManyArguments,
8708     /// When performing template argument deduction for a function
8709     /// template, there were too few call arguments.
8710     TDK_TooFewArguments,
8711     /// The explicitly-specified template arguments were not valid
8712     /// template arguments for the given template.
8713     TDK_InvalidExplicitArguments,
8714     /// Checking non-dependent argument conversions failed.
8715     TDK_NonDependentConversionFailure,
8716     /// The deduced arguments did not satisfy the constraints associated
8717     /// with the template.
8718     TDK_ConstraintsNotSatisfied,
8719     /// Deduction failed; that's all we know.
8720     TDK_MiscellaneousDeductionFailure,
8721     /// CUDA Target attributes do not match.
8722     TDK_CUDATargetMismatch
8723   };
8724 
8725   TemplateDeductionResult
8726   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8727                           const TemplateArgumentList &TemplateArgs,
8728                           sema::TemplateDeductionInfo &Info);
8729 
8730   TemplateDeductionResult
8731   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8732                           const TemplateArgumentList &TemplateArgs,
8733                           sema::TemplateDeductionInfo &Info);
8734 
8735   TemplateDeductionResult SubstituteExplicitTemplateArguments(
8736       FunctionTemplateDecl *FunctionTemplate,
8737       TemplateArgumentListInfo &ExplicitTemplateArgs,
8738       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8739       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8740       sema::TemplateDeductionInfo &Info);
8741 
8742   /// brief A function argument from which we performed template argument
8743   // deduction for a call.
8744   struct OriginalCallArg {
8745     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8746                     unsigned ArgIdx, QualType OriginalArgType)
8747         : OriginalParamType(OriginalParamType),
8748           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8749           OriginalArgType(OriginalArgType) {}
8750 
8751     QualType OriginalParamType;
8752     bool DecomposedParam;
8753     unsigned ArgIdx;
8754     QualType OriginalArgType;
8755   };
8756 
8757   TemplateDeductionResult FinishTemplateArgumentDeduction(
8758       FunctionTemplateDecl *FunctionTemplate,
8759       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8760       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8761       sema::TemplateDeductionInfo &Info,
8762       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8763       bool PartialOverloading = false,
8764       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8765 
8766   TemplateDeductionResult DeduceTemplateArguments(
8767       FunctionTemplateDecl *FunctionTemplate,
8768       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8769       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8770       bool PartialOverloading,
8771       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8772 
8773   TemplateDeductionResult
8774   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8775                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8776                           QualType ArgFunctionType,
8777                           FunctionDecl *&Specialization,
8778                           sema::TemplateDeductionInfo &Info,
8779                           bool IsAddressOfFunction = false);
8780 
8781   TemplateDeductionResult
8782   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8783                           QualType ToType,
8784                           CXXConversionDecl *&Specialization,
8785                           sema::TemplateDeductionInfo &Info);
8786 
8787   TemplateDeductionResult
8788   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8789                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8790                           FunctionDecl *&Specialization,
8791                           sema::TemplateDeductionInfo &Info,
8792                           bool IsAddressOfFunction = false);
8793 
8794   /// Substitute Replacement for \p auto in \p TypeWithAuto
8795   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8796   /// Substitute Replacement for auto in TypeWithAuto
8797   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8798                                           QualType Replacement);
8799 
8800   // Substitute auto in TypeWithAuto for a Dependent auto type
8801   QualType SubstAutoTypeDependent(QualType TypeWithAuto);
8802 
8803   // Substitute auto in TypeWithAuto for a Dependent auto type
8804   TypeSourceInfo *
8805   SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
8806 
8807   /// Completely replace the \c auto in \p TypeWithAuto by
8808   /// \p Replacement. This does not retain any \c auto type sugar.
8809   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8810   TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8811                                             QualType Replacement);
8812 
8813   /// Result type of DeduceAutoType.
8814   enum DeduceAutoResult {
8815     DAR_Succeeded,
8816     DAR_Failed,
8817     DAR_FailedAlreadyDiagnosed
8818   };
8819 
8820   DeduceAutoResult
8821   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8822                  Optional<unsigned> DependentDeductionDepth = None,
8823                  bool IgnoreConstraints = false);
8824   DeduceAutoResult
8825   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8826                  Optional<unsigned> DependentDeductionDepth = None,
8827                  bool IgnoreConstraints = false);
8828   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8829   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8830                         bool Diagnose = true);
8831 
8832   /// Declare implicit deduction guides for a class template if we've
8833   /// not already done so.
8834   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8835                                       SourceLocation Loc);
8836 
8837   QualType DeduceTemplateSpecializationFromInitializer(
8838       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8839       const InitializationKind &Kind, MultiExprArg Init);
8840 
8841   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8842                                         QualType Type, TypeSourceInfo *TSI,
8843                                         SourceRange Range, bool DirectInit,
8844                                         Expr *Init);
8845 
8846   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8847 
8848   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8849                                         SourceLocation ReturnLoc,
8850                                         Expr *&RetExpr, const AutoType *AT);
8851 
8852   FunctionTemplateDecl *getMoreSpecializedTemplate(
8853       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8854       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8855       unsigned NumCallArguments2, bool Reversed = false,
8856       bool AllowOrderingByConstraints = true);
8857   UnresolvedSetIterator
8858   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8859                      TemplateSpecCandidateSet &FailedCandidates,
8860                      SourceLocation Loc,
8861                      const PartialDiagnostic &NoneDiag,
8862                      const PartialDiagnostic &AmbigDiag,
8863                      const PartialDiagnostic &CandidateDiag,
8864                      bool Complain = true, QualType TargetType = QualType());
8865 
8866   ClassTemplatePartialSpecializationDecl *
8867   getMoreSpecializedPartialSpecialization(
8868                                   ClassTemplatePartialSpecializationDecl *PS1,
8869                                   ClassTemplatePartialSpecializationDecl *PS2,
8870                                   SourceLocation Loc);
8871 
8872   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8873                                     sema::TemplateDeductionInfo &Info);
8874 
8875   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8876       VarTemplatePartialSpecializationDecl *PS1,
8877       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8878 
8879   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8880                                     sema::TemplateDeductionInfo &Info);
8881 
8882   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8883       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8884 
8885   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8886                                   unsigned Depth, llvm::SmallBitVector &Used);
8887 
8888   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8889                                   bool OnlyDeduced,
8890                                   unsigned Depth,
8891                                   llvm::SmallBitVector &Used);
8892   void MarkDeducedTemplateParameters(
8893                                   const FunctionTemplateDecl *FunctionTemplate,
8894                                   llvm::SmallBitVector &Deduced) {
8895     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8896   }
8897   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8898                                   const FunctionTemplateDecl *FunctionTemplate,
8899                                   llvm::SmallBitVector &Deduced);
8900 
8901   //===--------------------------------------------------------------------===//
8902   // C++ Template Instantiation
8903   //
8904 
8905   MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
8906       const NamedDecl *D, const TemplateArgumentList *Innermost = nullptr,
8907       bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr);
8908 
8909   /// A context in which code is being synthesized (where a source location
8910   /// alone is not sufficient to identify the context). This covers template
8911   /// instantiation and various forms of implicitly-generated functions.
8912   struct CodeSynthesisContext {
8913     /// The kind of template instantiation we are performing
8914     enum SynthesisKind {
8915       /// We are instantiating a template declaration. The entity is
8916       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8917       TemplateInstantiation,
8918 
8919       /// We are instantiating a default argument for a template
8920       /// parameter. The Entity is the template parameter whose argument is
8921       /// being instantiated, the Template is the template, and the
8922       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8923       /// specified.
8924       DefaultTemplateArgumentInstantiation,
8925 
8926       /// We are instantiating a default argument for a function.
8927       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8928       /// provides the template arguments as specified.
8929       DefaultFunctionArgumentInstantiation,
8930 
8931       /// We are substituting explicit template arguments provided for
8932       /// a function template. The entity is a FunctionTemplateDecl.
8933       ExplicitTemplateArgumentSubstitution,
8934 
8935       /// We are substituting template argument determined as part of
8936       /// template argument deduction for either a class template
8937       /// partial specialization or a function template. The
8938       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8939       /// a TemplateDecl.
8940       DeducedTemplateArgumentSubstitution,
8941 
8942       /// We are substituting prior template arguments into a new
8943       /// template parameter. The template parameter itself is either a
8944       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8945       PriorTemplateArgumentSubstitution,
8946 
8947       /// We are checking the validity of a default template argument that
8948       /// has been used when naming a template-id.
8949       DefaultTemplateArgumentChecking,
8950 
8951       /// We are computing the exception specification for a defaulted special
8952       /// member function.
8953       ExceptionSpecEvaluation,
8954 
8955       /// We are instantiating the exception specification for a function
8956       /// template which was deferred until it was needed.
8957       ExceptionSpecInstantiation,
8958 
8959       /// We are instantiating a requirement of a requires expression.
8960       RequirementInstantiation,
8961 
8962       /// We are checking the satisfaction of a nested requirement of a requires
8963       /// expression.
8964       NestedRequirementConstraintsCheck,
8965 
8966       /// We are declaring an implicit special member function.
8967       DeclaringSpecialMember,
8968 
8969       /// We are declaring an implicit 'operator==' for a defaulted
8970       /// 'operator<=>'.
8971       DeclaringImplicitEqualityComparison,
8972 
8973       /// We are defining a synthesized function (such as a defaulted special
8974       /// member).
8975       DefiningSynthesizedFunction,
8976 
8977       // We are checking the constraints associated with a constrained entity or
8978       // the constraint expression of a concept. This includes the checks that
8979       // atomic constraints have the type 'bool' and that they can be constant
8980       // evaluated.
8981       ConstraintsCheck,
8982 
8983       // We are substituting template arguments into a constraint expression.
8984       ConstraintSubstitution,
8985 
8986       // We are normalizing a constraint expression.
8987       ConstraintNormalization,
8988 
8989       // We are substituting into the parameter mapping of an atomic constraint
8990       // during normalization.
8991       ParameterMappingSubstitution,
8992 
8993       /// We are rewriting a comparison operator in terms of an operator<=>.
8994       RewritingOperatorAsSpaceship,
8995 
8996       /// We are initializing a structured binding.
8997       InitializingStructuredBinding,
8998 
8999       /// We are marking a class as __dllexport.
9000       MarkingClassDllexported,
9001 
9002       /// We are building an implied call from __builtin_dump_struct. The
9003       /// arguments are in CallArgs.
9004       BuildingBuiltinDumpStructCall,
9005 
9006       /// Added for Template instantiation observation.
9007       /// Memoization means we are _not_ instantiating a template because
9008       /// it is already instantiated (but we entered a context where we
9009       /// would have had to if it was not already instantiated).
9010       Memoization
9011     } Kind;
9012 
9013     /// Was the enclosing context a non-instantiation SFINAE context?
9014     bool SavedInNonInstantiationSFINAEContext;
9015 
9016     /// The point of instantiation or synthesis within the source code.
9017     SourceLocation PointOfInstantiation;
9018 
9019     /// The entity that is being synthesized.
9020     Decl *Entity;
9021 
9022     /// The template (or partial specialization) in which we are
9023     /// performing the instantiation, for substitutions of prior template
9024     /// arguments.
9025     NamedDecl *Template;
9026 
9027     union {
9028       /// The list of template arguments we are substituting, if they
9029       /// are not part of the entity.
9030       const TemplateArgument *TemplateArgs;
9031 
9032       /// The list of argument expressions in a synthesized call.
9033       const Expr *const *CallArgs;
9034     };
9035 
9036     // FIXME: Wrap this union around more members, or perhaps store the
9037     // kind-specific members in the RAII object owning the context.
9038     union {
9039       /// The number of template arguments in TemplateArgs.
9040       unsigned NumTemplateArgs;
9041 
9042       /// The number of expressions in CallArgs.
9043       unsigned NumCallArgs;
9044 
9045       /// The special member being declared or defined.
9046       CXXSpecialMember SpecialMember;
9047     };
9048 
9049     ArrayRef<TemplateArgument> template_arguments() const {
9050       assert(Kind != DeclaringSpecialMember);
9051       return {TemplateArgs, NumTemplateArgs};
9052     }
9053 
9054     /// The template deduction info object associated with the
9055     /// substitution or checking of explicit or deduced template arguments.
9056     sema::TemplateDeductionInfo *DeductionInfo;
9057 
9058     /// The source range that covers the construct that cause
9059     /// the instantiation, e.g., the template-id that causes a class
9060     /// template instantiation.
9061     SourceRange InstantiationRange;
9062 
9063     CodeSynthesisContext()
9064         : Kind(TemplateInstantiation),
9065           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
9066           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
9067           DeductionInfo(nullptr) {}
9068 
9069     /// Determines whether this template is an actual instantiation
9070     /// that should be counted toward the maximum instantiation depth.
9071     bool isInstantiationRecord() const;
9072   };
9073 
9074   /// List of active code synthesis contexts.
9075   ///
9076   /// This vector is treated as a stack. As synthesis of one entity requires
9077   /// synthesis of another, additional contexts are pushed onto the stack.
9078   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
9079 
9080   /// Specializations whose definitions are currently being instantiated.
9081   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
9082 
9083   /// Non-dependent types used in templates that have already been instantiated
9084   /// by some template instantiation.
9085   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
9086 
9087   /// Extra modules inspected when performing a lookup during a template
9088   /// instantiation. Computed lazily.
9089   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
9090 
9091   /// Cache of additional modules that should be used for name lookup
9092   /// within the current template instantiation. Computed lazily; use
9093   /// getLookupModules() to get a complete set.
9094   llvm::DenseSet<Module*> LookupModulesCache;
9095 
9096   /// Get the set of additional modules that should be checked during
9097   /// name lookup. A module and its imports become visible when instanting a
9098   /// template defined within it.
9099   llvm::DenseSet<Module*> &getLookupModules();
9100 
9101   /// Map from the most recent declaration of a namespace to the most
9102   /// recent visible declaration of that namespace.
9103   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
9104 
9105   /// Whether we are in a SFINAE context that is not associated with
9106   /// template instantiation.
9107   ///
9108   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
9109   /// of a template instantiation or template argument deduction.
9110   bool InNonInstantiationSFINAEContext;
9111 
9112   /// The number of \p CodeSynthesisContexts that are not template
9113   /// instantiations and, therefore, should not be counted as part of the
9114   /// instantiation depth.
9115   ///
9116   /// When the instantiation depth reaches the user-configurable limit
9117   /// \p LangOptions::InstantiationDepth we will abort instantiation.
9118   // FIXME: Should we have a similar limit for other forms of synthesis?
9119   unsigned NonInstantiationEntries;
9120 
9121   /// The depth of the context stack at the point when the most recent
9122   /// error or warning was produced.
9123   ///
9124   /// This value is used to suppress printing of redundant context stacks
9125   /// when there are multiple errors or warnings in the same instantiation.
9126   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
9127   unsigned LastEmittedCodeSynthesisContextDepth = 0;
9128 
9129   /// The template instantiation callbacks to trace or track
9130   /// instantiations (objects can be chained).
9131   ///
9132   /// This callbacks is used to print, trace or track template
9133   /// instantiations as they are being constructed.
9134   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
9135       TemplateInstCallbacks;
9136 
9137   /// The current index into pack expansion arguments that will be
9138   /// used for substitution of parameter packs.
9139   ///
9140   /// The pack expansion index will be -1 to indicate that parameter packs
9141   /// should be instantiated as themselves. Otherwise, the index specifies
9142   /// which argument within the parameter pack will be used for substitution.
9143   int ArgumentPackSubstitutionIndex;
9144 
9145   /// RAII object used to change the argument pack substitution index
9146   /// within a \c Sema object.
9147   ///
9148   /// See \c ArgumentPackSubstitutionIndex for more information.
9149   class ArgumentPackSubstitutionIndexRAII {
9150     Sema &Self;
9151     int OldSubstitutionIndex;
9152 
9153   public:
9154     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
9155       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
9156       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
9157     }
9158 
9159     ~ArgumentPackSubstitutionIndexRAII() {
9160       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
9161     }
9162   };
9163 
9164   friend class ArgumentPackSubstitutionRAII;
9165 
9166   /// For each declaration that involved template argument deduction, the
9167   /// set of diagnostics that were suppressed during that template argument
9168   /// deduction.
9169   ///
9170   /// FIXME: Serialize this structure to the AST file.
9171   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
9172     SuppressedDiagnosticsMap;
9173   SuppressedDiagnosticsMap SuppressedDiagnostics;
9174 
9175   /// A stack object to be created when performing template
9176   /// instantiation.
9177   ///
9178   /// Construction of an object of type \c InstantiatingTemplate
9179   /// pushes the current instantiation onto the stack of active
9180   /// instantiations. If the size of this stack exceeds the maximum
9181   /// number of recursive template instantiations, construction
9182   /// produces an error and evaluates true.
9183   ///
9184   /// Destruction of this object will pop the named instantiation off
9185   /// the stack.
9186   struct InstantiatingTemplate {
9187     /// Note that we are instantiating a class template,
9188     /// function template, variable template, alias template,
9189     /// or a member thereof.
9190     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9191                           Decl *Entity,
9192                           SourceRange InstantiationRange = SourceRange());
9193 
9194     struct ExceptionSpecification {};
9195     /// Note that we are instantiating an exception specification
9196     /// of a function template.
9197     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9198                           FunctionDecl *Entity, ExceptionSpecification,
9199                           SourceRange InstantiationRange = SourceRange());
9200 
9201     /// Note that we are instantiating a default argument in a
9202     /// template-id.
9203     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9204                           TemplateParameter Param, TemplateDecl *Template,
9205                           ArrayRef<TemplateArgument> TemplateArgs,
9206                           SourceRange InstantiationRange = SourceRange());
9207 
9208     /// Note that we are substituting either explicitly-specified or
9209     /// deduced template arguments during function template argument deduction.
9210     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9211                           FunctionTemplateDecl *FunctionTemplate,
9212                           ArrayRef<TemplateArgument> TemplateArgs,
9213                           CodeSynthesisContext::SynthesisKind Kind,
9214                           sema::TemplateDeductionInfo &DeductionInfo,
9215                           SourceRange InstantiationRange = SourceRange());
9216 
9217     /// Note that we are instantiating as part of template
9218     /// argument deduction for a class template declaration.
9219     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9220                           TemplateDecl *Template,
9221                           ArrayRef<TemplateArgument> TemplateArgs,
9222                           sema::TemplateDeductionInfo &DeductionInfo,
9223                           SourceRange InstantiationRange = SourceRange());
9224 
9225     /// Note that we are instantiating as part of template
9226     /// argument deduction for a class template partial
9227     /// specialization.
9228     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9229                           ClassTemplatePartialSpecializationDecl *PartialSpec,
9230                           ArrayRef<TemplateArgument> TemplateArgs,
9231                           sema::TemplateDeductionInfo &DeductionInfo,
9232                           SourceRange InstantiationRange = SourceRange());
9233 
9234     /// Note that we are instantiating as part of template
9235     /// argument deduction for a variable template partial
9236     /// specialization.
9237     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9238                           VarTemplatePartialSpecializationDecl *PartialSpec,
9239                           ArrayRef<TemplateArgument> TemplateArgs,
9240                           sema::TemplateDeductionInfo &DeductionInfo,
9241                           SourceRange InstantiationRange = SourceRange());
9242 
9243     /// Note that we are instantiating a default argument for a function
9244     /// parameter.
9245     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9246                           ParmVarDecl *Param,
9247                           ArrayRef<TemplateArgument> TemplateArgs,
9248                           SourceRange InstantiationRange = SourceRange());
9249 
9250     /// Note that we are substituting prior template arguments into a
9251     /// non-type parameter.
9252     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9253                           NamedDecl *Template,
9254                           NonTypeTemplateParmDecl *Param,
9255                           ArrayRef<TemplateArgument> TemplateArgs,
9256                           SourceRange InstantiationRange);
9257 
9258     /// Note that we are substituting prior template arguments into a
9259     /// template template parameter.
9260     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9261                           NamedDecl *Template,
9262                           TemplateTemplateParmDecl *Param,
9263                           ArrayRef<TemplateArgument> TemplateArgs,
9264                           SourceRange InstantiationRange);
9265 
9266     /// Note that we are checking the default template argument
9267     /// against the template parameter for a given template-id.
9268     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9269                           TemplateDecl *Template,
9270                           NamedDecl *Param,
9271                           ArrayRef<TemplateArgument> TemplateArgs,
9272                           SourceRange InstantiationRange);
9273 
9274     struct ConstraintsCheck {};
9275     /// \brief Note that we are checking the constraints associated with some
9276     /// constrained entity (a concept declaration or a template with associated
9277     /// constraints).
9278     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9279                           ConstraintsCheck, NamedDecl *Template,
9280                           ArrayRef<TemplateArgument> TemplateArgs,
9281                           SourceRange InstantiationRange);
9282 
9283     struct ConstraintSubstitution {};
9284     /// \brief Note that we are checking a constraint expression associated
9285     /// with a template declaration or as part of the satisfaction check of a
9286     /// concept.
9287     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9288                           ConstraintSubstitution, NamedDecl *Template,
9289                           sema::TemplateDeductionInfo &DeductionInfo,
9290                           SourceRange InstantiationRange);
9291 
9292     struct ConstraintNormalization {};
9293     /// \brief Note that we are normalizing a constraint expression.
9294     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9295                           ConstraintNormalization, NamedDecl *Template,
9296                           SourceRange InstantiationRange);
9297 
9298     struct ParameterMappingSubstitution {};
9299     /// \brief Note that we are subtituting into the parameter mapping of an
9300     /// atomic constraint during constraint normalization.
9301     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9302                           ParameterMappingSubstitution, NamedDecl *Template,
9303                           SourceRange InstantiationRange);
9304 
9305     /// \brief Note that we are substituting template arguments into a part of
9306     /// a requirement of a requires expression.
9307     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9308                           concepts::Requirement *Req,
9309                           sema::TemplateDeductionInfo &DeductionInfo,
9310                           SourceRange InstantiationRange = SourceRange());
9311 
9312     /// \brief Note that we are checking the satisfaction of the constraint
9313     /// expression inside of a nested requirement.
9314     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9315                           concepts::NestedRequirement *Req, ConstraintsCheck,
9316                           SourceRange InstantiationRange = SourceRange());
9317 
9318     /// Note that we have finished instantiating this template.
9319     void Clear();
9320 
9321     ~InstantiatingTemplate() { Clear(); }
9322 
9323     /// Determines whether we have exceeded the maximum
9324     /// recursive template instantiations.
9325     bool isInvalid() const { return Invalid; }
9326 
9327     /// Determine whether we are already instantiating this
9328     /// specialization in some surrounding active instantiation.
9329     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9330 
9331   private:
9332     Sema &SemaRef;
9333     bool Invalid;
9334     bool AlreadyInstantiating;
9335     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9336                                  SourceRange InstantiationRange);
9337 
9338     InstantiatingTemplate(
9339         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9340         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9341         Decl *Entity, NamedDecl *Template = nullptr,
9342         ArrayRef<TemplateArgument> TemplateArgs = None,
9343         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9344 
9345     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9346 
9347     InstantiatingTemplate&
9348     operator=(const InstantiatingTemplate&) = delete;
9349   };
9350 
9351   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9352   void popCodeSynthesisContext();
9353 
9354   /// Determine whether we are currently performing template instantiation.
9355   bool inTemplateInstantiation() const {
9356     return CodeSynthesisContexts.size() > NonInstantiationEntries;
9357   }
9358 
9359   void PrintContextStack() {
9360     if (!CodeSynthesisContexts.empty() &&
9361         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9362       PrintInstantiationStack();
9363       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9364     }
9365     if (PragmaAttributeCurrentTargetDecl)
9366       PrintPragmaAttributeInstantiationPoint();
9367   }
9368   void PrintInstantiationStack();
9369 
9370   void PrintPragmaAttributeInstantiationPoint();
9371 
9372   /// Determines whether we are currently in a context where
9373   /// template argument substitution failures are not considered
9374   /// errors.
9375   ///
9376   /// \returns An empty \c Optional if we're not in a SFINAE context.
9377   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9378   /// template-deduction context object, which can be used to capture
9379   /// diagnostics that will be suppressed.
9380   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9381 
9382   /// Determines whether we are currently in a context that
9383   /// is not evaluated as per C++ [expr] p5.
9384   bool isUnevaluatedContext() const {
9385     assert(!ExprEvalContexts.empty() &&
9386            "Must be in an expression evaluation context");
9387     return ExprEvalContexts.back().isUnevaluated();
9388   }
9389 
9390   bool isImmediateFunctionContext() const {
9391     assert(!ExprEvalContexts.empty() &&
9392            "Must be in an expression evaluation context");
9393     return ExprEvalContexts.back().isImmediateFunctionContext();
9394   }
9395 
9396   /// RAII class used to determine whether SFINAE has
9397   /// trapped any errors that occur during template argument
9398   /// deduction.
9399   class SFINAETrap {
9400     Sema &SemaRef;
9401     unsigned PrevSFINAEErrors;
9402     bool PrevInNonInstantiationSFINAEContext;
9403     bool PrevAccessCheckingSFINAE;
9404     bool PrevLastDiagnosticIgnored;
9405 
9406   public:
9407     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
9408       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9409         PrevInNonInstantiationSFINAEContext(
9410                                       SemaRef.InNonInstantiationSFINAEContext),
9411         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9412         PrevLastDiagnosticIgnored(
9413             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9414     {
9415       if (!SemaRef.isSFINAEContext())
9416         SemaRef.InNonInstantiationSFINAEContext = true;
9417       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9418     }
9419 
9420     ~SFINAETrap() {
9421       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9422       SemaRef.InNonInstantiationSFINAEContext
9423         = PrevInNonInstantiationSFINAEContext;
9424       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9425       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9426           PrevLastDiagnosticIgnored);
9427     }
9428 
9429     /// Determine whether any SFINAE errors have been trapped.
9430     bool hasErrorOccurred() const {
9431       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9432     }
9433   };
9434 
9435   /// RAII class used to indicate that we are performing provisional
9436   /// semantic analysis to determine the validity of a construct, so
9437   /// typo-correction and diagnostics in the immediate context (not within
9438   /// implicitly-instantiated templates) should be suppressed.
9439   class TentativeAnalysisScope {
9440     Sema &SemaRef;
9441     // FIXME: Using a SFINAETrap for this is a hack.
9442     SFINAETrap Trap;
9443     bool PrevDisableTypoCorrection;
9444   public:
9445     explicit TentativeAnalysisScope(Sema &SemaRef)
9446         : SemaRef(SemaRef), Trap(SemaRef, true),
9447           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9448       SemaRef.DisableTypoCorrection = true;
9449     }
9450     ~TentativeAnalysisScope() {
9451       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9452     }
9453   };
9454 
9455   /// The current instantiation scope used to store local
9456   /// variables.
9457   LocalInstantiationScope *CurrentInstantiationScope;
9458 
9459   /// Tracks whether we are in a context where typo correction is
9460   /// disabled.
9461   bool DisableTypoCorrection;
9462 
9463   /// The number of typos corrected by CorrectTypo.
9464   unsigned TyposCorrected;
9465 
9466   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9467   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9468 
9469   /// A cache containing identifiers for which typo correction failed and
9470   /// their locations, so that repeated attempts to correct an identifier in a
9471   /// given location are ignored if typo correction already failed for it.
9472   IdentifierSourceLocations TypoCorrectionFailures;
9473 
9474   /// Worker object for performing CFG-based warnings.
9475   sema::AnalysisBasedWarnings AnalysisWarnings;
9476   threadSafety::BeforeSet *ThreadSafetyDeclCache;
9477 
9478   /// An entity for which implicit template instantiation is required.
9479   ///
9480   /// The source location associated with the declaration is the first place in
9481   /// the source code where the declaration was "used". It is not necessarily
9482   /// the point of instantiation (which will be either before or after the
9483   /// namespace-scope declaration that triggered this implicit instantiation),
9484   /// However, it is the location that diagnostics should generally refer to,
9485   /// because users will need to know what code triggered the instantiation.
9486   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9487 
9488   /// The queue of implicit template instantiations that are required
9489   /// but have not yet been performed.
9490   std::deque<PendingImplicitInstantiation> PendingInstantiations;
9491 
9492   /// Queue of implicit template instantiations that cannot be performed
9493   /// eagerly.
9494   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9495 
9496   class GlobalEagerInstantiationScope {
9497   public:
9498     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9499         : S(S), Enabled(Enabled) {
9500       if (!Enabled) return;
9501 
9502       SavedPendingInstantiations.swap(S.PendingInstantiations);
9503       SavedVTableUses.swap(S.VTableUses);
9504     }
9505 
9506     void perform() {
9507       if (Enabled) {
9508         S.DefineUsedVTables();
9509         S.PerformPendingInstantiations();
9510       }
9511     }
9512 
9513     ~GlobalEagerInstantiationScope() {
9514       if (!Enabled) return;
9515 
9516       // Restore the set of pending vtables.
9517       assert(S.VTableUses.empty() &&
9518              "VTableUses should be empty before it is discarded.");
9519       S.VTableUses.swap(SavedVTableUses);
9520 
9521       // Restore the set of pending implicit instantiations.
9522       if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9523         assert(S.PendingInstantiations.empty() &&
9524                "PendingInstantiations should be empty before it is discarded.");
9525         S.PendingInstantiations.swap(SavedPendingInstantiations);
9526       } else {
9527         // Template instantiations in the PCH may be delayed until the TU.
9528         S.PendingInstantiations.swap(SavedPendingInstantiations);
9529         S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9530                                        SavedPendingInstantiations.begin(),
9531                                        SavedPendingInstantiations.end());
9532       }
9533     }
9534 
9535   private:
9536     Sema &S;
9537     SmallVector<VTableUse, 16> SavedVTableUses;
9538     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9539     bool Enabled;
9540   };
9541 
9542   /// The queue of implicit template instantiations that are required
9543   /// and must be performed within the current local scope.
9544   ///
9545   /// This queue is only used for member functions of local classes in
9546   /// templates, which must be instantiated in the same scope as their
9547   /// enclosing function, so that they can reference function-local
9548   /// types, static variables, enumerators, etc.
9549   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9550 
9551   class LocalEagerInstantiationScope {
9552   public:
9553     LocalEagerInstantiationScope(Sema &S) : S(S) {
9554       SavedPendingLocalImplicitInstantiations.swap(
9555           S.PendingLocalImplicitInstantiations);
9556     }
9557 
9558     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9559 
9560     ~LocalEagerInstantiationScope() {
9561       assert(S.PendingLocalImplicitInstantiations.empty() &&
9562              "there shouldn't be any pending local implicit instantiations");
9563       SavedPendingLocalImplicitInstantiations.swap(
9564           S.PendingLocalImplicitInstantiations);
9565     }
9566 
9567   private:
9568     Sema &S;
9569     std::deque<PendingImplicitInstantiation>
9570         SavedPendingLocalImplicitInstantiations;
9571   };
9572 
9573   /// A helper class for building up ExtParameterInfos.
9574   class ExtParameterInfoBuilder {
9575     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9576     bool HasInteresting = false;
9577 
9578   public:
9579     /// Set the ExtParameterInfo for the parameter at the given index,
9580     ///
9581     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9582       assert(Infos.size() <= index);
9583       Infos.resize(index);
9584       Infos.push_back(info);
9585 
9586       if (!HasInteresting)
9587         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9588     }
9589 
9590     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9591     /// ExtParameterInfo array we've built up.
9592     const FunctionProtoType::ExtParameterInfo *
9593     getPointerOrNull(unsigned numParams) {
9594       if (!HasInteresting) return nullptr;
9595       Infos.resize(numParams);
9596       return Infos.data();
9597     }
9598   };
9599 
9600   void PerformPendingInstantiations(bool LocalOnly = false);
9601 
9602   TypeSourceInfo *SubstType(TypeSourceInfo *T,
9603                             const MultiLevelTemplateArgumentList &TemplateArgs,
9604                             SourceLocation Loc, DeclarationName Entity,
9605                             bool AllowDeducedTST = false);
9606 
9607   QualType SubstType(QualType T,
9608                      const MultiLevelTemplateArgumentList &TemplateArgs,
9609                      SourceLocation Loc, DeclarationName Entity);
9610 
9611   TypeSourceInfo *SubstType(TypeLoc TL,
9612                             const MultiLevelTemplateArgumentList &TemplateArgs,
9613                             SourceLocation Loc, DeclarationName Entity);
9614 
9615   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9616                             const MultiLevelTemplateArgumentList &TemplateArgs,
9617                                         SourceLocation Loc,
9618                                         DeclarationName Entity,
9619                                         CXXRecordDecl *ThisContext,
9620                                         Qualifiers ThisTypeQuals);
9621   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9622                           const MultiLevelTemplateArgumentList &Args);
9623   bool SubstExceptionSpec(SourceLocation Loc,
9624                           FunctionProtoType::ExceptionSpecInfo &ESI,
9625                           SmallVectorImpl<QualType> &ExceptionStorage,
9626                           const MultiLevelTemplateArgumentList &Args);
9627   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9628                             const MultiLevelTemplateArgumentList &TemplateArgs,
9629                                 int indexAdjustment,
9630                                 Optional<unsigned> NumExpansions,
9631                                 bool ExpectParameterPack);
9632   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9633                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9634                       const MultiLevelTemplateArgumentList &TemplateArgs,
9635                       SmallVectorImpl<QualType> &ParamTypes,
9636                       SmallVectorImpl<ParmVarDecl *> *OutParams,
9637                       ExtParameterInfoBuilder &ParamInfos);
9638   ExprResult SubstExpr(Expr *E,
9639                        const MultiLevelTemplateArgumentList &TemplateArgs);
9640 
9641   /// Substitute the given template arguments into a list of
9642   /// expressions, expanding pack expansions if required.
9643   ///
9644   /// \param Exprs The list of expressions to substitute into.
9645   ///
9646   /// \param IsCall Whether this is some form of call, in which case
9647   /// default arguments will be dropped.
9648   ///
9649   /// \param TemplateArgs The set of template arguments to substitute.
9650   ///
9651   /// \param Outputs Will receive all of the substituted arguments.
9652   ///
9653   /// \returns true if an error occurred, false otherwise.
9654   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9655                   const MultiLevelTemplateArgumentList &TemplateArgs,
9656                   SmallVectorImpl<Expr *> &Outputs);
9657 
9658   StmtResult SubstStmt(Stmt *S,
9659                        const MultiLevelTemplateArgumentList &TemplateArgs);
9660 
9661   TemplateParameterList *
9662   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9663                       const MultiLevelTemplateArgumentList &TemplateArgs);
9664 
9665   bool
9666   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9667                          const MultiLevelTemplateArgumentList &TemplateArgs,
9668                          TemplateArgumentListInfo &Outputs);
9669 
9670 
9671   Decl *SubstDecl(Decl *D, DeclContext *Owner,
9672                   const MultiLevelTemplateArgumentList &TemplateArgs);
9673 
9674   /// Substitute the name and return type of a defaulted 'operator<=>' to form
9675   /// an implicit 'operator=='.
9676   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9677                                            FunctionDecl *Spaceship);
9678 
9679   ExprResult SubstInitializer(Expr *E,
9680                        const MultiLevelTemplateArgumentList &TemplateArgs,
9681                        bool CXXDirectInit);
9682 
9683   bool
9684   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9685                       CXXRecordDecl *Pattern,
9686                       const MultiLevelTemplateArgumentList &TemplateArgs);
9687 
9688   bool
9689   InstantiateClass(SourceLocation PointOfInstantiation,
9690                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9691                    const MultiLevelTemplateArgumentList &TemplateArgs,
9692                    TemplateSpecializationKind TSK,
9693                    bool Complain = true);
9694 
9695   bool InstantiateEnum(SourceLocation PointOfInstantiation,
9696                        EnumDecl *Instantiation, EnumDecl *Pattern,
9697                        const MultiLevelTemplateArgumentList &TemplateArgs,
9698                        TemplateSpecializationKind TSK);
9699 
9700   bool InstantiateInClassInitializer(
9701       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9702       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9703 
9704   struct LateInstantiatedAttribute {
9705     const Attr *TmplAttr;
9706     LocalInstantiationScope *Scope;
9707     Decl *NewDecl;
9708 
9709     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9710                               Decl *D)
9711       : TmplAttr(A), Scope(S), NewDecl(D)
9712     { }
9713   };
9714   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9715 
9716   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9717                         const Decl *Pattern, Decl *Inst,
9718                         LateInstantiatedAttrVec *LateAttrs = nullptr,
9719                         LocalInstantiationScope *OuterMostScope = nullptr);
9720 
9721   void
9722   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9723                           const Decl *Pattern, Decl *Inst,
9724                           LateInstantiatedAttrVec *LateAttrs = nullptr,
9725                           LocalInstantiationScope *OuterMostScope = nullptr);
9726 
9727   void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
9728 
9729   bool usesPartialOrExplicitSpecialization(
9730       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9731 
9732   bool
9733   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9734                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9735                            TemplateSpecializationKind TSK,
9736                            bool Complain = true);
9737 
9738   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9739                                CXXRecordDecl *Instantiation,
9740                             const MultiLevelTemplateArgumentList &TemplateArgs,
9741                                TemplateSpecializationKind TSK);
9742 
9743   void InstantiateClassTemplateSpecializationMembers(
9744                                           SourceLocation PointOfInstantiation,
9745                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9746                                                 TemplateSpecializationKind TSK);
9747 
9748   NestedNameSpecifierLoc
9749   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9750                            const MultiLevelTemplateArgumentList &TemplateArgs);
9751 
9752   DeclarationNameInfo
9753   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9754                            const MultiLevelTemplateArgumentList &TemplateArgs);
9755   TemplateName
9756   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9757                     SourceLocation Loc,
9758                     const MultiLevelTemplateArgumentList &TemplateArgs);
9759 
9760   bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
9761                            const MultiLevelTemplateArgumentList &TemplateArgs);
9762 
9763   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9764                                   ParmVarDecl *Param);
9765   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9766                                 FunctionDecl *Function);
9767   bool CheckInstantiatedFunctionTemplateConstraints(
9768       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9769       ArrayRef<TemplateArgument> TemplateArgs,
9770       ConstraintSatisfaction &Satisfaction);
9771   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9772                                                const TemplateArgumentList *Args,
9773                                                SourceLocation Loc);
9774   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9775                                      FunctionDecl *Function,
9776                                      bool Recursive = false,
9777                                      bool DefinitionRequired = false,
9778                                      bool AtEndOfTU = false);
9779   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9780       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9781       const TemplateArgumentList &TemplateArgList,
9782       const TemplateArgumentListInfo &TemplateArgsInfo,
9783       SmallVectorImpl<TemplateArgument> &Converted,
9784       SourceLocation PointOfInstantiation,
9785       LateInstantiatedAttrVec *LateAttrs = nullptr,
9786       LocalInstantiationScope *StartingScope = nullptr);
9787   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9788       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9789       const MultiLevelTemplateArgumentList &TemplateArgs);
9790   void
9791   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9792                              const MultiLevelTemplateArgumentList &TemplateArgs,
9793                              LateInstantiatedAttrVec *LateAttrs,
9794                              DeclContext *Owner,
9795                              LocalInstantiationScope *StartingScope,
9796                              bool InstantiatingVarTemplate = false,
9797                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9798 
9799   void InstantiateVariableInitializer(
9800       VarDecl *Var, VarDecl *OldVar,
9801       const MultiLevelTemplateArgumentList &TemplateArgs);
9802   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9803                                      VarDecl *Var, bool Recursive = false,
9804                                      bool DefinitionRequired = false,
9805                                      bool AtEndOfTU = false);
9806 
9807   void InstantiateMemInitializers(CXXConstructorDecl *New,
9808                                   const CXXConstructorDecl *Tmpl,
9809                             const MultiLevelTemplateArgumentList &TemplateArgs);
9810 
9811   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9812                           const MultiLevelTemplateArgumentList &TemplateArgs,
9813                           bool FindingInstantiatedContext = false);
9814   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9815                           const MultiLevelTemplateArgumentList &TemplateArgs);
9816 
9817   // Objective-C declarations.
9818   enum ObjCContainerKind {
9819     OCK_None = -1,
9820     OCK_Interface = 0,
9821     OCK_Protocol,
9822     OCK_Category,
9823     OCK_ClassExtension,
9824     OCK_Implementation,
9825     OCK_CategoryImplementation
9826   };
9827   ObjCContainerKind getObjCContainerKind() const;
9828 
9829   DeclResult actOnObjCTypeParam(Scope *S,
9830                                 ObjCTypeParamVariance variance,
9831                                 SourceLocation varianceLoc,
9832                                 unsigned index,
9833                                 IdentifierInfo *paramName,
9834                                 SourceLocation paramLoc,
9835                                 SourceLocation colonLoc,
9836                                 ParsedType typeBound);
9837 
9838   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9839                                             ArrayRef<Decl *> typeParams,
9840                                             SourceLocation rAngleLoc);
9841   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9842 
9843   ObjCInterfaceDecl *ActOnStartClassInterface(
9844       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9845       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9846       IdentifierInfo *SuperName, SourceLocation SuperLoc,
9847       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9848       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9849       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9850       const ParsedAttributesView &AttrList);
9851 
9852   void ActOnSuperClassOfClassInterface(Scope *S,
9853                                        SourceLocation AtInterfaceLoc,
9854                                        ObjCInterfaceDecl *IDecl,
9855                                        IdentifierInfo *ClassName,
9856                                        SourceLocation ClassLoc,
9857                                        IdentifierInfo *SuperName,
9858                                        SourceLocation SuperLoc,
9859                                        ArrayRef<ParsedType> SuperTypeArgs,
9860                                        SourceRange SuperTypeArgsRange);
9861 
9862   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9863                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
9864                                IdentifierInfo *SuperName,
9865                                SourceLocation SuperLoc);
9866 
9867   Decl *ActOnCompatibilityAlias(
9868                     SourceLocation AtCompatibilityAliasLoc,
9869                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
9870                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
9871 
9872   bool CheckForwardProtocolDeclarationForCircularDependency(
9873     IdentifierInfo *PName,
9874     SourceLocation &PLoc, SourceLocation PrevLoc,
9875     const ObjCList<ObjCProtocolDecl> &PList);
9876 
9877   ObjCProtocolDecl *ActOnStartProtocolInterface(
9878       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9879       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9880       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9881       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9882 
9883   ObjCCategoryDecl *ActOnStartCategoryInterface(
9884       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9885       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9886       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9887       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9888       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9889       const ParsedAttributesView &AttrList);
9890 
9891   ObjCImplementationDecl *ActOnStartClassImplementation(
9892       SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
9893       SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
9894       SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList);
9895 
9896   ObjCCategoryImplDecl *ActOnStartCategoryImplementation(
9897       SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
9898       SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
9899       const ParsedAttributesView &AttrList);
9900 
9901   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9902                                                ArrayRef<Decl *> Decls);
9903 
9904   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9905                    IdentifierInfo **IdentList,
9906                    SourceLocation *IdentLocs,
9907                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
9908                    unsigned NumElts);
9909 
9910   DeclGroupPtrTy
9911   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9912                                   ArrayRef<IdentifierLocPair> IdentList,
9913                                   const ParsedAttributesView &attrList);
9914 
9915   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9916                                ArrayRef<IdentifierLocPair> ProtocolId,
9917                                SmallVectorImpl<Decl *> &Protocols);
9918 
9919   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9920                                     SourceLocation ProtocolLoc,
9921                                     IdentifierInfo *TypeArgId,
9922                                     SourceLocation TypeArgLoc,
9923                                     bool SelectProtocolFirst = false);
9924 
9925   /// Given a list of identifiers (and their locations), resolve the
9926   /// names to either Objective-C protocol qualifiers or type
9927   /// arguments, as appropriate.
9928   void actOnObjCTypeArgsOrProtocolQualifiers(
9929          Scope *S,
9930          ParsedType baseType,
9931          SourceLocation lAngleLoc,
9932          ArrayRef<IdentifierInfo *> identifiers,
9933          ArrayRef<SourceLocation> identifierLocs,
9934          SourceLocation rAngleLoc,
9935          SourceLocation &typeArgsLAngleLoc,
9936          SmallVectorImpl<ParsedType> &typeArgs,
9937          SourceLocation &typeArgsRAngleLoc,
9938          SourceLocation &protocolLAngleLoc,
9939          SmallVectorImpl<Decl *> &protocols,
9940          SourceLocation &protocolRAngleLoc,
9941          bool warnOnIncompleteProtocols);
9942 
9943   /// Build a an Objective-C protocol-qualified 'id' type where no
9944   /// base type was specified.
9945   TypeResult actOnObjCProtocolQualifierType(
9946                SourceLocation lAngleLoc,
9947                ArrayRef<Decl *> protocols,
9948                ArrayRef<SourceLocation> protocolLocs,
9949                SourceLocation rAngleLoc);
9950 
9951   /// Build a specialized and/or protocol-qualified Objective-C type.
9952   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9953                Scope *S,
9954                SourceLocation Loc,
9955                ParsedType BaseType,
9956                SourceLocation TypeArgsLAngleLoc,
9957                ArrayRef<ParsedType> TypeArgs,
9958                SourceLocation TypeArgsRAngleLoc,
9959                SourceLocation ProtocolLAngleLoc,
9960                ArrayRef<Decl *> Protocols,
9961                ArrayRef<SourceLocation> ProtocolLocs,
9962                SourceLocation ProtocolRAngleLoc);
9963 
9964   /// Build an Objective-C type parameter type.
9965   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9966                                   SourceLocation ProtocolLAngleLoc,
9967                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9968                                   ArrayRef<SourceLocation> ProtocolLocs,
9969                                   SourceLocation ProtocolRAngleLoc,
9970                                   bool FailOnError = false);
9971 
9972   /// Build an Objective-C object pointer type.
9973   QualType BuildObjCObjectType(QualType BaseType,
9974                                SourceLocation Loc,
9975                                SourceLocation TypeArgsLAngleLoc,
9976                                ArrayRef<TypeSourceInfo *> TypeArgs,
9977                                SourceLocation TypeArgsRAngleLoc,
9978                                SourceLocation ProtocolLAngleLoc,
9979                                ArrayRef<ObjCProtocolDecl *> Protocols,
9980                                ArrayRef<SourceLocation> ProtocolLocs,
9981                                SourceLocation ProtocolRAngleLoc,
9982                                bool FailOnError = false);
9983 
9984   /// Ensure attributes are consistent with type.
9985   /// \param [in, out] Attributes The attributes to check; they will
9986   /// be modified to be consistent with \p PropertyTy.
9987   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9988                                    SourceLocation Loc,
9989                                    unsigned &Attributes,
9990                                    bool propertyInPrimaryClass);
9991 
9992   /// Process the specified property declaration and create decls for the
9993   /// setters and getters as needed.
9994   /// \param property The property declaration being processed
9995   void ProcessPropertyDecl(ObjCPropertyDecl *property);
9996 
9997 
9998   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9999                                 ObjCPropertyDecl *SuperProperty,
10000                                 const IdentifierInfo *Name,
10001                                 bool OverridingProtocolProperty);
10002 
10003   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
10004                                         ObjCInterfaceDecl *ID);
10005 
10006   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
10007                    ArrayRef<Decl *> allMethods = None,
10008                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
10009 
10010   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
10011                       SourceLocation LParenLoc,
10012                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
10013                       Selector GetterSel, Selector SetterSel,
10014                       tok::ObjCKeywordKind MethodImplKind,
10015                       DeclContext *lexicalDC = nullptr);
10016 
10017   Decl *ActOnPropertyImplDecl(Scope *S,
10018                               SourceLocation AtLoc,
10019                               SourceLocation PropertyLoc,
10020                               bool ImplKind,
10021                               IdentifierInfo *PropertyId,
10022                               IdentifierInfo *PropertyIvar,
10023                               SourceLocation PropertyIvarLoc,
10024                               ObjCPropertyQueryKind QueryKind);
10025 
10026   enum ObjCSpecialMethodKind {
10027     OSMK_None,
10028     OSMK_Alloc,
10029     OSMK_New,
10030     OSMK_Copy,
10031     OSMK_RetainingInit,
10032     OSMK_NonRetainingInit
10033   };
10034 
10035   struct ObjCArgInfo {
10036     IdentifierInfo *Name;
10037     SourceLocation NameLoc;
10038     // The Type is null if no type was specified, and the DeclSpec is invalid
10039     // in this case.
10040     ParsedType Type;
10041     ObjCDeclSpec DeclSpec;
10042 
10043     /// ArgAttrs - Attribute list for this argument.
10044     ParsedAttributesView ArgAttrs;
10045   };
10046 
10047   Decl *ActOnMethodDeclaration(
10048       Scope *S,
10049       SourceLocation BeginLoc, // location of the + or -.
10050       SourceLocation EndLoc,   // location of the ; or {.
10051       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
10052       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
10053       // optional arguments. The number of types/arguments is obtained
10054       // from the Sel.getNumArgs().
10055       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
10056       unsigned CNumArgs, // c-style args
10057       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
10058       bool isVariadic, bool MethodDefinition);
10059 
10060   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
10061                                               const ObjCObjectPointerType *OPT,
10062                                               bool IsInstance);
10063   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
10064                                            bool IsInstance);
10065 
10066   bool CheckARCMethodDecl(ObjCMethodDecl *method);
10067   bool inferObjCARCLifetime(ValueDecl *decl);
10068 
10069   void deduceOpenCLAddressSpace(ValueDecl *decl);
10070 
10071   ExprResult
10072   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
10073                             Expr *BaseExpr,
10074                             SourceLocation OpLoc,
10075                             DeclarationName MemberName,
10076                             SourceLocation MemberLoc,
10077                             SourceLocation SuperLoc, QualType SuperType,
10078                             bool Super);
10079 
10080   ExprResult
10081   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
10082                             IdentifierInfo &propertyName,
10083                             SourceLocation receiverNameLoc,
10084                             SourceLocation propertyNameLoc);
10085 
10086   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
10087 
10088   /// Describes the kind of message expression indicated by a message
10089   /// send that starts with an identifier.
10090   enum ObjCMessageKind {
10091     /// The message is sent to 'super'.
10092     ObjCSuperMessage,
10093     /// The message is an instance message.
10094     ObjCInstanceMessage,
10095     /// The message is a class message, and the identifier is a type
10096     /// name.
10097     ObjCClassMessage
10098   };
10099 
10100   ObjCMessageKind getObjCMessageKind(Scope *S,
10101                                      IdentifierInfo *Name,
10102                                      SourceLocation NameLoc,
10103                                      bool IsSuper,
10104                                      bool HasTrailingDot,
10105                                      ParsedType &ReceiverType);
10106 
10107   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
10108                                Selector Sel,
10109                                SourceLocation LBracLoc,
10110                                ArrayRef<SourceLocation> SelectorLocs,
10111                                SourceLocation RBracLoc,
10112                                MultiExprArg Args);
10113 
10114   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
10115                                QualType ReceiverType,
10116                                SourceLocation SuperLoc,
10117                                Selector Sel,
10118                                ObjCMethodDecl *Method,
10119                                SourceLocation LBracLoc,
10120                                ArrayRef<SourceLocation> SelectorLocs,
10121                                SourceLocation RBracLoc,
10122                                MultiExprArg Args,
10123                                bool isImplicit = false);
10124 
10125   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
10126                                        bool isSuperReceiver,
10127                                        SourceLocation Loc,
10128                                        Selector Sel,
10129                                        ObjCMethodDecl *Method,
10130                                        MultiExprArg Args);
10131 
10132   ExprResult ActOnClassMessage(Scope *S,
10133                                ParsedType Receiver,
10134                                Selector Sel,
10135                                SourceLocation LBracLoc,
10136                                ArrayRef<SourceLocation> SelectorLocs,
10137                                SourceLocation RBracLoc,
10138                                MultiExprArg Args);
10139 
10140   ExprResult BuildInstanceMessage(Expr *Receiver,
10141                                   QualType ReceiverType,
10142                                   SourceLocation SuperLoc,
10143                                   Selector Sel,
10144                                   ObjCMethodDecl *Method,
10145                                   SourceLocation LBracLoc,
10146                                   ArrayRef<SourceLocation> SelectorLocs,
10147                                   SourceLocation RBracLoc,
10148                                   MultiExprArg Args,
10149                                   bool isImplicit = false);
10150 
10151   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
10152                                           QualType ReceiverType,
10153                                           SourceLocation Loc,
10154                                           Selector Sel,
10155                                           ObjCMethodDecl *Method,
10156                                           MultiExprArg Args);
10157 
10158   ExprResult ActOnInstanceMessage(Scope *S,
10159                                   Expr *Receiver,
10160                                   Selector Sel,
10161                                   SourceLocation LBracLoc,
10162                                   ArrayRef<SourceLocation> SelectorLocs,
10163                                   SourceLocation RBracLoc,
10164                                   MultiExprArg Args);
10165 
10166   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
10167                                   ObjCBridgeCastKind Kind,
10168                                   SourceLocation BridgeKeywordLoc,
10169                                   TypeSourceInfo *TSInfo,
10170                                   Expr *SubExpr);
10171 
10172   ExprResult ActOnObjCBridgedCast(Scope *S,
10173                                   SourceLocation LParenLoc,
10174                                   ObjCBridgeCastKind Kind,
10175                                   SourceLocation BridgeKeywordLoc,
10176                                   ParsedType Type,
10177                                   SourceLocation RParenLoc,
10178                                   Expr *SubExpr);
10179 
10180   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
10181 
10182   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
10183 
10184   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
10185                                      CastKind &Kind);
10186 
10187   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
10188                                         QualType DestType, QualType SrcType,
10189                                         ObjCInterfaceDecl *&RelatedClass,
10190                                         ObjCMethodDecl *&ClassMethod,
10191                                         ObjCMethodDecl *&InstanceMethod,
10192                                         TypedefNameDecl *&TDNDecl,
10193                                         bool CfToNs, bool Diagnose = true);
10194 
10195   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
10196                                          QualType DestType, QualType SrcType,
10197                                          Expr *&SrcExpr, bool Diagnose = true);
10198 
10199   bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
10200                                     bool Diagnose = true);
10201 
10202   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
10203 
10204   /// Check whether the given new method is a valid override of the
10205   /// given overridden method, and set any properties that should be inherited.
10206   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
10207                                const ObjCMethodDecl *Overridden);
10208 
10209   /// Describes the compatibility of a result type with its method.
10210   enum ResultTypeCompatibilityKind {
10211     RTC_Compatible,
10212     RTC_Incompatible,
10213     RTC_Unknown
10214   };
10215 
10216   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
10217                                       ObjCMethodDecl *overridden);
10218 
10219   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
10220                                 ObjCInterfaceDecl *CurrentClass,
10221                                 ResultTypeCompatibilityKind RTC);
10222 
10223   enum PragmaOptionsAlignKind {
10224     POAK_Native,  // #pragma options align=native
10225     POAK_Natural, // #pragma options align=natural
10226     POAK_Packed,  // #pragma options align=packed
10227     POAK_Power,   // #pragma options align=power
10228     POAK_Mac68k,  // #pragma options align=mac68k
10229     POAK_Reset    // #pragma options align=reset
10230   };
10231 
10232   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
10233   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
10234                                PragmaClangSectionAction Action,
10235                                PragmaClangSectionKind SecKind, StringRef SecName);
10236 
10237   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
10238   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
10239                                SourceLocation PragmaLoc);
10240 
10241   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
10242   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
10243                        StringRef SlotLabel, Expr *Alignment);
10244 
10245   enum class PragmaAlignPackDiagnoseKind {
10246     NonDefaultStateAtInclude,
10247     ChangedStateAtExit
10248   };
10249 
10250   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10251                                          SourceLocation IncludeLoc);
10252   void DiagnoseUnterminatedPragmaAlignPack();
10253 
10254   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10255   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10256 
10257   /// ActOnPragmaMSComment - Called on well formed
10258   /// \#pragma comment(kind, "arg").
10259   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10260                             StringRef Arg);
10261 
10262   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10263   /// pointers_to_members(representation method[, general purpose
10264   /// representation]).
10265   void ActOnPragmaMSPointersToMembers(
10266       LangOptions::PragmaMSPointersToMembersKind Kind,
10267       SourceLocation PragmaLoc);
10268 
10269   /// Called on well formed \#pragma vtordisp().
10270   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10271                              SourceLocation PragmaLoc,
10272                              MSVtorDispMode Value);
10273 
10274   enum PragmaSectionKind {
10275     PSK_DataSeg,
10276     PSK_BSSSeg,
10277     PSK_ConstSeg,
10278     PSK_CodeSeg,
10279   };
10280 
10281   bool UnifySection(StringRef SectionName, int SectionFlags,
10282                     NamedDecl *TheDecl);
10283   bool UnifySection(StringRef SectionName,
10284                     int SectionFlags,
10285                     SourceLocation PragmaSectionLocation);
10286 
10287   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10288   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10289                         PragmaMsStackAction Action,
10290                         llvm::StringRef StackSlotLabel,
10291                         StringLiteral *SegmentName,
10292                         llvm::StringRef PragmaName);
10293 
10294   /// Called on well formed \#pragma section().
10295   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10296                             int SectionFlags, StringLiteral *SegmentName);
10297 
10298   /// Called on well-formed \#pragma init_seg().
10299   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10300                             StringLiteral *SegmentName);
10301 
10302   /// Called on well-formed \#pragma alloc_text().
10303   void ActOnPragmaMSAllocText(
10304       SourceLocation PragmaLocation, StringRef Section,
10305       const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
10306           &Functions);
10307 
10308   /// Called on #pragma clang __debug dump II
10309   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10310 
10311   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10312   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10313                                  StringRef Value);
10314 
10315   /// Are precise floating point semantics currently enabled?
10316   bool isPreciseFPEnabled() {
10317     return !CurFPFeatures.getAllowFPReassociate() &&
10318            !CurFPFeatures.getNoSignedZero() &&
10319            !CurFPFeatures.getAllowReciprocal() &&
10320            !CurFPFeatures.getAllowApproxFunc();
10321   }
10322 
10323   void ActOnPragmaFPEvalMethod(SourceLocation Loc,
10324                                LangOptions::FPEvalMethodKind Value);
10325 
10326   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10327   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10328                                PragmaFloatControlKind Value);
10329 
10330   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10331   void ActOnPragmaUnused(const Token &Identifier,
10332                          Scope *curScope,
10333                          SourceLocation PragmaLoc);
10334 
10335   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10336   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10337                              SourceLocation PragmaLoc);
10338 
10339   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10340                                  SourceLocation Loc);
10341   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
10342 
10343   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10344   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10345                          SourceLocation PragmaLoc,
10346                          SourceLocation WeakNameLoc);
10347 
10348   /// ActOnPragmaRedefineExtname - Called on well formed
10349   /// \#pragma redefine_extname oldname newname.
10350   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10351                                   IdentifierInfo* AliasName,
10352                                   SourceLocation PragmaLoc,
10353                                   SourceLocation WeakNameLoc,
10354                                   SourceLocation AliasNameLoc);
10355 
10356   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10357   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10358                             IdentifierInfo* AliasName,
10359                             SourceLocation PragmaLoc,
10360                             SourceLocation WeakNameLoc,
10361                             SourceLocation AliasNameLoc);
10362 
10363   /// ActOnPragmaFPContract - Called on well formed
10364   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10365   /// \#pragma clang fp contract
10366   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10367 
10368   /// Called on well formed
10369   /// \#pragma clang fp reassociate
10370   void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10371 
10372   /// ActOnPragmaFenvAccess - Called on well formed
10373   /// \#pragma STDC FENV_ACCESS
10374   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10375 
10376   /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10377   void ActOnPragmaFPExceptions(SourceLocation Loc,
10378                                LangOptions::FPExceptionModeKind);
10379 
10380   /// Called to set constant rounding mode for floating point operations.
10381   void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
10382 
10383   /// Called to set exception behavior for floating point operations.
10384   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10385 
10386   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10387   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10388   void AddAlignmentAttributesForRecord(RecordDecl *RD);
10389 
10390   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10391   void AddMsStructLayoutForRecord(RecordDecl *RD);
10392 
10393   /// PushNamespaceVisibilityAttr - Note that we've entered a
10394   /// namespace with a visibility attribute.
10395   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10396                                    SourceLocation Loc);
10397 
10398   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10399   /// add an appropriate visibility attribute.
10400   void AddPushedVisibilityAttribute(Decl *RD);
10401 
10402   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10403   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10404   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10405 
10406   /// FreeVisContext - Deallocate and null out VisContext.
10407   void FreeVisContext();
10408 
10409   /// AddCFAuditedAttribute - Check whether we're currently within
10410   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10411   /// the appropriate attribute.
10412   void AddCFAuditedAttribute(Decl *D);
10413 
10414   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10415                                      SourceLocation PragmaLoc,
10416                                      attr::ParsedSubjectMatchRuleSet Rules);
10417   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10418                                      const IdentifierInfo *Namespace);
10419 
10420   /// Called on well-formed '\#pragma clang attribute pop'.
10421   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10422                                const IdentifierInfo *Namespace);
10423 
10424   /// Adds the attributes that have been specified using the
10425   /// '\#pragma clang attribute push' directives to the given declaration.
10426   void AddPragmaAttributes(Scope *S, Decl *D);
10427 
10428   void DiagnoseUnterminatedPragmaAttribute();
10429 
10430   /// Called on well formed \#pragma clang optimize.
10431   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10432 
10433   /// #pragma optimize("[optimization-list]", on | off).
10434   void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
10435 
10436   /// Call on well formed \#pragma function.
10437   void
10438   ActOnPragmaMSFunction(SourceLocation Loc,
10439                         const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
10440 
10441   /// Get the location for the currently active "\#pragma clang optimize
10442   /// off". If this location is invalid, then the state of the pragma is "on".
10443   SourceLocation getOptimizeOffPragmaLocation() const {
10444     return OptimizeOffPragmaLocation;
10445   }
10446 
10447   /// Only called on function definitions; if there is a pragma in scope
10448   /// with the effect of a range-based optnone, consider marking the function
10449   /// with attribute optnone.
10450   void AddRangeBasedOptnone(FunctionDecl *FD);
10451 
10452   /// Only called on function definitions; if there is a `#pragma alloc_text`
10453   /// that decides which code section the function should be in, add
10454   /// attribute section to the function.
10455   void AddSectionMSAllocText(FunctionDecl *FD);
10456 
10457   /// Adds the 'optnone' attribute to the function declaration if there
10458   /// are no conflicts; Loc represents the location causing the 'optnone'
10459   /// attribute to be added (usually because of a pragma).
10460   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10461 
10462   /// Only called on function definitions; if there is a MSVC #pragma optimize
10463   /// in scope, consider changing the function's attributes based on the
10464   /// optimization list passed to the pragma.
10465   void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
10466 
10467   /// Only called on function definitions; if there is a pragma in scope
10468   /// with the effect of a range-based no_builtin, consider marking the function
10469   /// with attribute no_builtin.
10470   void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
10471 
10472   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10473   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10474                       bool IsPackExpansion);
10475   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10476                       bool IsPackExpansion);
10477 
10478   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10479   /// declaration.
10480   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10481                             Expr *OE);
10482 
10483   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10484   /// declaration.
10485   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10486                          Expr *ParamExpr);
10487 
10488   /// AddAlignValueAttr - Adds an align_value attribute to a particular
10489   /// declaration.
10490   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10491 
10492   /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10493   void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10494                          StringRef Annot, MutableArrayRef<Expr *> Args);
10495 
10496   /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
10497   /// (unless they are value dependent or type dependent). Returns false
10498   /// and emits a diagnostic if one or more of the arguments could not be
10499   /// folded into a constant.
10500   bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
10501                             MutableArrayRef<Expr *> Args);
10502 
10503   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10504   /// declaration.
10505   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10506                            Expr *MaxThreads, Expr *MinBlocks);
10507 
10508   /// AddModeAttr - Adds a mode attribute to a particular declaration.
10509   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10510                    bool InInstantiation = false);
10511 
10512   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10513                            ParameterABI ABI);
10514 
10515   enum class RetainOwnershipKind {NS, CF, OS};
10516   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10517                         RetainOwnershipKind K, bool IsTemplateInstantiation);
10518 
10519   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10520   /// attribute to a particular declaration.
10521   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10522                                       Expr *Min, Expr *Max);
10523 
10524   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10525   /// particular declaration.
10526   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10527                                Expr *Min, Expr *Max);
10528 
10529   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10530 
10531   //===--------------------------------------------------------------------===//
10532   // C++ Coroutines TS
10533   //
10534   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10535                                StringRef Keyword);
10536   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10537   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10538   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10539 
10540   ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
10541   ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
10542                                       UnresolvedLookupExpr *Lookup);
10543   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10544                                       Expr *Awaiter, bool IsImplicit = false);
10545   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
10546                                         UnresolvedLookupExpr *Lookup);
10547   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10548   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10549                                bool IsImplicit = false);
10550   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10551   bool buildCoroutineParameterMoves(SourceLocation Loc);
10552   VarDecl *buildCoroutinePromise(SourceLocation Loc);
10553   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10554   /// Lookup 'coroutine_traits' in std namespace and std::experimental
10555   /// namespace. The namespace found is recorded in Namespace.
10556   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10557                                            SourceLocation FuncLoc,
10558                                            NamespaceDecl *&Namespace);
10559   /// Check that the expression co_await promise.final_suspend() shall not be
10560   /// potentially-throwing.
10561   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10562 
10563   //===--------------------------------------------------------------------===//
10564   // OpenMP directives and clauses.
10565   //
10566 private:
10567   void *VarDataSharingAttributesStack;
10568 
10569   struct DeclareTargetContextInfo {
10570     struct MapInfo {
10571       OMPDeclareTargetDeclAttr::MapTypeTy MT;
10572       SourceLocation Loc;
10573     };
10574     /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10575     llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10576 
10577     /// The 'device_type' as parsed from the clause.
10578     OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10579 
10580     /// The directive kind, `begin declare target` or `declare target`.
10581     OpenMPDirectiveKind Kind;
10582 
10583     /// The directive with indirect clause.
10584     Optional<Expr *> Indirect;
10585 
10586     /// The directive location.
10587     SourceLocation Loc;
10588 
10589     DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
10590         : Kind(Kind), Loc(Loc) {}
10591   };
10592 
10593   /// Number of nested '#pragma omp declare target' directives.
10594   SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
10595 
10596   /// Initialization of data-sharing attributes stack.
10597   void InitDataSharingAttributesStack();
10598   void DestroyDataSharingAttributesStack();
10599   ExprResult
10600   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10601                                         bool StrictlyPositive = true,
10602                                         bool SuppressExprDiags = false);
10603   /// Returns OpenMP nesting level for current directive.
10604   unsigned getOpenMPNestingLevel() const;
10605 
10606   /// Adjusts the function scopes index for the target-based regions.
10607   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10608                                     unsigned Level) const;
10609 
10610   /// Returns the number of scopes associated with the construct on the given
10611   /// OpenMP level.
10612   int getNumberOfConstructScopes(unsigned Level) const;
10613 
10614   /// Push new OpenMP function region for non-capturing function.
10615   void pushOpenMPFunctionRegion();
10616 
10617   /// Pop OpenMP function region for non-capturing function.
10618   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10619 
10620   /// Analyzes and checks a loop nest for use by a loop transformation.
10621   ///
10622   /// \param Kind          The loop transformation directive kind.
10623   /// \param NumLoops      How many nested loops the directive is expecting.
10624   /// \param AStmt         Associated statement of the transformation directive.
10625   /// \param LoopHelpers   [out] The loop analysis result.
10626   /// \param Body          [out] The body code nested in \p NumLoops loop.
10627   /// \param OriginalInits [out] Collection of statements and declarations that
10628   ///                      must have been executed/declared before entering the
10629   ///                      loop.
10630   ///
10631   /// \return Whether there was any error.
10632   bool checkTransformableLoopNest(
10633       OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
10634       SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
10635       Stmt *&Body,
10636       SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
10637           &OriginalInits);
10638 
10639   /// Helper to keep information about the current `omp begin/end declare
10640   /// variant` nesting.
10641   struct OMPDeclareVariantScope {
10642     /// The associated OpenMP context selector.
10643     OMPTraitInfo *TI;
10644 
10645     /// The associated OpenMP context selector mangling.
10646     std::string NameSuffix;
10647 
10648     OMPDeclareVariantScope(OMPTraitInfo &TI);
10649   };
10650 
10651   /// Return the OMPTraitInfo for the surrounding scope, if any.
10652   OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10653     return OMPDeclareVariantScopes.empty() ? nullptr
10654                                            : OMPDeclareVariantScopes.back().TI;
10655   }
10656 
10657   /// The current `omp begin/end declare variant` scopes.
10658   SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10659 
10660   /// The current `omp begin/end assumes` scopes.
10661   SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
10662 
10663   /// All `omp assumes` we encountered so far.
10664   SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
10665 
10666 public:
10667   /// The declarator \p D defines a function in the scope \p S which is nested
10668   /// in an `omp begin/end declare variant` scope. In this method we create a
10669   /// declaration for \p D and rename \p D according to the OpenMP context
10670   /// selector of the surrounding scope. Return all base functions in \p Bases.
10671   void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10672       Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10673       SmallVectorImpl<FunctionDecl *> &Bases);
10674 
10675   /// Register \p D as specialization of all base functions in \p Bases in the
10676   /// current `omp begin/end declare variant` scope.
10677   void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10678       Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10679 
10680   /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
10681   void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
10682 
10683   /// Can we exit an OpenMP declare variant scope at the moment.
10684   bool isInOpenMPDeclareVariantScope() const {
10685     return !OMPDeclareVariantScopes.empty();
10686   }
10687 
10688   /// Given the potential call expression \p Call, determine if there is a
10689   /// specialization via the OpenMP declare variant mechanism available. If
10690   /// there is, return the specialized call expression, otherwise return the
10691   /// original \p Call.
10692   ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10693                              SourceLocation LParenLoc, MultiExprArg ArgExprs,
10694                              SourceLocation RParenLoc, Expr *ExecConfig);
10695 
10696   /// Handle a `omp begin declare variant`.
10697   void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10698 
10699   /// Handle a `omp end declare variant`.
10700   void ActOnOpenMPEndDeclareVariant();
10701 
10702   /// Checks if the variant/multiversion functions are compatible.
10703   bool areMultiversionVariantFunctionsCompatible(
10704       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10705       const PartialDiagnostic &NoProtoDiagID,
10706       const PartialDiagnosticAt &NoteCausedDiagIDAt,
10707       const PartialDiagnosticAt &NoSupportDiagIDAt,
10708       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10709       bool ConstexprSupported, bool CLinkageMayDiffer);
10710 
10711   /// Function tries to capture lambda's captured variables in the OpenMP region
10712   /// before the original lambda is captured.
10713   void tryCaptureOpenMPLambdas(ValueDecl *V);
10714 
10715   /// Return true if the provided declaration \a VD should be captured by
10716   /// reference.
10717   /// \param Level Relative level of nested OpenMP construct for that the check
10718   /// is performed.
10719   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10720   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10721                              unsigned OpenMPCaptureLevel) const;
10722 
10723   /// Check if the specified variable is used in one of the private
10724   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10725   /// constructs.
10726   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10727                                 unsigned StopAt = 0);
10728 
10729   /// The member expression(this->fd) needs to be rebuilt in the template
10730   /// instantiation to generate private copy for OpenMP when default
10731   /// clause is used. The function will return true if default
10732   /// cluse is used.
10733   bool isOpenMPRebuildMemberExpr(ValueDecl *D);
10734 
10735   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10736                                    ExprObjectKind OK, SourceLocation Loc);
10737 
10738   /// If the current region is a loop-based region, mark the start of the loop
10739   /// construct.
10740   void startOpenMPLoop();
10741 
10742   /// If the current region is a range loop-based region, mark the start of the
10743   /// loop construct.
10744   void startOpenMPCXXRangeFor();
10745 
10746   /// Check if the specified variable is used in 'private' clause.
10747   /// \param Level Relative level of nested OpenMP construct for that the check
10748   /// is performed.
10749   OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10750                                        unsigned CapLevel) const;
10751 
10752   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10753   /// for \p FD based on DSA for the provided corresponding captured declaration
10754   /// \p D.
10755   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10756 
10757   /// Check if the specified variable is captured  by 'target' directive.
10758   /// \param Level Relative level of nested OpenMP construct for that the check
10759   /// is performed.
10760   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10761                                   unsigned CaptureLevel) const;
10762 
10763   /// Check if the specified global variable must be captured  by outer capture
10764   /// regions.
10765   /// \param Level Relative level of nested OpenMP construct for that
10766   /// the check is performed.
10767   bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10768                                   unsigned CaptureLevel) const;
10769 
10770   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10771                                                     Expr *Op);
10772   /// Called on start of new data sharing attribute block.
10773   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10774                            const DeclarationNameInfo &DirName, Scope *CurScope,
10775                            SourceLocation Loc);
10776   /// Start analysis of clauses.
10777   void StartOpenMPClause(OpenMPClauseKind K);
10778   /// End analysis of clauses.
10779   void EndOpenMPClause();
10780   /// Called on end of data sharing attribute block.
10781   void EndOpenMPDSABlock(Stmt *CurDirective);
10782 
10783   /// Check if the current region is an OpenMP loop region and if it is,
10784   /// mark loop control variable, used in \p Init for loop initialization, as
10785   /// private by default.
10786   /// \param Init First part of the for loop.
10787   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10788 
10789   /// Called on well-formed '\#pragma omp metadirective' after parsing
10790   /// of the  associated statement.
10791   StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
10792                                       Stmt *AStmt, SourceLocation StartLoc,
10793                                       SourceLocation EndLoc);
10794 
10795   // OpenMP directives and clauses.
10796   /// Called on correct id-expression from the '#pragma omp
10797   /// threadprivate'.
10798   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10799                                      const DeclarationNameInfo &Id,
10800                                      OpenMPDirectiveKind Kind);
10801   /// Called on well-formed '#pragma omp threadprivate'.
10802   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10803                                      SourceLocation Loc,
10804                                      ArrayRef<Expr *> VarList);
10805   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10806   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10807                                                   ArrayRef<Expr *> VarList);
10808   /// Called on well-formed '#pragma omp allocate'.
10809   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10810                                               ArrayRef<Expr *> VarList,
10811                                               ArrayRef<OMPClause *> Clauses,
10812                                               DeclContext *Owner = nullptr);
10813 
10814   /// Called on well-formed '#pragma omp [begin] assume[s]'.
10815   void ActOnOpenMPAssumesDirective(SourceLocation Loc,
10816                                    OpenMPDirectiveKind DKind,
10817                                    ArrayRef<std::string> Assumptions,
10818                                    bool SkippedClauses);
10819 
10820   /// Check if there is an active global `omp begin assumes` directive.
10821   bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
10822 
10823   /// Check if there is an active global `omp assumes` directive.
10824   bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
10825 
10826   /// Called on well-formed '#pragma omp end assumes'.
10827   void ActOnOpenMPEndAssumesDirective();
10828 
10829   /// Called on well-formed '#pragma omp requires'.
10830   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10831                                               ArrayRef<OMPClause *> ClauseList);
10832   /// Check restrictions on Requires directive
10833   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10834                                         ArrayRef<OMPClause *> Clauses);
10835   /// Check if the specified type is allowed to be used in 'omp declare
10836   /// reduction' construct.
10837   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10838                                            TypeResult ParsedType);
10839   /// Called on start of '#pragma omp declare reduction'.
10840   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10841       Scope *S, DeclContext *DC, DeclarationName Name,
10842       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10843       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10844   /// Initialize declare reduction construct initializer.
10845   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10846   /// Finish current declare reduction construct initializer.
10847   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10848   /// Initialize declare reduction construct initializer.
10849   /// \return omp_priv variable.
10850   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10851   /// Finish current declare reduction construct initializer.
10852   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10853                                                  VarDecl *OmpPrivParm);
10854   /// Called at the end of '#pragma omp declare reduction'.
10855   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10856       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10857 
10858   /// Check variable declaration in 'omp declare mapper' construct.
10859   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10860   /// Check if the specified type is allowed to be used in 'omp declare
10861   /// mapper' construct.
10862   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10863                                         TypeResult ParsedType);
10864   /// Called on start of '#pragma omp declare mapper'.
10865   DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10866       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10867       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10868       Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10869       Decl *PrevDeclInScope = nullptr);
10870   /// Build the mapper variable of '#pragma omp declare mapper'.
10871   ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10872                                                       QualType MapperType,
10873                                                       SourceLocation StartLoc,
10874                                                       DeclarationName VN);
10875   bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10876   const ValueDecl *getOpenMPDeclareMapperVarName() const;
10877 
10878   /// Called on the start of target region i.e. '#pragma omp declare target'.
10879   bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10880 
10881   /// Called at the end of target region i.e. '#pragma omp end declare target'.
10882   const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
10883 
10884   /// Called once a target context is completed, that can be when a
10885   /// '#pragma omp end declare target' was encountered or when a
10886   /// '#pragma omp declare target' without declaration-definition-seq was
10887   /// encountered.
10888   void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10889 
10890   /// Report unterminated 'omp declare target' or 'omp begin declare target' at
10891   /// the end of a compilation unit.
10892   void DiagnoseUnterminatedOpenMPDeclareTarget();
10893 
10894   /// Searches for the provided declaration name for OpenMP declare target
10895   /// directive.
10896   NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
10897                                            CXXScopeSpec &ScopeSpec,
10898                                            const DeclarationNameInfo &Id);
10899 
10900   /// Called on correct id-expression from the '#pragma omp declare target'.
10901   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10902                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
10903                                     DeclareTargetContextInfo &DTCI);
10904 
10905   /// Check declaration inside target region.
10906   void
10907   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10908                                    SourceLocation IdLoc = SourceLocation());
10909   /// Finishes analysis of the deferred functions calls that may be declared as
10910   /// host/nohost during device/host compilation.
10911   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10912                                      const FunctionDecl *Callee,
10913                                      SourceLocation Loc);
10914 
10915   /// Return true if currently in OpenMP task with untied clause context.
10916   bool isInOpenMPTaskUntiedContext() const;
10917 
10918   /// Return true inside OpenMP declare target region.
10919   bool isInOpenMPDeclareTargetContext() const {
10920     return !DeclareTargetNesting.empty();
10921   }
10922   /// Return true inside OpenMP target region.
10923   bool isInOpenMPTargetExecutionDirective() const;
10924 
10925   /// Return the number of captured regions created for an OpenMP directive.
10926   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10927 
10928   /// Initialization of captured region for OpenMP region.
10929   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10930 
10931   /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
10932   /// an OpenMP loop directive.
10933   StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
10934 
10935   /// Process a canonical OpenMP loop nest that can either be a canonical
10936   /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
10937   /// OpenMP loop transformation construct.
10938   StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
10939 
10940   /// End of OpenMP region.
10941   ///
10942   /// \param S Statement associated with the current OpenMP region.
10943   /// \param Clauses List of clauses for the current OpenMP region.
10944   ///
10945   /// \returns Statement for finished OpenMP region.
10946   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10947   StmtResult ActOnOpenMPExecutableDirective(
10948       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10949       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10950       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10951   /// Called on well-formed '\#pragma omp parallel' after parsing
10952   /// of the  associated statement.
10953   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10954                                           Stmt *AStmt,
10955                                           SourceLocation StartLoc,
10956                                           SourceLocation EndLoc);
10957   using VarsWithInheritedDSAType =
10958       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10959   /// Called on well-formed '\#pragma omp simd' after parsing
10960   /// of the associated statement.
10961   StmtResult
10962   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10963                            SourceLocation StartLoc, SourceLocation EndLoc,
10964                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
10965   /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
10966   /// the associated statement.
10967   StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
10968                                       Stmt *AStmt, SourceLocation StartLoc,
10969                                       SourceLocation EndLoc);
10970   /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
10971   /// and the associated statement.
10972   StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
10973                                         Stmt *AStmt, SourceLocation StartLoc,
10974                                         SourceLocation EndLoc);
10975   /// Called on well-formed '\#pragma omp for' after parsing
10976   /// of the associated statement.
10977   StmtResult
10978   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10979                           SourceLocation StartLoc, SourceLocation EndLoc,
10980                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
10981   /// Called on well-formed '\#pragma omp for simd' after parsing
10982   /// of the associated statement.
10983   StmtResult
10984   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10985                               SourceLocation StartLoc, SourceLocation EndLoc,
10986                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
10987   /// Called on well-formed '\#pragma omp sections' after parsing
10988   /// of the associated statement.
10989   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10990                                           Stmt *AStmt, SourceLocation StartLoc,
10991                                           SourceLocation EndLoc);
10992   /// Called on well-formed '\#pragma omp section' after parsing of the
10993   /// associated statement.
10994   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10995                                          SourceLocation EndLoc);
10996   /// Called on well-formed '\#pragma omp single' after parsing of the
10997   /// associated statement.
10998   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10999                                         Stmt *AStmt, SourceLocation StartLoc,
11000                                         SourceLocation EndLoc);
11001   /// Called on well-formed '\#pragma omp master' after parsing of the
11002   /// associated statement.
11003   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
11004                                         SourceLocation EndLoc);
11005   /// Called on well-formed '\#pragma omp critical' after parsing of the
11006   /// associated statement.
11007   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
11008                                           ArrayRef<OMPClause *> Clauses,
11009                                           Stmt *AStmt, SourceLocation StartLoc,
11010                                           SourceLocation EndLoc);
11011   /// Called on well-formed '\#pragma omp parallel for' after parsing
11012   /// of the  associated statement.
11013   StmtResult ActOnOpenMPParallelForDirective(
11014       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11015       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11016   /// Called on well-formed '\#pragma omp parallel for simd' after
11017   /// parsing of the  associated statement.
11018   StmtResult ActOnOpenMPParallelForSimdDirective(
11019       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11020       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11021   /// Called on well-formed '\#pragma omp parallel master' after
11022   /// parsing of the  associated statement.
11023   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
11024                                                 Stmt *AStmt,
11025                                                 SourceLocation StartLoc,
11026                                                 SourceLocation EndLoc);
11027   /// Called on well-formed '\#pragma omp parallel masked' after
11028   /// parsing of the associated statement.
11029   StmtResult ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses,
11030                                                 Stmt *AStmt,
11031                                                 SourceLocation StartLoc,
11032                                                 SourceLocation EndLoc);
11033   /// Called on well-formed '\#pragma omp parallel sections' after
11034   /// parsing of the  associated statement.
11035   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
11036                                                   Stmt *AStmt,
11037                                                   SourceLocation StartLoc,
11038                                                   SourceLocation EndLoc);
11039   /// Called on well-formed '\#pragma omp task' after parsing of the
11040   /// associated statement.
11041   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
11042                                       Stmt *AStmt, SourceLocation StartLoc,
11043                                       SourceLocation EndLoc);
11044   /// Called on well-formed '\#pragma omp taskyield'.
11045   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
11046                                            SourceLocation EndLoc);
11047   /// Called on well-formed '\#pragma omp barrier'.
11048   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
11049                                          SourceLocation EndLoc);
11050   /// Called on well-formed '\#pragma omp taskwait'.
11051   StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
11052                                           SourceLocation StartLoc,
11053                                           SourceLocation EndLoc);
11054   /// Called on well-formed '\#pragma omp taskgroup'.
11055   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
11056                                            Stmt *AStmt, SourceLocation StartLoc,
11057                                            SourceLocation EndLoc);
11058   /// Called on well-formed '\#pragma omp flush'.
11059   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
11060                                        SourceLocation StartLoc,
11061                                        SourceLocation EndLoc);
11062   /// Called on well-formed '\#pragma omp depobj'.
11063   StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
11064                                         SourceLocation StartLoc,
11065                                         SourceLocation EndLoc);
11066   /// Called on well-formed '\#pragma omp scan'.
11067   StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
11068                                       SourceLocation StartLoc,
11069                                       SourceLocation EndLoc);
11070   /// Called on well-formed '\#pragma omp ordered' after parsing of the
11071   /// associated statement.
11072   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
11073                                          Stmt *AStmt, SourceLocation StartLoc,
11074                                          SourceLocation EndLoc);
11075   /// Called on well-formed '\#pragma omp atomic' after parsing of the
11076   /// associated statement.
11077   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
11078                                         Stmt *AStmt, SourceLocation StartLoc,
11079                                         SourceLocation EndLoc);
11080   /// Called on well-formed '\#pragma omp target' after parsing of the
11081   /// associated statement.
11082   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
11083                                         Stmt *AStmt, SourceLocation StartLoc,
11084                                         SourceLocation EndLoc);
11085   /// Called on well-formed '\#pragma omp target data' after parsing of
11086   /// the associated statement.
11087   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
11088                                             Stmt *AStmt, SourceLocation StartLoc,
11089                                             SourceLocation EndLoc);
11090   /// Called on well-formed '\#pragma omp target enter data' after
11091   /// parsing of the associated statement.
11092   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
11093                                                  SourceLocation StartLoc,
11094                                                  SourceLocation EndLoc,
11095                                                  Stmt *AStmt);
11096   /// Called on well-formed '\#pragma omp target exit data' after
11097   /// parsing of the associated statement.
11098   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
11099                                                 SourceLocation StartLoc,
11100                                                 SourceLocation EndLoc,
11101                                                 Stmt *AStmt);
11102   /// Called on well-formed '\#pragma omp target parallel' after
11103   /// parsing of the associated statement.
11104   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
11105                                                 Stmt *AStmt,
11106                                                 SourceLocation StartLoc,
11107                                                 SourceLocation EndLoc);
11108   /// Called on well-formed '\#pragma omp target parallel for' after
11109   /// parsing of the  associated statement.
11110   StmtResult ActOnOpenMPTargetParallelForDirective(
11111       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11112       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11113   /// Called on well-formed '\#pragma omp teams' after parsing of the
11114   /// associated statement.
11115   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
11116                                        Stmt *AStmt, SourceLocation StartLoc,
11117                                        SourceLocation EndLoc);
11118   /// Called on well-formed '\#pragma omp teams loop' after parsing of the
11119   /// associated statement.
11120   StmtResult ActOnOpenMPTeamsGenericLoopDirective(
11121       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11122       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11123   /// Called on well-formed '\#pragma omp target teams loop' after parsing of
11124   /// the associated statement.
11125   StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective(
11126       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11127       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11128   /// Called on well-formed '\#pragma omp parallel loop' after parsing of the
11129   /// associated statement.
11130   StmtResult ActOnOpenMPParallelGenericLoopDirective(
11131       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11132       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11133   /// Called on well-formed '\#pragma omp target parallel loop' after parsing
11134   /// of the associated statement.
11135   StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
11136       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11137       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11138   /// Called on well-formed '\#pragma omp cancellation point'.
11139   StmtResult
11140   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
11141                                         SourceLocation EndLoc,
11142                                         OpenMPDirectiveKind CancelRegion);
11143   /// Called on well-formed '\#pragma omp cancel'.
11144   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
11145                                         SourceLocation StartLoc,
11146                                         SourceLocation EndLoc,
11147                                         OpenMPDirectiveKind CancelRegion);
11148   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
11149   /// associated statement.
11150   StmtResult
11151   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11152                                SourceLocation StartLoc, SourceLocation EndLoc,
11153                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
11154   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
11155   /// the associated statement.
11156   StmtResult ActOnOpenMPTaskLoopSimdDirective(
11157       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11158       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11159   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
11160   /// associated statement.
11161   StmtResult ActOnOpenMPMasterTaskLoopDirective(
11162       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11163       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11164   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
11165   /// the associated statement.
11166   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
11167       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11168       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11169   /// Called on well-formed '\#pragma omp parallel master taskloop' after
11170   /// parsing of the associated statement.
11171   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
11172       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11173       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11174   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
11175   /// parsing of the associated statement.
11176   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11177       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11178       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11179   /// Called on well-formed '\#pragma omp masked taskloop' after parsing of the
11180   /// associated statement.
11181   StmtResult ActOnOpenMPMaskedTaskLoopDirective(
11182       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11183       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11184   /// Called on well-formed '\#pragma omp masked taskloop simd' after parsing of
11185   /// the associated statement.
11186   StmtResult ActOnOpenMPMaskedTaskLoopSimdDirective(
11187       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11188       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11189   /// Called on well-formed '\#pragma omp parallel masked taskloop' after
11190   /// parsing of the associated statement.
11191   StmtResult ActOnOpenMPParallelMaskedTaskLoopDirective(
11192       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11193       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11194   /// Called on well-formed '\#pragma omp parallel masked taskloop simd' after
11195   /// parsing of the associated statement.
11196   StmtResult ActOnOpenMPParallelMaskedTaskLoopSimdDirective(
11197       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11198       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11199   /// Called on well-formed '\#pragma omp distribute' after parsing
11200   /// of the associated statement.
11201   StmtResult
11202   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11203                                  SourceLocation StartLoc, SourceLocation EndLoc,
11204                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
11205   /// Called on well-formed '\#pragma omp target update'.
11206   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11207                                               SourceLocation StartLoc,
11208                                               SourceLocation EndLoc,
11209                                               Stmt *AStmt);
11210   /// Called on well-formed '\#pragma omp distribute parallel for' after
11211   /// parsing of the associated statement.
11212   StmtResult ActOnOpenMPDistributeParallelForDirective(
11213       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11214       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11215   /// Called on well-formed '\#pragma omp distribute parallel for simd'
11216   /// after parsing of the associated statement.
11217   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
11218       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11219       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11220   /// Called on well-formed '\#pragma omp distribute simd' after
11221   /// parsing of the associated statement.
11222   StmtResult ActOnOpenMPDistributeSimdDirective(
11223       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11224       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11225   /// Called on well-formed '\#pragma omp target parallel for simd' after
11226   /// parsing of the associated statement.
11227   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
11228       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11229       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11230   /// Called on well-formed '\#pragma omp target simd' after parsing of
11231   /// the associated statement.
11232   StmtResult
11233   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11234                                  SourceLocation StartLoc, SourceLocation EndLoc,
11235                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
11236   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
11237   /// the associated statement.
11238   StmtResult ActOnOpenMPTeamsDistributeDirective(
11239       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11240       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11241   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
11242   /// of the associated statement.
11243   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
11244       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11245       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11246   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
11247   /// after parsing of the associated statement.
11248   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11249       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11250       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11251   /// Called on well-formed '\#pragma omp teams distribute parallel for'
11252   /// after parsing of the associated statement.
11253   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
11254       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11255       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11256   /// Called on well-formed '\#pragma omp target teams' after parsing of the
11257   /// associated statement.
11258   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11259                                              Stmt *AStmt,
11260                                              SourceLocation StartLoc,
11261                                              SourceLocation EndLoc);
11262   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
11263   /// of the associated statement.
11264   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
11265       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11266       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11267   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
11268   /// after parsing of the associated statement.
11269   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11270       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11271       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11272   /// Called on well-formed '\#pragma omp target teams distribute parallel for
11273   /// simd' after parsing of the associated statement.
11274   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11275       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11276       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11277   /// Called on well-formed '\#pragma omp target teams distribute simd' after
11278   /// parsing of the associated statement.
11279   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
11280       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11281       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11282   /// Called on well-formed '\#pragma omp interop'.
11283   StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
11284                                          SourceLocation StartLoc,
11285                                          SourceLocation EndLoc);
11286   /// Called on well-formed '\#pragma omp dispatch' after parsing of the
11287   // /associated statement.
11288   StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
11289                                           Stmt *AStmt, SourceLocation StartLoc,
11290                                           SourceLocation EndLoc);
11291   /// Called on well-formed '\#pragma omp masked' after parsing of the
11292   // /associated statement.
11293   StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
11294                                         Stmt *AStmt, SourceLocation StartLoc,
11295                                         SourceLocation EndLoc);
11296 
11297   /// Called on well-formed '\#pragma omp loop' after parsing of the
11298   /// associated statement.
11299   StmtResult ActOnOpenMPGenericLoopDirective(
11300       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11301       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11302 
11303   /// Checks correctness of linear modifiers.
11304   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11305                                  SourceLocation LinLoc);
11306   /// Checks that the specified declaration matches requirements for the linear
11307   /// decls.
11308   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11309                              OpenMPLinearClauseKind LinKind, QualType Type,
11310                              bool IsDeclareSimd = false);
11311 
11312   /// Called on well-formed '\#pragma omp declare simd' after parsing of
11313   /// the associated method/function.
11314   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
11315       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
11316       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
11317       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
11318       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
11319 
11320   /// Checks '\#pragma omp declare variant' variant function and original
11321   /// functions after parsing of the associated method/function.
11322   /// \param DG Function declaration to which declare variant directive is
11323   /// applied to.
11324   /// \param VariantRef Expression that references the variant function, which
11325   /// must be used instead of the original one, specified in \p DG.
11326   /// \param TI The trait info object representing the match clause.
11327   /// \param NumAppendArgs The number of omp_interop_t arguments to account for
11328   /// in checking.
11329   /// \returns None, if the function/variant function are not compatible with
11330   /// the pragma, pair of original function/variant ref expression otherwise.
11331   Optional<std::pair<FunctionDecl *, Expr *>>
11332   checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
11333                                     OMPTraitInfo &TI, unsigned NumAppendArgs,
11334                                     SourceRange SR);
11335 
11336   /// Called on well-formed '\#pragma omp declare variant' after parsing of
11337   /// the associated method/function.
11338   /// \param FD Function declaration to which declare variant directive is
11339   /// applied to.
11340   /// \param VariantRef Expression that references the variant function, which
11341   /// must be used instead of the original one, specified in \p DG.
11342   /// \param TI The context traits associated with the function variant.
11343   /// \param AdjustArgsNothing The list of 'nothing' arguments.
11344   /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments.
11345   /// \param AppendArgs The list of 'append_args' arguments.
11346   /// \param AdjustArgsLoc The Location of an 'adjust_args' clause.
11347   /// \param AppendArgsLoc The Location of an 'append_args' clause.
11348   /// \param SR The SourceRange of the 'declare variant' directive.
11349   void ActOnOpenMPDeclareVariantDirective(
11350       FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
11351       ArrayRef<Expr *> AdjustArgsNothing,
11352       ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
11353       ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
11354       SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
11355       SourceRange SR);
11356 
11357   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
11358                                          Expr *Expr,
11359                                          SourceLocation StartLoc,
11360                                          SourceLocation LParenLoc,
11361                                          SourceLocation EndLoc);
11362   /// Called on well-formed 'allocator' clause.
11363   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
11364                                         SourceLocation StartLoc,
11365                                         SourceLocation LParenLoc,
11366                                         SourceLocation EndLoc);
11367   /// Called on well-formed 'if' clause.
11368   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11369                                  Expr *Condition, SourceLocation StartLoc,
11370                                  SourceLocation LParenLoc,
11371                                  SourceLocation NameModifierLoc,
11372                                  SourceLocation ColonLoc,
11373                                  SourceLocation EndLoc);
11374   /// Called on well-formed 'final' clause.
11375   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11376                                     SourceLocation LParenLoc,
11377                                     SourceLocation EndLoc);
11378   /// Called on well-formed 'num_threads' clause.
11379   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11380                                          SourceLocation StartLoc,
11381                                          SourceLocation LParenLoc,
11382                                          SourceLocation EndLoc);
11383   /// Called on well-formed 'align' clause.
11384   OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc,
11385                                     SourceLocation LParenLoc,
11386                                     SourceLocation EndLoc);
11387   /// Called on well-formed 'safelen' clause.
11388   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11389                                       SourceLocation StartLoc,
11390                                       SourceLocation LParenLoc,
11391                                       SourceLocation EndLoc);
11392   /// Called on well-formed 'simdlen' clause.
11393   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11394                                       SourceLocation LParenLoc,
11395                                       SourceLocation EndLoc);
11396   /// Called on well-form 'sizes' clause.
11397   OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11398                                     SourceLocation StartLoc,
11399                                     SourceLocation LParenLoc,
11400                                     SourceLocation EndLoc);
11401   /// Called on well-form 'full' clauses.
11402   OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11403                                    SourceLocation EndLoc);
11404   /// Called on well-form 'partial' clauses.
11405   OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11406                                       SourceLocation LParenLoc,
11407                                       SourceLocation EndLoc);
11408   /// Called on well-formed 'collapse' clause.
11409   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11410                                        SourceLocation StartLoc,
11411                                        SourceLocation LParenLoc,
11412                                        SourceLocation EndLoc);
11413   /// Called on well-formed 'ordered' clause.
11414   OMPClause *
11415   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11416                            SourceLocation LParenLoc = SourceLocation(),
11417                            Expr *NumForLoops = nullptr);
11418   /// Called on well-formed 'grainsize' clause.
11419   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
11420                                         SourceLocation LParenLoc,
11421                                         SourceLocation EndLoc);
11422   /// Called on well-formed 'num_tasks' clause.
11423   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
11424                                        SourceLocation LParenLoc,
11425                                        SourceLocation EndLoc);
11426   /// Called on well-formed 'hint' clause.
11427   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11428                                    SourceLocation LParenLoc,
11429                                    SourceLocation EndLoc);
11430   /// Called on well-formed 'detach' clause.
11431   OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11432                                      SourceLocation LParenLoc,
11433                                      SourceLocation EndLoc);
11434 
11435   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11436                                      unsigned Argument,
11437                                      SourceLocation ArgumentLoc,
11438                                      SourceLocation StartLoc,
11439                                      SourceLocation LParenLoc,
11440                                      SourceLocation EndLoc);
11441   /// Called on well-formed 'when' clause.
11442   OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11443                                    SourceLocation LParenLoc,
11444                                    SourceLocation EndLoc);
11445   /// Called on well-formed 'default' clause.
11446   OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11447                                       SourceLocation KindLoc,
11448                                       SourceLocation StartLoc,
11449                                       SourceLocation LParenLoc,
11450                                       SourceLocation EndLoc);
11451   /// Called on well-formed 'proc_bind' clause.
11452   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11453                                        SourceLocation KindLoc,
11454                                        SourceLocation StartLoc,
11455                                        SourceLocation LParenLoc,
11456                                        SourceLocation EndLoc);
11457   /// Called on well-formed 'order' clause.
11458   OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
11459                                     SourceLocation KindLoc,
11460                                     SourceLocation StartLoc,
11461                                     SourceLocation LParenLoc,
11462                                     SourceLocation EndLoc);
11463   /// Called on well-formed 'update' clause.
11464   OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11465                                      SourceLocation KindLoc,
11466                                      SourceLocation StartLoc,
11467                                      SourceLocation LParenLoc,
11468                                      SourceLocation EndLoc);
11469 
11470   OMPClause *ActOnOpenMPSingleExprWithArgClause(
11471       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11472       SourceLocation StartLoc, SourceLocation LParenLoc,
11473       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11474       SourceLocation EndLoc);
11475   /// Called on well-formed 'schedule' clause.
11476   OMPClause *ActOnOpenMPScheduleClause(
11477       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11478       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11479       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11480       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11481 
11482   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11483                                SourceLocation EndLoc);
11484   /// Called on well-formed 'nowait' clause.
11485   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11486                                      SourceLocation EndLoc);
11487   /// Called on well-formed 'untied' clause.
11488   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11489                                      SourceLocation EndLoc);
11490   /// Called on well-formed 'mergeable' clause.
11491   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11492                                         SourceLocation EndLoc);
11493   /// Called on well-formed 'read' clause.
11494   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11495                                    SourceLocation EndLoc);
11496   /// Called on well-formed 'write' clause.
11497   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11498                                     SourceLocation EndLoc);
11499   /// Called on well-formed 'update' clause.
11500   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11501                                      SourceLocation EndLoc);
11502   /// Called on well-formed 'capture' clause.
11503   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11504                                       SourceLocation EndLoc);
11505   /// Called on well-formed 'compare' clause.
11506   OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc,
11507                                       SourceLocation EndLoc);
11508   /// Called on well-formed 'seq_cst' clause.
11509   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11510                                      SourceLocation EndLoc);
11511   /// Called on well-formed 'acq_rel' clause.
11512   OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
11513                                      SourceLocation EndLoc);
11514   /// Called on well-formed 'acquire' clause.
11515   OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
11516                                       SourceLocation EndLoc);
11517   /// Called on well-formed 'release' clause.
11518   OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
11519                                       SourceLocation EndLoc);
11520   /// Called on well-formed 'relaxed' clause.
11521   OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
11522                                       SourceLocation EndLoc);
11523 
11524   /// Called on well-formed 'init' clause.
11525   OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
11526                                    bool IsTarget, bool IsTargetSync,
11527                                    SourceLocation StartLoc,
11528                                    SourceLocation LParenLoc,
11529                                    SourceLocation VarLoc,
11530                                    SourceLocation EndLoc);
11531 
11532   /// Called on well-formed 'use' clause.
11533   OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
11534                                   SourceLocation LParenLoc,
11535                                   SourceLocation VarLoc, SourceLocation EndLoc);
11536 
11537   /// Called on well-formed 'destroy' clause.
11538   OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
11539                                       SourceLocation LParenLoc,
11540                                       SourceLocation VarLoc,
11541                                       SourceLocation EndLoc);
11542   /// Called on well-formed 'novariants' clause.
11543   OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
11544                                          SourceLocation StartLoc,
11545                                          SourceLocation LParenLoc,
11546                                          SourceLocation EndLoc);
11547   /// Called on well-formed 'nocontext' clause.
11548   OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
11549                                         SourceLocation StartLoc,
11550                                         SourceLocation LParenLoc,
11551                                         SourceLocation EndLoc);
11552   /// Called on well-formed 'filter' clause.
11553   OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
11554                                      SourceLocation LParenLoc,
11555                                      SourceLocation EndLoc);
11556   /// Called on well-formed 'threads' clause.
11557   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11558                                       SourceLocation EndLoc);
11559   /// Called on well-formed 'simd' clause.
11560   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11561                                    SourceLocation EndLoc);
11562   /// Called on well-formed 'nogroup' clause.
11563   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11564                                       SourceLocation EndLoc);
11565   /// Called on well-formed 'unified_address' clause.
11566   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11567                                              SourceLocation EndLoc);
11568 
11569   /// Called on well-formed 'unified_address' clause.
11570   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11571                                                   SourceLocation EndLoc);
11572 
11573   /// Called on well-formed 'reverse_offload' clause.
11574   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11575                                              SourceLocation EndLoc);
11576 
11577   /// Called on well-formed 'dynamic_allocators' clause.
11578   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11579                                                 SourceLocation EndLoc);
11580 
11581   /// Called on well-formed 'atomic_default_mem_order' clause.
11582   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
11583       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
11584       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11585 
11586   /// Data used for processing a list of variables in OpenMP clauses.
11587   struct OpenMPVarListDataTy final {
11588     Expr *DepModOrTailExpr = nullptr;
11589     SourceLocation ColonLoc;
11590     SourceLocation RLoc;
11591     CXXScopeSpec ReductionOrMapperIdScopeSpec;
11592     DeclarationNameInfo ReductionOrMapperId;
11593     int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
11594                             ///< lastprivate clause.
11595     SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
11596         MapTypeModifiers;
11597     SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
11598         MapTypeModifiersLoc;
11599     SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
11600         MotionModifiers;
11601     SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
11602     bool IsMapTypeImplicit = false;
11603     SourceLocation ExtraModifierLoc;
11604     SourceLocation OmpAllMemoryLoc;
11605   };
11606 
11607   OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
11608                                       ArrayRef<Expr *> Vars,
11609                                       const OMPVarListLocTy &Locs,
11610                                       OpenMPVarListDataTy &Data);
11611   /// Called on well-formed 'inclusive' clause.
11612   OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
11613                                         SourceLocation StartLoc,
11614                                         SourceLocation LParenLoc,
11615                                         SourceLocation EndLoc);
11616   /// Called on well-formed 'exclusive' clause.
11617   OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
11618                                         SourceLocation StartLoc,
11619                                         SourceLocation LParenLoc,
11620                                         SourceLocation EndLoc);
11621   /// Called on well-formed 'allocate' clause.
11622   OMPClause *
11623   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
11624                             SourceLocation StartLoc, SourceLocation ColonLoc,
11625                             SourceLocation LParenLoc, SourceLocation EndLoc);
11626   /// Called on well-formed 'private' clause.
11627   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11628                                       SourceLocation StartLoc,
11629                                       SourceLocation LParenLoc,
11630                                       SourceLocation EndLoc);
11631   /// Called on well-formed 'firstprivate' clause.
11632   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11633                                            SourceLocation StartLoc,
11634                                            SourceLocation LParenLoc,
11635                                            SourceLocation EndLoc);
11636   /// Called on well-formed 'lastprivate' clause.
11637   OMPClause *ActOnOpenMPLastprivateClause(
11638       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
11639       SourceLocation LPKindLoc, SourceLocation ColonLoc,
11640       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11641   /// Called on well-formed 'shared' clause.
11642   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11643                                      SourceLocation StartLoc,
11644                                      SourceLocation LParenLoc,
11645                                      SourceLocation EndLoc);
11646   /// Called on well-formed 'reduction' clause.
11647   OMPClause *ActOnOpenMPReductionClause(
11648       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
11649       SourceLocation StartLoc, SourceLocation LParenLoc,
11650       SourceLocation ModifierLoc, SourceLocation ColonLoc,
11651       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
11652       const DeclarationNameInfo &ReductionId,
11653       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11654   /// Called on well-formed 'task_reduction' clause.
11655   OMPClause *ActOnOpenMPTaskReductionClause(
11656       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11657       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11658       CXXScopeSpec &ReductionIdScopeSpec,
11659       const DeclarationNameInfo &ReductionId,
11660       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11661   /// Called on well-formed 'in_reduction' clause.
11662   OMPClause *ActOnOpenMPInReductionClause(
11663       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11664       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11665       CXXScopeSpec &ReductionIdScopeSpec,
11666       const DeclarationNameInfo &ReductionId,
11667       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11668   /// Called on well-formed 'linear' clause.
11669   OMPClause *
11670   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
11671                           SourceLocation StartLoc, SourceLocation LParenLoc,
11672                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
11673                           SourceLocation ColonLoc, SourceLocation EndLoc);
11674   /// Called on well-formed 'aligned' clause.
11675   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
11676                                       Expr *Alignment,
11677                                       SourceLocation StartLoc,
11678                                       SourceLocation LParenLoc,
11679                                       SourceLocation ColonLoc,
11680                                       SourceLocation EndLoc);
11681   /// Called on well-formed 'copyin' clause.
11682   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11683                                      SourceLocation StartLoc,
11684                                      SourceLocation LParenLoc,
11685                                      SourceLocation EndLoc);
11686   /// Called on well-formed 'copyprivate' clause.
11687   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11688                                           SourceLocation StartLoc,
11689                                           SourceLocation LParenLoc,
11690                                           SourceLocation EndLoc);
11691   /// Called on well-formed 'flush' pseudo clause.
11692   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11693                                     SourceLocation StartLoc,
11694                                     SourceLocation LParenLoc,
11695                                     SourceLocation EndLoc);
11696   /// Called on well-formed 'depobj' pseudo clause.
11697   OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11698                                      SourceLocation LParenLoc,
11699                                      SourceLocation EndLoc);
11700   /// Called on well-formed 'depend' clause.
11701   OMPClause *ActOnOpenMPDependClause(const OMPDependClause::DependDataTy &Data,
11702                                      Expr *DepModifier,
11703                                      ArrayRef<Expr *> VarList,
11704                                      SourceLocation StartLoc,
11705                                      SourceLocation LParenLoc,
11706                                      SourceLocation EndLoc);
11707   /// Called on well-formed 'device' clause.
11708   OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11709                                      Expr *Device, SourceLocation StartLoc,
11710                                      SourceLocation LParenLoc,
11711                                      SourceLocation ModifierLoc,
11712                                      SourceLocation EndLoc);
11713   /// Called on well-formed 'map' clause.
11714   OMPClause *ActOnOpenMPMapClause(
11715       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11716       ArrayRef<SourceLocation> MapTypeModifiersLoc,
11717       CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
11718       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11719       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
11720       const OMPVarListLocTy &Locs, bool NoDiagnose = false,
11721       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11722   /// Called on well-formed 'num_teams' clause.
11723   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11724                                        SourceLocation LParenLoc,
11725                                        SourceLocation EndLoc);
11726   /// Called on well-formed 'thread_limit' clause.
11727   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11728                                           SourceLocation StartLoc,
11729                                           SourceLocation LParenLoc,
11730                                           SourceLocation EndLoc);
11731   /// Called on well-formed 'priority' clause.
11732   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11733                                        SourceLocation LParenLoc,
11734                                        SourceLocation EndLoc);
11735   /// Called on well-formed 'dist_schedule' clause.
11736   OMPClause *ActOnOpenMPDistScheduleClause(
11737       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11738       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11739       SourceLocation CommaLoc, SourceLocation EndLoc);
11740   /// Called on well-formed 'defaultmap' clause.
11741   OMPClause *ActOnOpenMPDefaultmapClause(
11742       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11743       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11744       SourceLocation KindLoc, SourceLocation EndLoc);
11745   /// Called on well-formed 'to' clause.
11746   OMPClause *
11747   ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11748                       ArrayRef<SourceLocation> MotionModifiersLoc,
11749                       CXXScopeSpec &MapperIdScopeSpec,
11750                       DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11751                       ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11752                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11753   /// Called on well-formed 'from' clause.
11754   OMPClause *
11755   ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11756                         ArrayRef<SourceLocation> MotionModifiersLoc,
11757                         CXXScopeSpec &MapperIdScopeSpec,
11758                         DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11759                         ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11760                         ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11761   /// Called on well-formed 'use_device_ptr' clause.
11762   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11763                                            const OMPVarListLocTy &Locs);
11764   /// Called on well-formed 'use_device_addr' clause.
11765   OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11766                                             const OMPVarListLocTy &Locs);
11767   /// Called on well-formed 'is_device_ptr' clause.
11768   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11769                                           const OMPVarListLocTy &Locs);
11770   /// Called on well-formed 'has_device_addr' clause.
11771   OMPClause *ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
11772                                             const OMPVarListLocTy &Locs);
11773   /// Called on well-formed 'nontemporal' clause.
11774   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11775                                           SourceLocation StartLoc,
11776                                           SourceLocation LParenLoc,
11777                                           SourceLocation EndLoc);
11778 
11779   /// Data for list of allocators.
11780   struct UsesAllocatorsData {
11781     /// Allocator.
11782     Expr *Allocator = nullptr;
11783     /// Allocator traits.
11784     Expr *AllocatorTraits = nullptr;
11785     /// Locations of '(' and ')' symbols.
11786     SourceLocation LParenLoc, RParenLoc;
11787   };
11788   /// Called on well-formed 'uses_allocators' clause.
11789   OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11790                                             SourceLocation LParenLoc,
11791                                             SourceLocation EndLoc,
11792                                             ArrayRef<UsesAllocatorsData> Data);
11793   /// Called on well-formed 'affinity' clause.
11794   OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11795                                        SourceLocation LParenLoc,
11796                                        SourceLocation ColonLoc,
11797                                        SourceLocation EndLoc, Expr *Modifier,
11798                                        ArrayRef<Expr *> Locators);
11799   /// Called on a well-formed 'bind' clause.
11800   OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
11801                                    SourceLocation KindLoc,
11802                                    SourceLocation StartLoc,
11803                                    SourceLocation LParenLoc,
11804                                    SourceLocation EndLoc);
11805 
11806   /// The kind of conversion being performed.
11807   enum CheckedConversionKind {
11808     /// An implicit conversion.
11809     CCK_ImplicitConversion,
11810     /// A C-style cast.
11811     CCK_CStyleCast,
11812     /// A functional-style cast.
11813     CCK_FunctionalCast,
11814     /// A cast other than a C-style cast.
11815     CCK_OtherCast,
11816     /// A conversion for an operand of a builtin overloaded operator.
11817     CCK_ForBuiltinOverloadedOp
11818   };
11819 
11820   static bool isCast(CheckedConversionKind CCK) {
11821     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11822            CCK == CCK_OtherCast;
11823   }
11824 
11825   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11826   /// cast.  If there is already an implicit cast, merge into the existing one.
11827   /// If isLvalue, the result of the cast is an lvalue.
11828   ExprResult
11829   ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11830                     ExprValueKind VK = VK_PRValue,
11831                     const CXXCastPath *BasePath = nullptr,
11832                     CheckedConversionKind CCK = CCK_ImplicitConversion);
11833 
11834   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11835   /// to the conversion from scalar type ScalarTy to the Boolean type.
11836   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11837 
11838   /// IgnoredValueConversions - Given that an expression's result is
11839   /// syntactically ignored, perform any conversions that are
11840   /// required.
11841   ExprResult IgnoredValueConversions(Expr *E);
11842 
11843   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11844   // functions and arrays to their respective pointers (C99 6.3.2.1).
11845   ExprResult UsualUnaryConversions(Expr *E);
11846 
11847   /// CallExprUnaryConversions - a special case of an unary conversion
11848   /// performed on a function designator of a call expression.
11849   ExprResult CallExprUnaryConversions(Expr *E);
11850 
11851   // DefaultFunctionArrayConversion - converts functions and arrays
11852   // to their respective pointers (C99 6.3.2.1).
11853   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11854 
11855   // DefaultFunctionArrayLvalueConversion - converts functions and
11856   // arrays to their respective pointers and performs the
11857   // lvalue-to-rvalue conversion.
11858   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11859                                                   bool Diagnose = true);
11860 
11861   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11862   // the operand. This function is a no-op if the operand has a function type
11863   // or an array type.
11864   ExprResult DefaultLvalueConversion(Expr *E);
11865 
11866   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11867   // do not have a prototype. Integer promotions are performed on each
11868   // argument, and arguments that have type float are promoted to double.
11869   ExprResult DefaultArgumentPromotion(Expr *E);
11870 
11871   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11872   /// it as an xvalue. In C++98, the result will still be a prvalue, because
11873   /// we don't have xvalues there.
11874   ExprResult TemporaryMaterializationConversion(Expr *E);
11875 
11876   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11877   enum VariadicCallType {
11878     VariadicFunction,
11879     VariadicBlock,
11880     VariadicMethod,
11881     VariadicConstructor,
11882     VariadicDoesNotApply
11883   };
11884 
11885   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11886                                        const FunctionProtoType *Proto,
11887                                        Expr *Fn);
11888 
11889   // Used for determining in which context a type is allowed to be passed to a
11890   // vararg function.
11891   enum VarArgKind {
11892     VAK_Valid,
11893     VAK_ValidInCXX11,
11894     VAK_Undefined,
11895     VAK_MSVCUndefined,
11896     VAK_Invalid
11897   };
11898 
11899   // Determines which VarArgKind fits an expression.
11900   VarArgKind isValidVarArgType(const QualType &Ty);
11901 
11902   /// Check to see if the given expression is a valid argument to a variadic
11903   /// function, issuing a diagnostic if not.
11904   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11905 
11906   /// Check whether the given statement can have musttail applied to it,
11907   /// issuing a diagnostic and returning false if not. In the success case,
11908   /// the statement is rewritten to remove implicit nodes from the return
11909   /// value.
11910   bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11911 
11912 private:
11913   /// Check whether the given statement can have musttail applied to it,
11914   /// issuing a diagnostic and returning false if not.
11915   bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11916 
11917 public:
11918   /// Check to see if a given expression could have '.c_str()' called on it.
11919   bool hasCStrMethod(const Expr *E);
11920 
11921   /// GatherArgumentsForCall - Collector argument expressions for various
11922   /// form of call prototypes.
11923   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11924                               const FunctionProtoType *Proto,
11925                               unsigned FirstParam, ArrayRef<Expr *> Args,
11926                               SmallVectorImpl<Expr *> &AllArgs,
11927                               VariadicCallType CallType = VariadicDoesNotApply,
11928                               bool AllowExplicit = false,
11929                               bool IsListInitialization = false);
11930 
11931   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11932   // will create a runtime trap if the resulting type is not a POD type.
11933   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11934                                               FunctionDecl *FDecl);
11935 
11936   /// Context in which we're performing a usual arithmetic conversion.
11937   enum ArithConvKind {
11938     /// An arithmetic operation.
11939     ACK_Arithmetic,
11940     /// A bitwise operation.
11941     ACK_BitwiseOp,
11942     /// A comparison.
11943     ACK_Comparison,
11944     /// A conditional (?:) operator.
11945     ACK_Conditional,
11946     /// A compound assignment expression.
11947     ACK_CompAssign,
11948   };
11949 
11950   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11951   // operands and then handles various conversions that are common to binary
11952   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11953   // routine returns the first non-arithmetic type found. The client is
11954   // responsible for emitting appropriate error diagnostics.
11955   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11956                                       SourceLocation Loc, ArithConvKind ACK);
11957 
11958   /// AssignConvertType - All of the 'assignment' semantic checks return this
11959   /// enum to indicate whether the assignment was allowed.  These checks are
11960   /// done for simple assignments, as well as initialization, return from
11961   /// function, argument passing, etc.  The query is phrased in terms of a
11962   /// source and destination type.
11963   enum AssignConvertType {
11964     /// Compatible - the types are compatible according to the standard.
11965     Compatible,
11966 
11967     /// PointerToInt - The assignment converts a pointer to an int, which we
11968     /// accept as an extension.
11969     PointerToInt,
11970 
11971     /// IntToPointer - The assignment converts an int to a pointer, which we
11972     /// accept as an extension.
11973     IntToPointer,
11974 
11975     /// FunctionVoidPointer - The assignment is between a function pointer and
11976     /// void*, which the standard doesn't allow, but we accept as an extension.
11977     FunctionVoidPointer,
11978 
11979     /// IncompatiblePointer - The assignment is between two pointers types that
11980     /// are not compatible, but we accept them as an extension.
11981     IncompatiblePointer,
11982 
11983     /// IncompatibleFunctionPointer - The assignment is between two function
11984     /// pointers types that are not compatible, but we accept them as an
11985     /// extension.
11986     IncompatibleFunctionPointer,
11987 
11988     /// IncompatiblePointerSign - The assignment is between two pointers types
11989     /// which point to integers which have a different sign, but are otherwise
11990     /// identical. This is a subset of the above, but broken out because it's by
11991     /// far the most common case of incompatible pointers.
11992     IncompatiblePointerSign,
11993 
11994     /// CompatiblePointerDiscardsQualifiers - The assignment discards
11995     /// c/v/r qualifiers, which we accept as an extension.
11996     CompatiblePointerDiscardsQualifiers,
11997 
11998     /// IncompatiblePointerDiscardsQualifiers - The assignment
11999     /// discards qualifiers that we don't permit to be discarded,
12000     /// like address spaces.
12001     IncompatiblePointerDiscardsQualifiers,
12002 
12003     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
12004     /// changes address spaces in nested pointer types which is not allowed.
12005     /// For instance, converting __private int ** to __generic int ** is
12006     /// illegal even though __private could be converted to __generic.
12007     IncompatibleNestedPointerAddressSpaceMismatch,
12008 
12009     /// IncompatibleNestedPointerQualifiers - The assignment is between two
12010     /// nested pointer types, and the qualifiers other than the first two
12011     /// levels differ e.g. char ** -> const char **, but we accept them as an
12012     /// extension.
12013     IncompatibleNestedPointerQualifiers,
12014 
12015     /// IncompatibleVectors - The assignment is between two vector types that
12016     /// have the same size, which we accept as an extension.
12017     IncompatibleVectors,
12018 
12019     /// IntToBlockPointer - The assignment converts an int to a block
12020     /// pointer. We disallow this.
12021     IntToBlockPointer,
12022 
12023     /// IncompatibleBlockPointer - The assignment is between two block
12024     /// pointers types that are not compatible.
12025     IncompatibleBlockPointer,
12026 
12027     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
12028     /// id type and something else (that is incompatible with it). For example,
12029     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
12030     IncompatibleObjCQualifiedId,
12031 
12032     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
12033     /// object with __weak qualifier.
12034     IncompatibleObjCWeakRef,
12035 
12036     /// Incompatible - We reject this conversion outright, it is invalid to
12037     /// represent it in the AST.
12038     Incompatible
12039   };
12040 
12041   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
12042   /// assignment conversion type specified by ConvTy.  This returns true if the
12043   /// conversion was invalid or false if the conversion was accepted.
12044   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
12045                                 SourceLocation Loc,
12046                                 QualType DstType, QualType SrcType,
12047                                 Expr *SrcExpr, AssignmentAction Action,
12048                                 bool *Complained = nullptr);
12049 
12050   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
12051   /// enum. If AllowMask is true, then we also allow the complement of a valid
12052   /// value, to be used as a mask.
12053   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
12054                          bool AllowMask) const;
12055 
12056   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
12057   /// integer not in the range of enum values.
12058   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
12059                               Expr *SrcExpr);
12060 
12061   /// CheckAssignmentConstraints - Perform type checking for assignment,
12062   /// argument passing, variable initialization, and function return values.
12063   /// C99 6.5.16.
12064   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
12065                                                QualType LHSType,
12066                                                QualType RHSType);
12067 
12068   /// Check assignment constraints and optionally prepare for a conversion of
12069   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
12070   /// is true.
12071   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
12072                                                ExprResult &RHS,
12073                                                CastKind &Kind,
12074                                                bool ConvertRHS = true);
12075 
12076   /// Check assignment constraints for an assignment of RHS to LHSType.
12077   ///
12078   /// \param LHSType The destination type for the assignment.
12079   /// \param RHS The source expression for the assignment.
12080   /// \param Diagnose If \c true, diagnostics may be produced when checking
12081   ///        for assignability. If a diagnostic is produced, \p RHS will be
12082   ///        set to ExprError(). Note that this function may still return
12083   ///        without producing a diagnostic, even for an invalid assignment.
12084   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
12085   ///        in an audited Core Foundation API and does not need to be checked
12086   ///        for ARC retain issues.
12087   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
12088   ///        conversions necessary to perform the assignment. If \c false,
12089   ///        \p Diagnose must also be \c false.
12090   AssignConvertType CheckSingleAssignmentConstraints(
12091       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
12092       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
12093 
12094   // If the lhs type is a transparent union, check whether we
12095   // can initialize the transparent union with the given expression.
12096   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
12097                                                              ExprResult &RHS);
12098 
12099   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
12100 
12101   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
12102 
12103   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12104                                        AssignmentAction Action,
12105                                        bool AllowExplicit = false);
12106   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12107                                        const ImplicitConversionSequence& ICS,
12108                                        AssignmentAction Action,
12109                                        CheckedConversionKind CCK
12110                                           = CCK_ImplicitConversion);
12111   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
12112                                        const StandardConversionSequence& SCS,
12113                                        AssignmentAction Action,
12114                                        CheckedConversionKind CCK);
12115 
12116   ExprResult PerformQualificationConversion(
12117       Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
12118       CheckedConversionKind CCK = CCK_ImplicitConversion);
12119 
12120   /// the following "Check" methods will return a valid/converted QualType
12121   /// or a null QualType (indicating an error diagnostic was issued).
12122 
12123   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
12124   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
12125                            ExprResult &RHS);
12126   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
12127                                  ExprResult &RHS);
12128   QualType CheckPointerToMemberOperands( // C++ 5.5
12129     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
12130     SourceLocation OpLoc, bool isIndirect);
12131   QualType CheckMultiplyDivideOperands( // C99 6.5.5
12132     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
12133     bool IsDivide);
12134   QualType CheckRemainderOperands( // C99 6.5.5
12135     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12136     bool IsCompAssign = false);
12137   QualType CheckAdditionOperands( // C99 6.5.6
12138     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12139     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
12140   QualType CheckSubtractionOperands( // C99 6.5.6
12141     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12142     QualType* CompLHSTy = nullptr);
12143   QualType CheckShiftOperands( // C99 6.5.7
12144     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12145     BinaryOperatorKind Opc, bool IsCompAssign = false);
12146   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
12147   QualType CheckCompareOperands( // C99 6.5.8/9
12148       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12149       BinaryOperatorKind Opc);
12150   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
12151       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12152       BinaryOperatorKind Opc);
12153   QualType CheckLogicalOperands( // C99 6.5.[13,14]
12154     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
12155     BinaryOperatorKind Opc);
12156   // CheckAssignmentOperands is used for both simple and compound assignment.
12157   // For simple assignment, pass both expressions and a null converted type.
12158   // For compound assignment, pass both expressions and the converted type.
12159   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
12160     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
12161 
12162   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
12163                                      UnaryOperatorKind Opcode, Expr *Op);
12164   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
12165                                          BinaryOperatorKind Opcode,
12166                                          Expr *LHS, Expr *RHS);
12167   ExprResult checkPseudoObjectRValue(Expr *E);
12168   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
12169 
12170   QualType CheckConditionalOperands( // C99 6.5.15
12171     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
12172     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
12173   QualType CXXCheckConditionalOperands( // C++ 5.16
12174     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
12175     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
12176   QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
12177                                        ExprResult &RHS,
12178                                        SourceLocation QuestionLoc);
12179 
12180   QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond,
12181                                                ExprResult &LHS, ExprResult &RHS,
12182                                                SourceLocation QuestionLoc);
12183   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
12184                                     bool ConvertArgs = true);
12185   QualType FindCompositePointerType(SourceLocation Loc,
12186                                     ExprResult &E1, ExprResult &E2,
12187                                     bool ConvertArgs = true) {
12188     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
12189     QualType Composite =
12190         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
12191     E1 = E1Tmp;
12192     E2 = E2Tmp;
12193     return Composite;
12194   }
12195 
12196   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
12197                                         SourceLocation QuestionLoc);
12198 
12199   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
12200                                   SourceLocation QuestionLoc);
12201 
12202   void DiagnoseAlwaysNonNullPointer(Expr *E,
12203                                     Expr::NullPointerConstantKind NullType,
12204                                     bool IsEqual, SourceRange Range);
12205 
12206   /// type checking for vector binary operators.
12207   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
12208                                SourceLocation Loc, bool IsCompAssign,
12209                                bool AllowBothBool, bool AllowBoolConversion,
12210                                bool AllowBoolOperation, bool ReportInvalid);
12211   QualType GetSignedVectorType(QualType V);
12212   QualType GetSignedSizelessVectorType(QualType V);
12213   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12214                                       SourceLocation Loc,
12215                                       BinaryOperatorKind Opc);
12216   QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12217                                               SourceLocation Loc,
12218                                               BinaryOperatorKind Opc);
12219   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12220                                       SourceLocation Loc);
12221 
12222   // type checking for sizeless vector binary operators.
12223   QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
12224                                        SourceLocation Loc, bool IsCompAssign,
12225                                        ArithConvKind OperationKind);
12226 
12227   /// Type checking for matrix binary operators.
12228   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12229                                           SourceLocation Loc,
12230                                           bool IsCompAssign);
12231   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12232                                        SourceLocation Loc, bool IsCompAssign);
12233 
12234   bool isValidSveBitcast(QualType srcType, QualType destType);
12235 
12236   bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
12237 
12238   bool areVectorTypesSameSize(QualType srcType, QualType destType);
12239   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
12240   bool isLaxVectorConversion(QualType srcType, QualType destType);
12241   bool areSameVectorElemTypes(QualType srcType, QualType destType);
12242   bool anyAltivecTypes(QualType srcType, QualType destType);
12243 
12244   /// type checking declaration initializers (C99 6.7.8)
12245   bool CheckForConstantInitializer(Expr *e, QualType t);
12246 
12247   // type checking C++ declaration initializers (C++ [dcl.init]).
12248 
12249   /// ReferenceCompareResult - Expresses the result of comparing two
12250   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
12251   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
12252   enum ReferenceCompareResult {
12253     /// Ref_Incompatible - The two types are incompatible, so direct
12254     /// reference binding is not possible.
12255     Ref_Incompatible = 0,
12256     /// Ref_Related - The two types are reference-related, which means
12257     /// that their unqualified forms (T1 and T2) are either the same
12258     /// or T1 is a base class of T2.
12259     Ref_Related,
12260     /// Ref_Compatible - The two types are reference-compatible.
12261     Ref_Compatible
12262   };
12263 
12264   // Fake up a scoped enumeration that still contextually converts to bool.
12265   struct ReferenceConversionsScope {
12266     /// The conversions that would be performed on an lvalue of type T2 when
12267     /// binding a reference of type T1 to it, as determined when evaluating
12268     /// whether T1 is reference-compatible with T2.
12269     enum ReferenceConversions {
12270       Qualification = 0x1,
12271       NestedQualification = 0x2,
12272       Function = 0x4,
12273       DerivedToBase = 0x8,
12274       ObjC = 0x10,
12275       ObjCLifetime = 0x20,
12276 
12277       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
12278     };
12279   };
12280   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
12281 
12282   ReferenceCompareResult
12283   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
12284                                ReferenceConversions *Conv = nullptr);
12285 
12286   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12287                                  Expr *CastExpr, CastKind &CastKind,
12288                                  ExprValueKind &VK, CXXCastPath &Path);
12289 
12290   /// Force an expression with unknown-type to an expression of the
12291   /// given type.
12292   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
12293 
12294   /// Type-check an expression that's being passed to an
12295   /// __unknown_anytype parameter.
12296   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
12297                                 Expr *result, QualType &paramType);
12298 
12299   // CheckMatrixCast - Check type constraints for matrix casts.
12300   // We allow casting between matrixes of the same dimensions i.e. when they
12301   // have the same number of rows and column. Returns true if the cast is
12302   // invalid.
12303   bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
12304                        CastKind &Kind);
12305 
12306   // CheckVectorCast - check type constraints for vectors.
12307   // Since vectors are an extension, there are no C standard reference for this.
12308   // We allow casting between vectors and integer datatypes of the same size.
12309   // returns true if the cast is invalid
12310   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
12311                        CastKind &Kind);
12312 
12313   /// Prepare `SplattedExpr` for a vector splat operation, adding
12314   /// implicit casts if necessary.
12315   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
12316 
12317   // CheckExtVectorCast - check type constraints for extended vectors.
12318   // Since vectors are an extension, there are no C standard reference for this.
12319   // We allow casting between vectors and integer datatypes of the same size,
12320   // or vectors and the element type of that vector.
12321   // returns the cast expr
12322   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
12323                                 CastKind &Kind);
12324 
12325   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
12326                                         SourceLocation LParenLoc,
12327                                         Expr *CastExpr,
12328                                         SourceLocation RParenLoc);
12329 
12330   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
12331 
12332   /// Checks for invalid conversions and casts between
12333   /// retainable pointers and other pointer kinds for ARC and Weak.
12334   ARCConversionResult CheckObjCConversion(SourceRange castRange,
12335                                           QualType castType, Expr *&op,
12336                                           CheckedConversionKind CCK,
12337                                           bool Diagnose = true,
12338                                           bool DiagnoseCFAudited = false,
12339                                           BinaryOperatorKind Opc = BO_PtrMemD
12340                                           );
12341 
12342   Expr *stripARCUnbridgedCast(Expr *e);
12343   void diagnoseARCUnbridgedCast(Expr *e);
12344 
12345   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
12346                                              QualType ExprType);
12347 
12348   /// checkRetainCycles - Check whether an Objective-C message send
12349   /// might create an obvious retain cycle.
12350   void checkRetainCycles(ObjCMessageExpr *msg);
12351   void checkRetainCycles(Expr *receiver, Expr *argument);
12352   void checkRetainCycles(VarDecl *Var, Expr *Init);
12353 
12354   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
12355   /// to weak/__unsafe_unretained type.
12356   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
12357 
12358   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
12359   /// to weak/__unsafe_unretained expression.
12360   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
12361 
12362   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
12363   /// \param Method - May be null.
12364   /// \param [out] ReturnType - The return type of the send.
12365   /// \return true iff there were any incompatible types.
12366   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
12367                                  MultiExprArg Args, Selector Sel,
12368                                  ArrayRef<SourceLocation> SelectorLocs,
12369                                  ObjCMethodDecl *Method, bool isClassMessage,
12370                                  bool isSuperMessage, SourceLocation lbrac,
12371                                  SourceLocation rbrac, SourceRange RecRange,
12372                                  QualType &ReturnType, ExprValueKind &VK);
12373 
12374   /// Determine the result of a message send expression based on
12375   /// the type of the receiver, the method expected to receive the message,
12376   /// and the form of the message send.
12377   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
12378                                     ObjCMethodDecl *Method, bool isClassMessage,
12379                                     bool isSuperMessage);
12380 
12381   /// If the given expression involves a message send to a method
12382   /// with a related result type, emit a note describing what happened.
12383   void EmitRelatedResultTypeNote(const Expr *E);
12384 
12385   /// Given that we had incompatible pointer types in a return
12386   /// statement, check whether we're in a method with a related result
12387   /// type, and if so, emit a note describing what happened.
12388   void EmitRelatedResultTypeNoteForReturn(QualType destType);
12389 
12390   class ConditionResult {
12391     Decl *ConditionVar;
12392     FullExprArg Condition;
12393     bool Invalid;
12394     bool HasKnownValue;
12395     bool KnownValue;
12396 
12397     friend class Sema;
12398     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
12399                     bool IsConstexpr)
12400         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
12401           HasKnownValue(IsConstexpr && Condition.get() &&
12402                         !Condition.get()->isValueDependent()),
12403           KnownValue(HasKnownValue &&
12404                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
12405     explicit ConditionResult(bool Invalid)
12406         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
12407           HasKnownValue(false), KnownValue(false) {}
12408 
12409   public:
12410     ConditionResult() : ConditionResult(false) {}
12411     bool isInvalid() const { return Invalid; }
12412     std::pair<VarDecl *, Expr *> get() const {
12413       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
12414                             Condition.get());
12415     }
12416     llvm::Optional<bool> getKnownValue() const {
12417       if (!HasKnownValue)
12418         return None;
12419       return KnownValue;
12420     }
12421   };
12422   static ConditionResult ConditionError() { return ConditionResult(true); }
12423 
12424   enum class ConditionKind {
12425     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
12426     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
12427     Switch       ///< An integral condition for a 'switch' statement.
12428   };
12429   QualType PreferredConditionType(ConditionKind K) const {
12430     return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
12431   }
12432 
12433   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
12434                                  ConditionKind CK, bool MissingOK = false);
12435 
12436   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
12437                                          SourceLocation StmtLoc,
12438                                          ConditionKind CK);
12439 
12440   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
12441 
12442   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
12443                                     SourceLocation StmtLoc,
12444                                     ConditionKind CK);
12445   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
12446 
12447   /// CheckBooleanCondition - Diagnose problems involving the use of
12448   /// the given expression as a boolean condition (e.g. in an if
12449   /// statement).  Also performs the standard function and array
12450   /// decays, possibly changing the input variable.
12451   ///
12452   /// \param Loc - A location associated with the condition, e.g. the
12453   /// 'if' keyword.
12454   /// \return true iff there were any errors
12455   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
12456                                    bool IsConstexpr = false);
12457 
12458   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
12459   /// found in an explicit(bool) specifier.
12460   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
12461 
12462   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
12463   /// Returns true if the explicit specifier is now resolved.
12464   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
12465 
12466   /// DiagnoseAssignmentAsCondition - Given that an expression is
12467   /// being used as a boolean condition, warn if it's an assignment.
12468   void DiagnoseAssignmentAsCondition(Expr *E);
12469 
12470   /// Redundant parentheses over an equality comparison can indicate
12471   /// that the user intended an assignment used as condition.
12472   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
12473 
12474   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
12475   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
12476 
12477   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
12478   /// the specified width and sign.  If an overflow occurs, detect it and emit
12479   /// the specified diagnostic.
12480   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
12481                                           unsigned NewWidth, bool NewSign,
12482                                           SourceLocation Loc, unsigned DiagID);
12483 
12484   /// Checks that the Objective-C declaration is declared in the global scope.
12485   /// Emits an error and marks the declaration as invalid if it's not declared
12486   /// in the global scope.
12487   bool CheckObjCDeclScope(Decl *D);
12488 
12489   /// Abstract base class used for diagnosing integer constant
12490   /// expression violations.
12491   class VerifyICEDiagnoser {
12492   public:
12493     bool Suppress;
12494 
12495     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
12496 
12497     virtual SemaDiagnosticBuilder
12498     diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
12499     virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
12500                                                  SourceLocation Loc) = 0;
12501     virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
12502     virtual ~VerifyICEDiagnoser() {}
12503   };
12504 
12505   enum AllowFoldKind {
12506     NoFold,
12507     AllowFold,
12508   };
12509 
12510   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
12511   /// and reports the appropriate diagnostics. Returns false on success.
12512   /// Can optionally return the value of the expression.
12513   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12514                                              VerifyICEDiagnoser &Diagnoser,
12515                                              AllowFoldKind CanFold = NoFold);
12516   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12517                                              unsigned DiagID,
12518                                              AllowFoldKind CanFold = NoFold);
12519   ExprResult VerifyIntegerConstantExpression(Expr *E,
12520                                              llvm::APSInt *Result = nullptr,
12521                                              AllowFoldKind CanFold = NoFold);
12522   ExprResult VerifyIntegerConstantExpression(Expr *E,
12523                                              AllowFoldKind CanFold = NoFold) {
12524     return VerifyIntegerConstantExpression(E, nullptr, CanFold);
12525   }
12526 
12527   /// VerifyBitField - verifies that a bit field expression is an ICE and has
12528   /// the correct width, and that the field type is valid.
12529   /// Returns false on success.
12530   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
12531                             QualType FieldTy, bool IsMsStruct, Expr *BitWidth);
12532 
12533 private:
12534   unsigned ForceCUDAHostDeviceDepth = 0;
12535 
12536 public:
12537   /// Increments our count of the number of times we've seen a pragma forcing
12538   /// functions to be __host__ __device__.  So long as this count is greater
12539   /// than zero, all functions encountered will be __host__ __device__.
12540   void PushForceCUDAHostDevice();
12541 
12542   /// Decrements our count of the number of times we've seen a pragma forcing
12543   /// functions to be __host__ __device__.  Returns false if the count is 0
12544   /// before incrementing, so you can emit an error.
12545   bool PopForceCUDAHostDevice();
12546 
12547   /// Diagnostics that are emitted only if we discover that the given function
12548   /// must be codegen'ed.  Because handling these correctly adds overhead to
12549   /// compilation, this is currently only enabled for CUDA compilations.
12550   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
12551                  std::vector<PartialDiagnosticAt>>
12552       DeviceDeferredDiags;
12553 
12554   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
12555   /// key in a hashtable, both the FD and location are hashed.
12556   struct FunctionDeclAndLoc {
12557     CanonicalDeclPtr<FunctionDecl> FD;
12558     SourceLocation Loc;
12559   };
12560 
12561   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
12562   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
12563   /// same deferred diag twice.
12564   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
12565 
12566   /// An inverse call graph, mapping known-emitted functions to one of their
12567   /// known-emitted callers (plus the location of the call).
12568   ///
12569   /// Functions that we can tell a priori must be emitted aren't added to this
12570   /// map.
12571   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
12572                  /* Caller = */ FunctionDeclAndLoc>
12573       DeviceKnownEmittedFns;
12574 
12575   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12576   /// context is "used as device code".
12577   ///
12578   /// - If CurContext is a __host__ function, does not emit any diagnostics
12579   ///   unless \p EmitOnBothSides is true.
12580   /// - If CurContext is a __device__ or __global__ function, emits the
12581   ///   diagnostics immediately.
12582   /// - If CurContext is a __host__ __device__ function and we are compiling for
12583   ///   the device, creates a diagnostic which is emitted if and when we realize
12584   ///   that the function will be codegen'ed.
12585   ///
12586   /// Example usage:
12587   ///
12588   ///  // Variable-length arrays are not allowed in CUDA device code.
12589   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
12590   ///    return ExprError();
12591   ///  // Otherwise, continue parsing as normal.
12592   SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
12593                                              unsigned DiagID);
12594 
12595   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12596   /// context is "used as host code".
12597   ///
12598   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
12599   SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
12600 
12601   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12602   /// context is "used as device code".
12603   ///
12604   /// - If CurContext is a `declare target` function or it is known that the
12605   /// function is emitted for the device, emits the diagnostics immediately.
12606   /// - If CurContext is a non-`declare target` function and we are compiling
12607   ///   for the device, creates a diagnostic which is emitted if and when we
12608   ///   realize that the function will be codegen'ed.
12609   ///
12610   /// Example usage:
12611   ///
12612   ///  // Variable-length arrays are not allowed in NVPTX device code.
12613   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
12614   ///    return ExprError();
12615   ///  // Otherwise, continue parsing as normal.
12616   SemaDiagnosticBuilder
12617   diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
12618 
12619   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12620   /// context is "used as host code".
12621   ///
12622   /// - If CurContext is a `declare target` function or it is known that the
12623   /// function is emitted for the host, emits the diagnostics immediately.
12624   /// - If CurContext is a non-host function, just ignore it.
12625   ///
12626   /// Example usage:
12627   ///
12628   ///  // Variable-length arrays are not allowed in NVPTX device code.
12629   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
12630   ///    return ExprError();
12631   ///  // Otherwise, continue parsing as normal.
12632   SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
12633                                              unsigned DiagID, FunctionDecl *FD);
12634 
12635   SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
12636                                    FunctionDecl *FD = nullptr);
12637   SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
12638                                    const PartialDiagnostic &PD,
12639                                    FunctionDecl *FD = nullptr) {
12640     return targetDiag(Loc, PD.getDiagID(), FD) << PD;
12641   }
12642 
12643   /// Check if the type is allowed to be used for the current target.
12644   void checkTypeSupport(QualType Ty, SourceLocation Loc,
12645                         ValueDecl *D = nullptr);
12646 
12647   enum CUDAFunctionTarget {
12648     CFT_Device,
12649     CFT_Global,
12650     CFT_Host,
12651     CFT_HostDevice,
12652     CFT_InvalidTarget
12653   };
12654 
12655   /// Determines whether the given function is a CUDA device/host/kernel/etc.
12656   /// function.
12657   ///
12658   /// Use this rather than examining the function's attributes yourself -- you
12659   /// will get it wrong.  Returns CFT_Host if D is null.
12660   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
12661                                         bool IgnoreImplicitHDAttr = false);
12662   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
12663 
12664   enum CUDAVariableTarget {
12665     CVT_Device,  /// Emitted on device side with a shadow variable on host side
12666     CVT_Host,    /// Emitted on host side only
12667     CVT_Both,    /// Emitted on both sides with different addresses
12668     CVT_Unified, /// Emitted as a unified address, e.g. managed variables
12669   };
12670   /// Determines whether the given variable is emitted on host or device side.
12671   CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
12672 
12673   /// Gets the CUDA target for the current context.
12674   CUDAFunctionTarget CurrentCUDATarget() {
12675     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
12676   }
12677 
12678   static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
12679 
12680   // CUDA function call preference. Must be ordered numerically from
12681   // worst to best.
12682   enum CUDAFunctionPreference {
12683     CFP_Never,      // Invalid caller/callee combination.
12684     CFP_WrongSide,  // Calls from host-device to host or device
12685                     // function that do not match current compilation
12686                     // mode.
12687     CFP_HostDevice, // Any calls to host/device functions.
12688     CFP_SameSide,   // Calls from host-device to host or device
12689                     // function matching current compilation mode.
12690     CFP_Native,     // host-to-host or device-to-device calls.
12691   };
12692 
12693   /// Identifies relative preference of a given Caller/Callee
12694   /// combination, based on their host/device attributes.
12695   /// \param Caller function which needs address of \p Callee.
12696   ///               nullptr in case of global context.
12697   /// \param Callee target function
12698   ///
12699   /// \returns preference value for particular Caller/Callee combination.
12700   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
12701                                                 const FunctionDecl *Callee);
12702 
12703   /// Determines whether Caller may invoke Callee, based on their CUDA
12704   /// host/device attributes.  Returns false if the call is not allowed.
12705   ///
12706   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
12707   /// semantically correct CUDA programs, but only if they're never codegen'ed.
12708   bool IsAllowedCUDACall(const FunctionDecl *Caller,
12709                          const FunctionDecl *Callee) {
12710     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
12711   }
12712 
12713   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
12714   /// depending on FD and the current compilation settings.
12715   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
12716                                    const LookupResult &Previous);
12717 
12718   /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
12719   /// and current compilation settings.
12720   void MaybeAddCUDAConstantAttr(VarDecl *VD);
12721 
12722 public:
12723   /// Check whether we're allowed to call Callee from the current context.
12724   ///
12725   /// - If the call is never allowed in a semantically-correct program
12726   ///   (CFP_Never), emits an error and returns false.
12727   ///
12728   /// - If the call is allowed in semantically-correct programs, but only if
12729   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
12730   ///   be emitted if and when the caller is codegen'ed, and returns true.
12731   ///
12732   ///   Will only create deferred diagnostics for a given SourceLocation once,
12733   ///   so you can safely call this multiple times without generating duplicate
12734   ///   deferred errors.
12735   ///
12736   /// - Otherwise, returns true without emitting any diagnostics.
12737   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
12738 
12739   void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
12740 
12741   /// Set __device__ or __host__ __device__ attributes on the given lambda
12742   /// operator() method.
12743   ///
12744   /// CUDA lambdas by default is host device function unless it has explicit
12745   /// host or device attribute.
12746   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
12747 
12748   /// Finds a function in \p Matches with highest calling priority
12749   /// from \p Caller context and erases all functions with lower
12750   /// calling priority.
12751   void EraseUnwantedCUDAMatches(
12752       const FunctionDecl *Caller,
12753       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
12754 
12755   /// Given a implicit special member, infer its CUDA target from the
12756   /// calls it needs to make to underlying base/field special members.
12757   /// \param ClassDecl the class for which the member is being created.
12758   /// \param CSM the kind of special member.
12759   /// \param MemberDecl the special member itself.
12760   /// \param ConstRHS true if this is a copy operation with a const object on
12761   ///        its RHS.
12762   /// \param Diagnose true if this call should emit diagnostics.
12763   /// \return true if there was an error inferring.
12764   /// The result of this call is implicit CUDA target attribute(s) attached to
12765   /// the member declaration.
12766   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12767                                                CXXSpecialMember CSM,
12768                                                CXXMethodDecl *MemberDecl,
12769                                                bool ConstRHS,
12770                                                bool Diagnose);
12771 
12772   /// \return true if \p CD can be considered empty according to CUDA
12773   /// (E.2.3.1 in CUDA 7.5 Programming guide).
12774   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12775   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12776 
12777   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12778   // case of error emits appropriate diagnostic and invalidates \p Var.
12779   //
12780   // \details CUDA allows only empty constructors as initializers for global
12781   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12782   // __shared__ variables whether they are local or not (they all are implicitly
12783   // static in CUDA). One exception is that CUDA allows constant initializers
12784   // for __constant__ and __device__ variables.
12785   void checkAllowedCUDAInitializer(VarDecl *VD);
12786 
12787   /// Check whether NewFD is a valid overload for CUDA. Emits
12788   /// diagnostics and invalidates NewFD if not.
12789   void checkCUDATargetOverload(FunctionDecl *NewFD,
12790                                const LookupResult &Previous);
12791   /// Copies target attributes from the template TD to the function FD.
12792   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12793 
12794   /// Returns the name of the launch configuration function.  This is the name
12795   /// of the function that will be called to configure kernel call, with the
12796   /// parameters specified via <<<>>>.
12797   std::string getCudaConfigureFuncName() const;
12798 
12799   /// \name Code completion
12800   //@{
12801   /// Describes the context in which code completion occurs.
12802   enum ParserCompletionContext {
12803     /// Code completion occurs at top-level or namespace context.
12804     PCC_Namespace,
12805     /// Code completion occurs within a class, struct, or union.
12806     PCC_Class,
12807     /// Code completion occurs within an Objective-C interface, protocol,
12808     /// or category.
12809     PCC_ObjCInterface,
12810     /// Code completion occurs within an Objective-C implementation or
12811     /// category implementation
12812     PCC_ObjCImplementation,
12813     /// Code completion occurs within the list of instance variables
12814     /// in an Objective-C interface, protocol, category, or implementation.
12815     PCC_ObjCInstanceVariableList,
12816     /// Code completion occurs following one or more template
12817     /// headers.
12818     PCC_Template,
12819     /// Code completion occurs following one or more template
12820     /// headers within a class.
12821     PCC_MemberTemplate,
12822     /// Code completion occurs within an expression.
12823     PCC_Expression,
12824     /// Code completion occurs within a statement, which may
12825     /// also be an expression or a declaration.
12826     PCC_Statement,
12827     /// Code completion occurs at the beginning of the
12828     /// initialization statement (or expression) in a for loop.
12829     PCC_ForInit,
12830     /// Code completion occurs within the condition of an if,
12831     /// while, switch, or for statement.
12832     PCC_Condition,
12833     /// Code completion occurs within the body of a function on a
12834     /// recovery path, where we do not have a specific handle on our position
12835     /// in the grammar.
12836     PCC_RecoveryInFunction,
12837     /// Code completion occurs where only a type is permitted.
12838     PCC_Type,
12839     /// Code completion occurs in a parenthesized expression, which
12840     /// might also be a type cast.
12841     PCC_ParenthesizedExpression,
12842     /// Code completion occurs within a sequence of declaration
12843     /// specifiers within a function, method, or block.
12844     PCC_LocalDeclarationSpecifiers
12845   };
12846 
12847   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12848   void CodeCompleteOrdinaryName(Scope *S,
12849                                 ParserCompletionContext CompletionContext);
12850   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12851                             bool AllowNonIdentifiers,
12852                             bool AllowNestedNameSpecifiers);
12853 
12854   struct CodeCompleteExpressionData;
12855   void CodeCompleteExpression(Scope *S,
12856                               const CodeCompleteExpressionData &Data);
12857   void CodeCompleteExpression(Scope *S, QualType PreferredType,
12858                               bool IsParenthesized = false);
12859   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12860                                        SourceLocation OpLoc, bool IsArrow,
12861                                        bool IsBaseExprStatement,
12862                                        QualType PreferredType);
12863   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12864                                      QualType PreferredType);
12865   void CodeCompleteTag(Scope *S, unsigned TagSpec);
12866   void CodeCompleteTypeQualifiers(DeclSpec &DS);
12867   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12868                                       const VirtSpecifiers *VS = nullptr);
12869   void CodeCompleteBracketDeclarator(Scope *S);
12870   void CodeCompleteCase(Scope *S);
12871   enum class AttributeCompletion {
12872     Attribute,
12873     Scope,
12874     None,
12875   };
12876   void CodeCompleteAttribute(
12877       AttributeCommonInfo::Syntax Syntax,
12878       AttributeCompletion Completion = AttributeCompletion::Attribute,
12879       const IdentifierInfo *Scope = nullptr);
12880   /// Determines the preferred type of the current function argument, by
12881   /// examining the signatures of all possible overloads.
12882   /// Returns null if unknown or ambiguous, or if code completion is off.
12883   ///
12884   /// If the code completion point has been reached, also reports the function
12885   /// signatures that were considered.
12886   ///
12887   /// FIXME: rename to GuessCallArgumentType to reduce confusion.
12888   QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
12889                                     SourceLocation OpenParLoc);
12890   QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc,
12891                                            ArrayRef<Expr *> Args,
12892                                            SourceLocation OpenParLoc,
12893                                            bool Braced);
12894   QualType ProduceCtorInitMemberSignatureHelp(
12895       Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
12896       ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
12897       bool Braced);
12898   QualType ProduceTemplateArgumentSignatureHelp(
12899       TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc);
12900   void CodeCompleteInitializer(Scope *S, Decl *D);
12901   /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12902   /// expressions in the initializer list seen so far and \p D is the current
12903   /// Designation being parsed.
12904   void CodeCompleteDesignator(const QualType BaseType,
12905                               llvm::ArrayRef<Expr *> InitExprs,
12906                               const Designation &D);
12907   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12908 
12909   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12910                                bool IsUsingDeclaration, QualType BaseType,
12911                                QualType PreferredType);
12912   void CodeCompleteUsing(Scope *S);
12913   void CodeCompleteUsingDirective(Scope *S);
12914   void CodeCompleteNamespaceDecl(Scope *S);
12915   void CodeCompleteNamespaceAliasDecl(Scope *S);
12916   void CodeCompleteOperatorName(Scope *S);
12917   void CodeCompleteConstructorInitializer(
12918                                 Decl *Constructor,
12919                                 ArrayRef<CXXCtorInitializer *> Initializers);
12920 
12921   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12922                                     bool AfterAmpersand);
12923   void CodeCompleteAfterFunctionEquals(Declarator &D);
12924 
12925   void CodeCompleteObjCAtDirective(Scope *S);
12926   void CodeCompleteObjCAtVisibility(Scope *S);
12927   void CodeCompleteObjCAtStatement(Scope *S);
12928   void CodeCompleteObjCAtExpression(Scope *S);
12929   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12930   void CodeCompleteObjCPropertyGetter(Scope *S);
12931   void CodeCompleteObjCPropertySetter(Scope *S);
12932   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12933                                    bool IsParameter);
12934   void CodeCompleteObjCMessageReceiver(Scope *S);
12935   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12936                                     ArrayRef<IdentifierInfo *> SelIdents,
12937                                     bool AtArgumentExpression);
12938   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12939                                     ArrayRef<IdentifierInfo *> SelIdents,
12940                                     bool AtArgumentExpression,
12941                                     bool IsSuper = false);
12942   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12943                                        ArrayRef<IdentifierInfo *> SelIdents,
12944                                        bool AtArgumentExpression,
12945                                        ObjCInterfaceDecl *Super = nullptr);
12946   void CodeCompleteObjCForCollection(Scope *S,
12947                                      DeclGroupPtrTy IterationVar);
12948   void CodeCompleteObjCSelector(Scope *S,
12949                                 ArrayRef<IdentifierInfo *> SelIdents);
12950   void CodeCompleteObjCProtocolReferences(
12951                                          ArrayRef<IdentifierLocPair> Protocols);
12952   void CodeCompleteObjCProtocolDecl(Scope *S);
12953   void CodeCompleteObjCInterfaceDecl(Scope *S);
12954   void CodeCompleteObjCSuperclass(Scope *S,
12955                                   IdentifierInfo *ClassName,
12956                                   SourceLocation ClassNameLoc);
12957   void CodeCompleteObjCImplementationDecl(Scope *S);
12958   void CodeCompleteObjCInterfaceCategory(Scope *S,
12959                                          IdentifierInfo *ClassName,
12960                                          SourceLocation ClassNameLoc);
12961   void CodeCompleteObjCImplementationCategory(Scope *S,
12962                                               IdentifierInfo *ClassName,
12963                                               SourceLocation ClassNameLoc);
12964   void CodeCompleteObjCPropertyDefinition(Scope *S);
12965   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12966                                               IdentifierInfo *PropertyName);
12967   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12968                                   ParsedType ReturnType);
12969   void CodeCompleteObjCMethodDeclSelector(Scope *S,
12970                                           bool IsInstanceMethod,
12971                                           bool AtParameterName,
12972                                           ParsedType ReturnType,
12973                                           ArrayRef<IdentifierInfo *> SelIdents);
12974   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12975                                             SourceLocation ClassNameLoc,
12976                                             bool IsBaseExprStatement);
12977   void CodeCompletePreprocessorDirective(bool InConditional);
12978   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12979   void CodeCompletePreprocessorMacroName(bool IsDefinition);
12980   void CodeCompletePreprocessorExpression();
12981   void CodeCompletePreprocessorMacroArgument(Scope *S,
12982                                              IdentifierInfo *Macro,
12983                                              MacroInfo *MacroInfo,
12984                                              unsigned Argument);
12985   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12986   void CodeCompleteNaturalLanguage();
12987   void CodeCompleteAvailabilityPlatformName();
12988   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12989                                    CodeCompletionTUInfo &CCTUInfo,
12990                   SmallVectorImpl<CodeCompletionResult> &Results);
12991   //@}
12992 
12993   //===--------------------------------------------------------------------===//
12994   // Extra semantic analysis beyond the C type system
12995 
12996 public:
12997   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12998                                                 unsigned ByteNo) const;
12999 
13000 private:
13001   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13002                         const ArraySubscriptExpr *ASE=nullptr,
13003                         bool AllowOnePastEnd=true, bool IndexNegated=false);
13004   void CheckArrayAccess(const Expr *E);
13005   // Used to grab the relevant information from a FormatAttr and a
13006   // FunctionDeclaration.
13007   struct FormatStringInfo {
13008     unsigned FormatIdx;
13009     unsigned FirstDataArg;
13010     bool HasVAListArg;
13011   };
13012 
13013   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
13014                                   FormatStringInfo *FSI);
13015   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
13016                          const FunctionProtoType *Proto);
13017   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
13018                            ArrayRef<const Expr *> Args);
13019   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
13020                         const FunctionProtoType *Proto);
13021   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
13022   void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
13023                             ArrayRef<const Expr *> Args,
13024                             const FunctionProtoType *Proto, SourceLocation Loc);
13025 
13026   void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
13027                          StringRef ParamName, QualType ArgTy, QualType ParamTy);
13028 
13029   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
13030                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
13031                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
13032                  VariadicCallType CallType);
13033 
13034   bool CheckObjCString(Expr *Arg);
13035   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
13036 
13037   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
13038                                       unsigned BuiltinID, CallExpr *TheCall);
13039 
13040   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13041                                   CallExpr *TheCall);
13042 
13043   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
13044 
13045   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
13046                                     unsigned MaxWidth);
13047   bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13048                                     CallExpr *TheCall);
13049   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13050   bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13051   bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13052                                    CallExpr *TheCall);
13053   bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
13054                                     bool WantCDE);
13055   bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13056                                    CallExpr *TheCall);
13057 
13058   bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13059                                        CallExpr *TheCall);
13060   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13061   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13062   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13063   bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13064                                     CallExpr *TheCall);
13065   bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
13066                            CallExpr *TheCall);
13067   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
13068   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13069   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
13070   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
13071   bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
13072   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
13073                                          ArrayRef<int> ArgNums);
13074   bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
13075   bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
13076                                             ArrayRef<int> ArgNums);
13077   bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13078                                    CallExpr *TheCall);
13079   bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13080                                    CallExpr *TheCall);
13081   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
13082   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
13083   bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
13084                                      CallExpr *TheCall);
13085 
13086   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
13087   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
13088   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
13089   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
13090   bool SemaBuiltinComplex(CallExpr *TheCall);
13091   bool SemaBuiltinVSX(CallExpr *TheCall);
13092   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
13093   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
13094 
13095 public:
13096   // Used by C++ template instantiation.
13097   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
13098   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
13099                                    SourceLocation BuiltinLoc,
13100                                    SourceLocation RParenLoc);
13101 
13102 private:
13103   bool SemaBuiltinPrefetch(CallExpr *TheCall);
13104   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
13105   bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
13106   bool SemaBuiltinAssume(CallExpr *TheCall);
13107   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
13108   bool SemaBuiltinLongjmp(CallExpr *TheCall);
13109   bool SemaBuiltinSetjmp(CallExpr *TheCall);
13110   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
13111   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
13112   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
13113                                      AtomicExpr::AtomicOp Op);
13114   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
13115                                                     bool IsDelete);
13116   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
13117                               llvm::APSInt &Result);
13118   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
13119                                    int High, bool RangeIsError = true);
13120   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
13121                                       unsigned Multiple);
13122   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
13123   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
13124                                          unsigned ArgBits);
13125   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
13126                                                unsigned ArgBits);
13127   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
13128                                 int ArgNum, unsigned ExpectedFieldNum,
13129                                 bool AllowName);
13130   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
13131   bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
13132                              const char *TypeDesc);
13133 
13134   bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
13135 
13136   bool SemaBuiltinElementwiseMath(CallExpr *TheCall);
13137   bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall);
13138   bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
13139 
13140   // Matrix builtin handling.
13141   ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
13142                                         ExprResult CallResult);
13143   ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
13144                                               ExprResult CallResult);
13145   ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
13146                                                ExprResult CallResult);
13147 
13148 public:
13149   enum FormatStringType {
13150     FST_Scanf,
13151     FST_Printf,
13152     FST_NSString,
13153     FST_Strftime,
13154     FST_Strfmon,
13155     FST_Kprintf,
13156     FST_FreeBSDKPrintf,
13157     FST_OSTrace,
13158     FST_OSLog,
13159     FST_Unknown
13160   };
13161   static FormatStringType GetFormatStringType(const FormatAttr *Format);
13162 
13163   bool FormatStringHasSArg(const StringLiteral *FExpr);
13164 
13165   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
13166 
13167 private:
13168   bool CheckFormatArguments(const FormatAttr *Format,
13169                             ArrayRef<const Expr *> Args,
13170                             bool IsCXXMember,
13171                             VariadicCallType CallType,
13172                             SourceLocation Loc, SourceRange Range,
13173                             llvm::SmallBitVector &CheckedVarArgs);
13174   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
13175                             bool HasVAListArg, unsigned format_idx,
13176                             unsigned firstDataArg, FormatStringType Type,
13177                             VariadicCallType CallType,
13178                             SourceLocation Loc, SourceRange range,
13179                             llvm::SmallBitVector &CheckedVarArgs);
13180 
13181   void CheckAbsoluteValueFunction(const CallExpr *Call,
13182                                   const FunctionDecl *FDecl);
13183 
13184   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
13185 
13186   void CheckMemaccessArguments(const CallExpr *Call,
13187                                unsigned BId,
13188                                IdentifierInfo *FnName);
13189 
13190   void CheckStrlcpycatArguments(const CallExpr *Call,
13191                                 IdentifierInfo *FnName);
13192 
13193   void CheckStrncatArguments(const CallExpr *Call,
13194                              IdentifierInfo *FnName);
13195 
13196   void CheckFreeArguments(const CallExpr *E);
13197 
13198   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
13199                           SourceLocation ReturnLoc,
13200                           bool isObjCMethod = false,
13201                           const AttrVec *Attrs = nullptr,
13202                           const FunctionDecl *FD = nullptr);
13203 
13204 public:
13205   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
13206                             BinaryOperatorKind Opcode);
13207 
13208 private:
13209   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
13210   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
13211   void CheckForIntOverflow(Expr *E);
13212   void CheckUnsequencedOperations(const Expr *E);
13213 
13214   /// Perform semantic checks on a completed expression. This will either
13215   /// be a full-expression or a default argument expression.
13216   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
13217                           bool IsConstexpr = false);
13218 
13219   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
13220                                    Expr *Init);
13221 
13222   /// Check if there is a field shadowing.
13223   void CheckShadowInheritedFields(const SourceLocation &Loc,
13224                                   DeclarationName FieldName,
13225                                   const CXXRecordDecl *RD,
13226                                   bool DeclIsField = true);
13227 
13228   /// Check if the given expression contains 'break' or 'continue'
13229   /// statement that produces control flow different from GCC.
13230   void CheckBreakContinueBinding(Expr *E);
13231 
13232   /// Check whether receiver is mutable ObjC container which
13233   /// attempts to add itself into the container
13234   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
13235 
13236   void CheckTCBEnforcement(const SourceLocation CallExprLoc,
13237                            const NamedDecl *Callee);
13238 
13239   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
13240   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
13241                                  bool DeleteWasArrayForm);
13242 public:
13243   /// Register a magic integral constant to be used as a type tag.
13244   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13245                                   uint64_t MagicValue, QualType Type,
13246                                   bool LayoutCompatible, bool MustBeNull);
13247 
13248   struct TypeTagData {
13249     TypeTagData() {}
13250 
13251     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
13252         Type(Type), LayoutCompatible(LayoutCompatible),
13253         MustBeNull(MustBeNull)
13254     {}
13255 
13256     QualType Type;
13257 
13258     /// If true, \c Type should be compared with other expression's types for
13259     /// layout-compatibility.
13260     unsigned LayoutCompatible : 1;
13261     unsigned MustBeNull : 1;
13262   };
13263 
13264   /// A pair of ArgumentKind identifier and magic value.  This uniquely
13265   /// identifies the magic value.
13266   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
13267 
13268 private:
13269   /// A map from magic value to type information.
13270   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
13271       TypeTagForDatatypeMagicValues;
13272 
13273   /// Peform checks on a call of a function with argument_with_type_tag
13274   /// or pointer_with_type_tag attributes.
13275   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13276                                 const ArrayRef<const Expr *> ExprArgs,
13277                                 SourceLocation CallSiteLoc);
13278 
13279   /// Check if we are taking the address of a packed field
13280   /// as this may be a problem if the pointer value is dereferenced.
13281   void CheckAddressOfPackedMember(Expr *rhs);
13282 
13283   /// The parser's current scope.
13284   ///
13285   /// The parser maintains this state here.
13286   Scope *CurScope;
13287 
13288   mutable IdentifierInfo *Ident_super;
13289   mutable IdentifierInfo *Ident___float128;
13290 
13291   /// Nullability type specifiers.
13292   IdentifierInfo *Ident__Nonnull = nullptr;
13293   IdentifierInfo *Ident__Nullable = nullptr;
13294   IdentifierInfo *Ident__Nullable_result = nullptr;
13295   IdentifierInfo *Ident__Null_unspecified = nullptr;
13296 
13297   IdentifierInfo *Ident_NSError = nullptr;
13298 
13299   /// The handler for the FileChanged preprocessor events.
13300   ///
13301   /// Used for diagnostics that implement custom semantic analysis for #include
13302   /// directives, like -Wpragma-pack.
13303   sema::SemaPPCallbacks *SemaPPCallbackHandler;
13304 
13305 protected:
13306   friend class Parser;
13307   friend class InitializationSequence;
13308   friend class ASTReader;
13309   friend class ASTDeclReader;
13310   friend class ASTWriter;
13311 
13312 public:
13313   /// Retrieve the keyword associated
13314   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
13315 
13316   /// The struct behind the CFErrorRef pointer.
13317   RecordDecl *CFError = nullptr;
13318   bool isCFError(RecordDecl *D);
13319 
13320   /// Retrieve the identifier "NSError".
13321   IdentifierInfo *getNSErrorIdent();
13322 
13323   /// Retrieve the parser's current scope.
13324   ///
13325   /// This routine must only be used when it is certain that semantic analysis
13326   /// and the parser are in precisely the same context, which is not the case
13327   /// when, e.g., we are performing any kind of template instantiation.
13328   /// Therefore, the only safe places to use this scope are in the parser
13329   /// itself and in routines directly invoked from the parser and *never* from
13330   /// template substitution or instantiation.
13331   Scope *getCurScope() const { return CurScope; }
13332 
13333   void incrementMSManglingNumber() const {
13334     return CurScope->incrementMSManglingNumber();
13335   }
13336 
13337   IdentifierInfo *getSuperIdentifier() const;
13338   IdentifierInfo *getFloat128Identifier() const;
13339 
13340   ObjCContainerDecl *getObjCDeclContext() const;
13341 
13342   DeclContext *getCurLexicalContext() const {
13343     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
13344   }
13345 
13346   const DeclContext *getCurObjCLexicalContext() const {
13347     const DeclContext *DC = getCurLexicalContext();
13348     // A category implicitly has the attribute of the interface.
13349     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
13350       DC = CatD->getClassInterface();
13351     return DC;
13352   }
13353 
13354   /// Determine the number of levels of enclosing template parameters. This is
13355   /// only usable while parsing. Note that this does not include dependent
13356   /// contexts in which no template parameters have yet been declared, such as
13357   /// in a terse function template or generic lambda before the first 'auto' is
13358   /// encountered.
13359   unsigned getTemplateDepth(Scope *S) const;
13360 
13361   /// To be used for checking whether the arguments being passed to
13362   /// function exceeds the number of parameters expected for it.
13363   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
13364                                bool PartialOverloading = false) {
13365     // We check whether we're just after a comma in code-completion.
13366     if (NumArgs > 0 && PartialOverloading)
13367       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
13368     return NumArgs > NumParams;
13369   }
13370 
13371   // Emitting members of dllexported classes is delayed until the class
13372   // (including field initializers) is fully parsed.
13373   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
13374   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
13375 
13376 private:
13377   int ParsingClassDepth = 0;
13378 
13379   class SavePendingParsedClassStateRAII {
13380   public:
13381     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
13382 
13383     ~SavePendingParsedClassStateRAII() {
13384       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
13385              "there shouldn't be any pending delayed exception spec checks");
13386       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
13387              "there shouldn't be any pending delayed exception spec checks");
13388       swapSavedState();
13389     }
13390 
13391   private:
13392     Sema &S;
13393     decltype(DelayedOverridingExceptionSpecChecks)
13394         SavedOverridingExceptionSpecChecks;
13395     decltype(DelayedEquivalentExceptionSpecChecks)
13396         SavedEquivalentExceptionSpecChecks;
13397 
13398     void swapSavedState() {
13399       SavedOverridingExceptionSpecChecks.swap(
13400           S.DelayedOverridingExceptionSpecChecks);
13401       SavedEquivalentExceptionSpecChecks.swap(
13402           S.DelayedEquivalentExceptionSpecChecks);
13403     }
13404   };
13405 
13406   /// Helper class that collects misaligned member designations and
13407   /// their location info for delayed diagnostics.
13408   struct MisalignedMember {
13409     Expr *E;
13410     RecordDecl *RD;
13411     ValueDecl *MD;
13412     CharUnits Alignment;
13413 
13414     MisalignedMember() : E(), RD(), MD() {}
13415     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
13416                      CharUnits Alignment)
13417         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
13418     explicit MisalignedMember(Expr *E)
13419         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
13420 
13421     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
13422   };
13423   /// Small set of gathered accesses to potentially misaligned members
13424   /// due to the packed attribute.
13425   SmallVector<MisalignedMember, 4> MisalignedMembers;
13426 
13427   /// Adds an expression to the set of gathered misaligned members.
13428   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13429                                      CharUnits Alignment);
13430 
13431 public:
13432   /// Diagnoses the current set of gathered accesses. This typically
13433   /// happens at full expression level. The set is cleared after emitting the
13434   /// diagnostics.
13435   void DiagnoseMisalignedMembers();
13436 
13437   /// This function checks if the expression is in the sef of potentially
13438   /// misaligned members and it is converted to some pointer type T with lower
13439   /// or equal alignment requirements. If so it removes it. This is used when
13440   /// we do not want to diagnose such misaligned access (e.g. in conversions to
13441   /// void*).
13442   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
13443 
13444   /// This function calls Action when it determines that E designates a
13445   /// misaligned member due to the packed attribute. This is used to emit
13446   /// local diagnostics like in reference binding.
13447   void RefersToMemberWithReducedAlignment(
13448       Expr *E,
13449       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13450           Action);
13451 
13452   /// Describes the reason a calling convention specification was ignored, used
13453   /// for diagnostics.
13454   enum class CallingConventionIgnoredReason {
13455     ForThisTarget = 0,
13456     VariadicFunction,
13457     ConstructorDestructor,
13458     BuiltinFunction
13459   };
13460   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13461   /// context is "used as device code".
13462   ///
13463   /// - If CurLexicalContext is a kernel function or it is known that the
13464   ///   function will be emitted for the device, emits the diagnostics
13465   ///   immediately.
13466   /// - If CurLexicalContext is a function and we are compiling
13467   ///   for the device, but we don't know that this function will be codegen'ed
13468   ///   for devive yet, creates a diagnostic which is emitted if and when we
13469   ///   realize that the function will be codegen'ed.
13470   ///
13471   /// Example usage:
13472   ///
13473   /// Diagnose __float128 type usage only from SYCL device code if the current
13474   /// target doesn't support it
13475   /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
13476   ///     S.getLangOpts().SYCLIsDevice)
13477   ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
13478   SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
13479                                              unsigned DiagID);
13480 
13481   /// Check whether we're allowed to call Callee from the current context.
13482   ///
13483   /// - If the call is never allowed in a semantically-correct program
13484   ///   emits an error and returns false.
13485   ///
13486   /// - If the call is allowed in semantically-correct programs, but only if
13487   ///   it's never codegen'ed, creates a deferred diagnostic to be emitted if
13488   ///   and when the caller is codegen'ed, and returns true.
13489   ///
13490   /// - Otherwise, returns true without emitting any diagnostics.
13491   ///
13492   /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
13493   /// codegen'ed yet.
13494   bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
13495   void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
13496                                   llvm::DenseSet<QualType> Visited,
13497                                   ValueDecl *DeclToCheck);
13498 };
13499 
13500 /// RAII object that enters a new expression evaluation context.
13501 class EnterExpressionEvaluationContext {
13502   Sema &Actions;
13503   bool Entered = true;
13504 
13505 public:
13506   EnterExpressionEvaluationContext(
13507       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13508       Decl *LambdaContextDecl = nullptr,
13509       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13510           Sema::ExpressionEvaluationContextRecord::EK_Other,
13511       bool ShouldEnter = true)
13512       : Actions(Actions), Entered(ShouldEnter) {
13513     if (Entered)
13514       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
13515                                               ExprContext);
13516   }
13517   EnterExpressionEvaluationContext(
13518       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13519       Sema::ReuseLambdaContextDecl_t,
13520       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13521           Sema::ExpressionEvaluationContextRecord::EK_Other)
13522       : Actions(Actions) {
13523     Actions.PushExpressionEvaluationContext(
13524         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
13525   }
13526 
13527   enum InitListTag { InitList };
13528   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
13529                                    bool ShouldEnter = true)
13530       : Actions(Actions), Entered(false) {
13531     // In C++11 onwards, narrowing checks are performed on the contents of
13532     // braced-init-lists, even when they occur within unevaluated operands.
13533     // Therefore we still need to instantiate constexpr functions used in such
13534     // a context.
13535     if (ShouldEnter && Actions.isUnevaluatedContext() &&
13536         Actions.getLangOpts().CPlusPlus11) {
13537       Actions.PushExpressionEvaluationContext(
13538           Sema::ExpressionEvaluationContext::UnevaluatedList);
13539       Entered = true;
13540     }
13541   }
13542 
13543   ~EnterExpressionEvaluationContext() {
13544     if (Entered)
13545       Actions.PopExpressionEvaluationContext();
13546   }
13547 };
13548 
13549 DeductionFailureInfo
13550 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
13551                          sema::TemplateDeductionInfo &Info);
13552 
13553 /// Contains a late templated function.
13554 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
13555 struct LateParsedTemplate {
13556   CachedTokens Toks;
13557   /// The template function declaration to be late parsed.
13558   Decl *D;
13559 };
13560 
13561 template <>
13562 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
13563                                                  PragmaMsStackAction Action,
13564                                                  llvm::StringRef StackSlotLabel,
13565                                                  AlignPackInfo Value);
13566 
13567 } // end namespace clang
13568 
13569 namespace llvm {
13570 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
13571 // SourceLocation.
13572 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
13573   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
13574   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
13575 
13576   static FunctionDeclAndLoc getEmptyKey() {
13577     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
13578   }
13579 
13580   static FunctionDeclAndLoc getTombstoneKey() {
13581     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
13582   }
13583 
13584   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
13585     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
13586                         FDL.Loc.getHashValue());
13587   }
13588 
13589   static bool isEqual(const FunctionDeclAndLoc &LHS,
13590                       const FunctionDeclAndLoc &RHS) {
13591     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
13592   }
13593 };
13594 } // namespace llvm
13595 
13596 #endif
13597