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> struct DenseMapInfo;
78   template <typename ValueT, typename ValueInfoT> class DenseSet;
79   class SmallBitVector;
80   struct InlineAsmIdentifierInfo;
81 }
82 
83 namespace clang {
84   class ADLResult;
85   class ASTConsumer;
86   class ASTContext;
87   class ASTMutationListener;
88   class ASTReader;
89   class ASTWriter;
90   class ArrayType;
91   class ParsedAttr;
92   class BindingDecl;
93   class BlockDecl;
94   class CapturedDecl;
95   class CXXBasePath;
96   class CXXBasePaths;
97   class CXXBindTemporaryExpr;
98   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
99   class CXXConstructorDecl;
100   class CXXConversionDecl;
101   class CXXDeleteExpr;
102   class CXXDestructorDecl;
103   class CXXFieldCollector;
104   class CXXMemberCallExpr;
105   class CXXMethodDecl;
106   class CXXScopeSpec;
107   class CXXTemporary;
108   class CXXTryStmt;
109   class CallExpr;
110   class ClassTemplateDecl;
111   class ClassTemplatePartialSpecializationDecl;
112   class ClassTemplateSpecializationDecl;
113   class VarTemplatePartialSpecializationDecl;
114   class CodeCompleteConsumer;
115   class CodeCompletionAllocator;
116   class CodeCompletionTUInfo;
117   class CodeCompletionResult;
118   class CoroutineBodyStmt;
119   class Decl;
120   class DeclAccessPair;
121   class DeclContext;
122   class DeclRefExpr;
123   class DeclaratorDecl;
124   class DeducedTemplateArgument;
125   class DependentDiagnostic;
126   class DesignatedInitExpr;
127   class Designation;
128   class EnableIfAttr;
129   class EnumConstantDecl;
130   class Expr;
131   class ExtVectorType;
132   class FormatAttr;
133   class FriendDecl;
134   class FunctionDecl;
135   class FunctionProtoType;
136   class FunctionTemplateDecl;
137   class ImplicitConversionSequence;
138   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
139   class InitListExpr;
140   class InitializationKind;
141   class InitializationSequence;
142   class InitializedEntity;
143   class IntegerLiteral;
144   class LabelStmt;
145   class LambdaExpr;
146   class LangOptions;
147   class LocalInstantiationScope;
148   class LookupResult;
149   class MacroInfo;
150   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
151   class ModuleLoader;
152   class MultiLevelTemplateArgumentList;
153   class NamedDecl;
154   class ObjCCategoryDecl;
155   class ObjCCategoryImplDecl;
156   class ObjCCompatibleAliasDecl;
157   class ObjCContainerDecl;
158   class ObjCImplDecl;
159   class ObjCImplementationDecl;
160   class ObjCInterfaceDecl;
161   class ObjCIvarDecl;
162   template <class T> class ObjCList;
163   class ObjCMessageExpr;
164   class ObjCMethodDecl;
165   class ObjCPropertyDecl;
166   class ObjCProtocolDecl;
167   class OMPThreadPrivateDecl;
168   class OMPRequiresDecl;
169   class OMPDeclareReductionDecl;
170   class OMPDeclareSimdDecl;
171   class OMPClause;
172   struct OMPVarListLocTy;
173   struct OverloadCandidate;
174   enum class OverloadCandidateParamOrder : char;
175   enum OverloadCandidateRewriteKind : unsigned;
176   class OverloadCandidateSet;
177   class OverloadExpr;
178   class ParenListExpr;
179   class ParmVarDecl;
180   class Preprocessor;
181   class PseudoDestructorTypeStorage;
182   class PseudoObjectExpr;
183   class QualType;
184   class StandardConversionSequence;
185   class Stmt;
186   class StringLiteral;
187   class SwitchStmt;
188   class TemplateArgument;
189   class TemplateArgumentList;
190   class TemplateArgumentLoc;
191   class TemplateDecl;
192   class TemplateInstantiationCallback;
193   class TemplateParameterList;
194   class TemplatePartialOrderingContext;
195   class TemplateTemplateParmDecl;
196   class Token;
197   class TypeAliasDecl;
198   class TypedefDecl;
199   class TypedefNameDecl;
200   class TypeLoc;
201   class TypoCorrectionConsumer;
202   class UnqualifiedId;
203   class UnresolvedLookupExpr;
204   class UnresolvedMemberExpr;
205   class UnresolvedSetImpl;
206   class UnresolvedSetIterator;
207   class UsingDecl;
208   class UsingShadowDecl;
209   class ValueDecl;
210   class VarDecl;
211   class VarTemplateSpecializationDecl;
212   class VisibilityAttr;
213   class VisibleDeclConsumer;
214   class IndirectFieldDecl;
215   struct DeductionFailureInfo;
216   class TemplateSpecCandidateSet;
217 
218 namespace sema {
219   class AccessedEntity;
220   class BlockScopeInfo;
221   class Capture;
222   class CapturedRegionScopeInfo;
223   class CapturingScopeInfo;
224   class CompoundScopeInfo;
225   class DelayedDiagnostic;
226   class DelayedDiagnosticPool;
227   class FunctionScopeInfo;
228   class LambdaScopeInfo;
229   class PossiblyUnreachableDiag;
230   class SemaPPCallbacks;
231   class TemplateDeductionInfo;
232 }
233 
234 namespace threadSafety {
235   class BeforeSet;
236   void threadSafetyCleanup(BeforeSet* Cache);
237 }
238 
239 // FIXME: No way to easily map from TemplateTypeParmTypes to
240 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
241 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
242                   SourceLocation> UnexpandedParameterPack;
243 
244 /// Describes whether we've seen any nullability information for the given
245 /// file.
246 struct FileNullability {
247   /// The first pointer declarator (of any pointer kind) in the file that does
248   /// not have a corresponding nullability annotation.
249   SourceLocation PointerLoc;
250 
251   /// The end location for the first pointer declarator in the file. Used for
252   /// placing fix-its.
253   SourceLocation PointerEndLoc;
254 
255   /// Which kind of pointer declarator we saw.
256   uint8_t PointerKind;
257 
258   /// Whether we saw any type nullability annotations in the given file.
259   bool SawTypeNullability = false;
260 };
261 
262 /// A mapping from file IDs to a record of whether we've seen nullability
263 /// information in that file.
264 class FileNullabilityMap {
265   /// A mapping from file IDs to the nullability information for each file ID.
266   llvm::DenseMap<FileID, FileNullability> Map;
267 
268   /// A single-element cache based on the file ID.
269   struct {
270     FileID File;
271     FileNullability Nullability;
272   } Cache;
273 
274 public:
275   FileNullability &operator[](FileID file) {
276     // Check the single-element cache.
277     if (file == Cache.File)
278       return Cache.Nullability;
279 
280     // It's not in the single-element cache; flush the cache if we have one.
281     if (!Cache.File.isInvalid()) {
282       Map[Cache.File] = Cache.Nullability;
283     }
284 
285     // Pull this entry into the cache.
286     Cache.File = file;
287     Cache.Nullability = Map[file];
288     return Cache.Nullability;
289   }
290 };
291 
292 /// Tracks expected type during expression parsing, for use in code completion.
293 /// The type is tied to a particular token, all functions that update or consume
294 /// the type take a start location of the token they are looking at as a
295 /// parameter. This avoids updating the type on hot paths in the parser.
296 class PreferredTypeBuilder {
297 public:
PreferredTypeBuilder(bool Enabled)298   PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
299 
300   void enterCondition(Sema &S, SourceLocation Tok);
301   void enterReturn(Sema &S, SourceLocation Tok);
302   void enterVariableInit(SourceLocation Tok, Decl *D);
303   /// Handles e.g. BaseType{ .D = Tok...
304   void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
305                                   const Designation &D);
306   /// Computing a type for the function argument may require running
307   /// overloading, so we postpone its computation until it is actually needed.
308   ///
309   /// Clients should be very careful when using this funciton, as it stores a
310   /// function_ref, clients should make sure all calls to get() with the same
311   /// location happen while function_ref is alive.
312   ///
313   /// The callback should also emit signature help as a side-effect, but only
314   /// if the completion point has been reached.
315   void enterFunctionArgument(SourceLocation Tok,
316                              llvm::function_ref<QualType()> ComputeType);
317 
318   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
319   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
320                   SourceLocation OpLoc);
321   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
322   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
323   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
324   /// Handles all type casts, including C-style cast, C++ casts, etc.
325   void enterTypeCast(SourceLocation Tok, QualType CastType);
326 
327   /// Get the expected type associated with this location, if any.
328   ///
329   /// If the location is a function argument, determining the expected type
330   /// involves considering all function overloads and the arguments so far.
331   /// In this case, signature help for these function overloads will be reported
332   /// as a side-effect (only if the completion point has been reached).
get(SourceLocation Tok)333   QualType get(SourceLocation Tok) const {
334     if (!Enabled || Tok != ExpectedLoc)
335       return QualType();
336     if (!Type.isNull())
337       return Type;
338     if (ComputeType)
339       return ComputeType();
340     return QualType();
341   }
342 
343 private:
344   bool Enabled;
345   /// Start position of a token for which we store expected type.
346   SourceLocation ExpectedLoc;
347   /// Expected type for a token starting at ExpectedLoc.
348   QualType Type;
349   /// A function to compute expected type at ExpectedLoc. It is only considered
350   /// if Type is null.
351   llvm::function_ref<QualType()> ComputeType;
352 };
353 
354 /// Sema - This implements semantic analysis and AST building for C.
355 class Sema final {
356   Sema(const Sema &) = delete;
357   void operator=(const Sema &) = delete;
358 
359   ///Source of additional semantic information.
360   ExternalSemaSource *ExternalSource;
361 
362   ///Whether Sema has generated a multiplexer and has to delete it.
363   bool isMultiplexExternalSource;
364 
365   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
366 
367   bool isVisibleSlow(const NamedDecl *D);
368 
369   /// Determine whether two declarations should be linked together, given that
370   /// the old declaration might not be visible and the new declaration might
371   /// not have external linkage.
shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)372   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
373                                     const NamedDecl *New) {
374     if (isVisible(Old))
375      return true;
376     // See comment in below overload for why it's safe to compute the linkage
377     // of the new declaration here.
378     if (New->isExternallyDeclarable()) {
379       assert(Old->isExternallyDeclarable() &&
380              "should not have found a non-externally-declarable previous decl");
381       return true;
382     }
383     return false;
384   }
385   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
386 
387   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
388                                       QualType ResultTy,
389                                       ArrayRef<QualType> Args);
390 
391 public:
392   /// The maximum alignment, same as in llvm::Value. We duplicate them here
393   /// because that allows us not to duplicate the constants in clang code,
394   /// which we must to since we can't directly use the llvm constants.
395   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
396   ///
397   /// This is the greatest alignment value supported by load, store, and alloca
398   /// instructions, and global values.
399   static const unsigned MaxAlignmentExponent = 29;
400   static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
401 
402   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
403   typedef OpaquePtr<TemplateName> TemplateTy;
404   typedef OpaquePtr<QualType> TypeTy;
405 
406   OpenCLOptions OpenCLFeatures;
407   FPOptions CurFPFeatures;
408 
409   const LangOptions &LangOpts;
410   Preprocessor &PP;
411   ASTContext &Context;
412   ASTConsumer &Consumer;
413   DiagnosticsEngine &Diags;
414   SourceManager &SourceMgr;
415 
416   /// Flag indicating whether or not to collect detailed statistics.
417   bool CollectStats;
418 
419   /// Code-completion consumer.
420   CodeCompleteConsumer *CodeCompleter;
421 
422   /// CurContext - This is the current declaration context of parsing.
423   DeclContext *CurContext;
424 
425   /// Generally null except when we temporarily switch decl contexts,
426   /// like in \see ActOnObjCTemporaryExitContainerContext.
427   DeclContext *OriginalLexicalContext;
428 
429   /// VAListTagName - The declaration name corresponding to __va_list_tag.
430   /// This is used as part of a hack to omit that class from ADL results.
431   DeclarationName VAListTagName;
432 
433   bool MSStructPragmaOn; // True when \#pragma ms_struct on
434 
435   /// Controls member pointer representation format under the MS ABI.
436   LangOptions::PragmaMSPointersToMembersKind
437       MSPointerToMemberRepresentationMethod;
438 
439   /// Stack of active SEH __finally scopes.  Can be empty.
440   SmallVector<Scope*, 2> CurrentSEHFinally;
441 
442   /// Source location for newly created implicit MSInheritanceAttrs
443   SourceLocation ImplicitMSInheritanceAttrLoc;
444 
445   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
446   /// `TransformTypos` in order to keep track of any TypoExprs that are created
447   /// recursively during typo correction and wipe them away if the correction
448   /// fails.
449   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
450 
451   /// pragma clang section kind
452   enum PragmaClangSectionKind {
453     PCSK_Invalid      = 0,
454     PCSK_BSS          = 1,
455     PCSK_Data         = 2,
456     PCSK_Rodata       = 3,
457     PCSK_Text         = 4,
458     PCSK_Relro        = 5
459    };
460 
461   enum PragmaClangSectionAction {
462     PCSA_Set     = 0,
463     PCSA_Clear   = 1
464   };
465 
466   struct PragmaClangSection {
467     std::string SectionName;
468     bool Valid = false;
469     SourceLocation PragmaLocation;
470   };
471 
472    PragmaClangSection PragmaClangBSSSection;
473    PragmaClangSection PragmaClangDataSection;
474    PragmaClangSection PragmaClangRodataSection;
475    PragmaClangSection PragmaClangRelroSection;
476    PragmaClangSection PragmaClangTextSection;
477 
478   enum PragmaMsStackAction {
479     PSK_Reset     = 0x0,                // #pragma ()
480     PSK_Set       = 0x1,                // #pragma (value)
481     PSK_Push      = 0x2,                // #pragma (push[, id])
482     PSK_Pop       = 0x4,                // #pragma (pop[, id])
483     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
484     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
485     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
486   };
487 
488   // #pragma pack and align.
489   class AlignPackInfo {
490   public:
491     // `Native` represents default align mode, which may vary based on the
492     // platform.
493     enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
494 
495     // #pragma pack info constructor
AlignPackInfo(AlignPackInfo::Mode M,unsigned Num,bool IsXL)496     AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
497         : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
498       assert(Num == PackNumber && "The pack number has been truncated.");
499     }
500 
501     // #pragma align info constructor
AlignPackInfo(AlignPackInfo::Mode M,bool IsXL)502     AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
503         : PackAttr(false), AlignMode(M),
504           PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
505 
AlignPackInfo(bool IsXL)506     explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
507 
AlignPackInfo()508     AlignPackInfo() : AlignPackInfo(Native, false) {}
509 
510     // When a AlignPackInfo itself cannot be used, this returns an 32-bit
511     // integer encoding for it. This should only be passed to
512     // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
getRawEncoding(const AlignPackInfo & Info)513     static uint32_t getRawEncoding(const AlignPackInfo &Info) {
514       std::uint32_t Encoding{};
515       if (Info.IsXLStack())
516         Encoding |= IsXLMask;
517 
518       Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
519 
520       if (Info.IsPackAttr())
521         Encoding |= PackAttrMask;
522 
523       Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
524 
525       return Encoding;
526     }
527 
getFromRawEncoding(unsigned Encoding)528     static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
529       bool IsXL = static_cast<bool>(Encoding & IsXLMask);
530       AlignPackInfo::Mode M =
531           static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
532       int PackNumber = (Encoding & PackNumMask) >> 4;
533 
534       if (Encoding & PackAttrMask)
535         return AlignPackInfo(M, PackNumber, IsXL);
536 
537       return AlignPackInfo(M, IsXL);
538     }
539 
IsPackAttr()540     bool IsPackAttr() const { return PackAttr; }
541 
IsAlignAttr()542     bool IsAlignAttr() const { return !PackAttr; }
543 
getAlignMode()544     Mode getAlignMode() const { return AlignMode; }
545 
getPackNumber()546     unsigned getPackNumber() const { return PackNumber; }
547 
IsPackSet()548     bool IsPackSet() const {
549       // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
550       // attriute on a decl.
551       return PackNumber != UninitPackVal && PackNumber != 0;
552     }
553 
IsXLStack()554     bool IsXLStack() const { return XLStack; }
555 
556     bool operator==(const AlignPackInfo &Info) const {
557       return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
558              std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
559                       Info.XLStack);
560     }
561 
562     bool operator!=(const AlignPackInfo &Info) const {
563       return !(*this == Info);
564     }
565 
566   private:
567     /// \brief True if this is a pragma pack attribute,
568     ///         not a pragma align attribute.
569     bool PackAttr;
570 
571     /// \brief The alignment mode that is in effect.
572     Mode AlignMode;
573 
574     /// \brief The pack number of the stack.
575     unsigned char PackNumber;
576 
577     /// \brief True if it is a XL #pragma align/pack stack.
578     bool XLStack;
579 
580     /// \brief Uninitialized pack value.
581     static constexpr unsigned char UninitPackVal = -1;
582 
583     // Masks to encode and decode an AlignPackInfo.
584     static constexpr uint32_t IsXLMask{0x0000'0001};
585     static constexpr uint32_t AlignModeMask{0x0000'0006};
586     static constexpr uint32_t PackAttrMask{0x00000'0008};
587     static constexpr uint32_t PackNumMask{0x0000'01F0};
588   };
589 
590   template<typename ValueType>
591   struct PragmaStack {
592     struct Slot {
593       llvm::StringRef StackSlotLabel;
594       ValueType Value;
595       SourceLocation PragmaLocation;
596       SourceLocation PragmaPushLocation;
SlotPragmaStack::Slot597       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
598            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
599           : StackSlotLabel(StackSlotLabel), Value(Value),
600             PragmaLocation(PragmaLocation),
601             PragmaPushLocation(PragmaPushLocation) {}
602     };
603 
ActPragmaStack604     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
605              llvm::StringRef StackSlotLabel, ValueType Value) {
606       if (Action == PSK_Reset) {
607         CurrentValue = DefaultValue;
608         CurrentPragmaLocation = PragmaLocation;
609         return;
610       }
611       if (Action & PSK_Push)
612         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
613                            PragmaLocation);
614       else if (Action & PSK_Pop) {
615         if (!StackSlotLabel.empty()) {
616           // If we've got a label, try to find it and jump there.
617           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
618             return x.StackSlotLabel == StackSlotLabel;
619           });
620           // If we found the label so pop from there.
621           if (I != Stack.rend()) {
622             CurrentValue = I->Value;
623             CurrentPragmaLocation = I->PragmaLocation;
624             Stack.erase(std::prev(I.base()), Stack.end());
625           }
626         } else if (!Stack.empty()) {
627           // We do not have a label, just pop the last entry.
628           CurrentValue = Stack.back().Value;
629           CurrentPragmaLocation = Stack.back().PragmaLocation;
630           Stack.pop_back();
631         }
632       }
633       if (Action & PSK_Set) {
634         CurrentValue = Value;
635         CurrentPragmaLocation = PragmaLocation;
636       }
637     }
638 
639     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
640     // method body to restore the stacks on exit, so it works like this:
641     //
642     //   struct S {
643     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
644     //     void Method {}
645     //     #pragma <name>(pop, InternalPragmaSlot)
646     //   };
647     //
648     // It works even with #pragma vtordisp, although MSVC doesn't support
649     //   #pragma vtordisp(push [, id], n)
650     // syntax.
651     //
652     // Push / pop a named sentinel slot.
SentinelActionPragmaStack653     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
654       assert((Action == PSK_Push || Action == PSK_Pop) &&
655              "Can only push / pop #pragma stack sentinels!");
656       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
657     }
658 
659     // Constructors.
PragmaStackPragmaStack660     explicit PragmaStack(const ValueType &Default)
661         : DefaultValue(Default), CurrentValue(Default) {}
662 
hasValuePragmaStack663     bool hasValue() const { return CurrentValue != DefaultValue; }
664 
665     SmallVector<Slot, 2> Stack;
666     ValueType DefaultValue; // Value used for PSK_Reset action.
667     ValueType CurrentValue;
668     SourceLocation CurrentPragmaLocation;
669   };
670   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
671   // we shouldn't do so if they're in a module).
672 
673   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
674   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
675   ///
676   /// 0: Suppress all vtordisps
677   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
678   ///    structors
679   /// 2: Always insert vtordisps to support RTTI on partially constructed
680   ///    objects
681   PragmaStack<MSVtorDispMode> VtorDispStack;
682   PragmaStack<AlignPackInfo> AlignPackStack;
683   // The current #pragma align/pack values and locations at each #include.
684   struct AlignPackIncludeState {
685     AlignPackInfo CurrentValue;
686     SourceLocation CurrentPragmaLocation;
687     bool HasNonDefaultValue, ShouldWarnOnInclude;
688   };
689   SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
690   // Segment #pragmas.
691   PragmaStack<StringLiteral *> DataSegStack;
692   PragmaStack<StringLiteral *> BSSSegStack;
693   PragmaStack<StringLiteral *> ConstSegStack;
694   PragmaStack<StringLiteral *> CodeSegStack;
695 
696   // This stack tracks the current state of Sema.CurFPFeatures.
697   PragmaStack<FPOptionsOverride> FpPragmaStack;
CurFPFeatureOverrides()698   FPOptionsOverride CurFPFeatureOverrides() {
699     FPOptionsOverride result;
700     if (!FpPragmaStack.hasValue()) {
701       result = FPOptionsOverride();
702     } else {
703       result = FpPragmaStack.CurrentValue;
704     }
705     return result;
706   }
707 
708   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
709   // Actions should be performed only if we enter / exit a C++ method body.
710   class PragmaStackSentinelRAII {
711   public:
712     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
713     ~PragmaStackSentinelRAII();
714 
715   private:
716     Sema &S;
717     StringRef SlotLabel;
718     bool ShouldAct;
719   };
720 
721   /// A mapping that describes the nullability we've seen in each header file.
722   FileNullabilityMap NullabilityMap;
723 
724   /// Last section used with #pragma init_seg.
725   StringLiteral *CurInitSeg;
726   SourceLocation CurInitSegLoc;
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   /// Flag indicating if Sema is building a recovery call expression.
760   ///
761   /// This flag is used to avoid building recovery call expressions
762   /// if Sema is already doing so, which would cause infinite recursions.
763   bool IsBuildingRecoveryCallExpr;
764 
765   /// Used to control the generation of ExprWithCleanups.
766   CleanupInfo Cleanup;
767 
768   /// ExprCleanupObjects - This is the stack of objects requiring
769   /// cleanup that are created by the current full expression.
770   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
771 
772   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
773   /// to a variable (constant) that may or may not be odr-used in this Expr, and
774   /// we won't know until all lvalue-to-rvalue and discarded value conversions
775   /// have been applied to all subexpressions of the enclosing full expression.
776   /// This is cleared at the end of each full expression.
777   using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
778                                              llvm::SmallPtrSet<Expr *, 4>>;
779   MaybeODRUseExprSet MaybeODRUseExprs;
780 
781   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
782 
783   /// Stack containing information about each of the nested
784   /// function, block, and method scopes that are currently active.
785   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
786 
787   /// The index of the first FunctionScope that corresponds to the current
788   /// context.
789   unsigned FunctionScopesStart = 0;
790 
getFunctionScopes()791   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
792     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
793                               FunctionScopes.end());
794   }
795 
796   /// Stack containing information needed when in C++2a an 'auto' is encountered
797   /// in a function declaration parameter type specifier in order to invent a
798   /// corresponding template parameter in the enclosing abbreviated function
799   /// template. This information is also present in LambdaScopeInfo, stored in
800   /// the FunctionScopes stack.
801   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
802 
803   /// The index of the first InventedParameterInfo that refers to the current
804   /// context.
805   unsigned InventedParameterInfosStart = 0;
806 
getInventedParameterInfos()807   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
808     return llvm::makeArrayRef(InventedParameterInfos.begin() +
809                                   InventedParameterInfosStart,
810                               InventedParameterInfos.end());
811   }
812 
813   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
814                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
815     ExtVectorDeclsType;
816 
817   /// ExtVectorDecls - This is a list all the extended vector types. This allows
818   /// us to associate a raw vector type with one of the ext_vector type names.
819   /// This is only necessary for issuing pretty diagnostics.
820   ExtVectorDeclsType ExtVectorDecls;
821 
822   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
823   std::unique_ptr<CXXFieldCollector> FieldCollector;
824 
825   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
826 
827   /// Set containing all declared private fields that are not used.
828   NamedDeclSetType UnusedPrivateFields;
829 
830   /// Set containing all typedefs that are likely unused.
831   llvm::SmallSetVector<const TypedefNameDecl *, 4>
832       UnusedLocalTypedefNameCandidates;
833 
834   /// Delete-expressions to be analyzed at the end of translation unit
835   ///
836   /// This list contains class members, and locations of delete-expressions
837   /// that could not be proven as to whether they mismatch with new-expression
838   /// used in initializer of the field.
839   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
840   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
841   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
842 
843   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
844 
845   /// PureVirtualClassDiagSet - a set of class declarations which we have
846   /// emitted a list of pure virtual functions. Used to prevent emitting the
847   /// same list more than once.
848   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
849 
850   /// ParsingInitForAutoVars - a set of declarations with auto types for which
851   /// we are currently parsing the initializer.
852   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
853 
854   /// Look for a locally scoped extern "C" declaration by the given name.
855   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
856 
857   typedef LazyVector<VarDecl *, ExternalSemaSource,
858                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
859     TentativeDefinitionsType;
860 
861   /// All the tentative definitions encountered in the TU.
862   TentativeDefinitionsType TentativeDefinitions;
863 
864   /// All the external declarations encoutered and used in the TU.
865   SmallVector<VarDecl *, 4> ExternalDeclarations;
866 
867   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
868                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
869     UnusedFileScopedDeclsType;
870 
871   /// The set of file scoped decls seen so far that have not been used
872   /// and must warn if not used. Only contains the first declaration.
873   UnusedFileScopedDeclsType UnusedFileScopedDecls;
874 
875   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
876                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
877     DelegatingCtorDeclsType;
878 
879   /// All the delegating constructors seen so far in the file, used for
880   /// cycle detection at the end of the TU.
881   DelegatingCtorDeclsType DelegatingCtorDecls;
882 
883   /// All the overriding functions seen during a class definition
884   /// that had their exception spec checks delayed, plus the overridden
885   /// function.
886   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
887     DelayedOverridingExceptionSpecChecks;
888 
889   /// All the function redeclarations seen during a class definition that had
890   /// their exception spec checks delayed, plus the prior declaration they
891   /// should be checked against. Except during error recovery, the new decl
892   /// should always be a friend declaration, as that's the only valid way to
893   /// redeclare a special member before its class is complete.
894   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
895     DelayedEquivalentExceptionSpecChecks;
896 
897   typedef llvm::MapVector<const FunctionDecl *,
898                           std::unique_ptr<LateParsedTemplate>>
899       LateParsedTemplateMapT;
900   LateParsedTemplateMapT LateParsedTemplateMap;
901 
902   /// Callback to the parser to parse templated functions when needed.
903   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
904   typedef void LateTemplateParserCleanupCB(void *P);
905   LateTemplateParserCB *LateTemplateParser;
906   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
907   void *OpaqueParser;
908 
SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)909   void SetLateTemplateParser(LateTemplateParserCB *LTP,
910                              LateTemplateParserCleanupCB *LTPCleanup,
911                              void *P) {
912     LateTemplateParser = LTP;
913     LateTemplateParserCleanup = LTPCleanup;
914     OpaqueParser = P;
915   }
916 
917   // Does the work necessary to deal with a SYCL kernel lambda. At the moment,
918   // this just marks the list of lambdas required to name the kernel.
919   void AddSYCLKernelLambda(const FunctionDecl *FD);
920 
921   class DelayedDiagnostics;
922 
923   class DelayedDiagnosticsState {
924     sema::DelayedDiagnosticPool *SavedPool;
925     friend class Sema::DelayedDiagnostics;
926   };
927   typedef DelayedDiagnosticsState ParsingDeclState;
928   typedef DelayedDiagnosticsState ProcessingContextState;
929 
930   /// A class which encapsulates the logic for delaying diagnostics
931   /// during parsing and other processing.
932   class DelayedDiagnostics {
933     /// The current pool of diagnostics into which delayed
934     /// diagnostics should go.
935     sema::DelayedDiagnosticPool *CurPool;
936 
937   public:
DelayedDiagnostics()938     DelayedDiagnostics() : CurPool(nullptr) {}
939 
940     /// Adds a delayed diagnostic.
941     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
942 
943     /// Determines whether diagnostics should be delayed.
shouldDelayDiagnostics()944     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
945 
946     /// Returns the current delayed-diagnostics pool.
getCurrentPool()947     sema::DelayedDiagnosticPool *getCurrentPool() const {
948       return CurPool;
949     }
950 
951     /// Enter a new scope.  Access and deprecation diagnostics will be
952     /// collected in this pool.
push(sema::DelayedDiagnosticPool & pool)953     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
954       DelayedDiagnosticsState state;
955       state.SavedPool = CurPool;
956       CurPool = &pool;
957       return state;
958     }
959 
960     /// Leave a delayed-diagnostic state that was previously pushed.
961     /// Do not emit any of the diagnostics.  This is performed as part
962     /// of the bookkeeping of popping a pool "properly".
popWithoutEmitting(DelayedDiagnosticsState state)963     void popWithoutEmitting(DelayedDiagnosticsState state) {
964       CurPool = state.SavedPool;
965     }
966 
967     /// Enter a new scope where access and deprecation diagnostics are
968     /// not delayed.
pushUndelayed()969     DelayedDiagnosticsState pushUndelayed() {
970       DelayedDiagnosticsState state;
971       state.SavedPool = CurPool;
972       CurPool = nullptr;
973       return state;
974     }
975 
976     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)977     void popUndelayed(DelayedDiagnosticsState state) {
978       assert(CurPool == nullptr);
979       CurPool = state.SavedPool;
980     }
981   } DelayedDiagnostics;
982 
983   /// A RAII object to temporarily push a declaration context.
984   class ContextRAII {
985   private:
986     Sema &S;
987     DeclContext *SavedContext;
988     ProcessingContextState SavedContextState;
989     QualType SavedCXXThisTypeOverride;
990     unsigned SavedFunctionScopesStart;
991     unsigned SavedInventedParameterInfosStart;
992 
993   public:
994     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
S(S)995       : S(S), SavedContext(S.CurContext),
996         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
997         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
998         SavedFunctionScopesStart(S.FunctionScopesStart),
999         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1000     {
1001       assert(ContextToPush && "pushing null context");
1002       S.CurContext = ContextToPush;
1003       if (NewThisContext)
1004         S.CXXThisTypeOverride = QualType();
1005       // Any saved FunctionScopes do not refer to this context.
1006       S.FunctionScopesStart = S.FunctionScopes.size();
1007       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1008     }
1009 
pop()1010     void pop() {
1011       if (!SavedContext) return;
1012       S.CurContext = SavedContext;
1013       S.DelayedDiagnostics.popUndelayed(SavedContextState);
1014       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1015       S.FunctionScopesStart = SavedFunctionScopesStart;
1016       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1017       SavedContext = nullptr;
1018     }
1019 
~ContextRAII()1020     ~ContextRAII() {
1021       pop();
1022     }
1023   };
1024 
1025   /// Whether the AST is currently being rebuilt to correct immediate
1026   /// invocations. Immediate invocation candidates and references to consteval
1027   /// functions aren't tracked when this is set.
1028   bool RebuildingImmediateInvocation = false;
1029 
1030   /// Used to change context to isConstantEvaluated without pushing a heavy
1031   /// ExpressionEvaluationContextRecord object.
1032   bool isConstantEvaluatedOverride;
1033 
isConstantEvaluated()1034   bool isConstantEvaluated() {
1035     return ExprEvalContexts.back().isConstantEvaluated() ||
1036            isConstantEvaluatedOverride;
1037   }
1038 
1039   /// RAII object to handle the state changes required to synthesize
1040   /// a function body.
1041   class SynthesizedFunctionScope {
1042     Sema &S;
1043     Sema::ContextRAII SavedContext;
1044     bool PushedCodeSynthesisContext = false;
1045 
1046   public:
SynthesizedFunctionScope(Sema & S,DeclContext * DC)1047     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1048         : S(S), SavedContext(S, DC) {
1049       S.PushFunctionScope();
1050       S.PushExpressionEvaluationContext(
1051           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1052       if (auto *FD = dyn_cast<FunctionDecl>(DC))
1053         FD->setWillHaveBody(true);
1054       else
1055         assert(isa<ObjCMethodDecl>(DC));
1056     }
1057 
addContextNote(SourceLocation UseLoc)1058     void addContextNote(SourceLocation UseLoc) {
1059       assert(!PushedCodeSynthesisContext);
1060 
1061       Sema::CodeSynthesisContext Ctx;
1062       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1063       Ctx.PointOfInstantiation = UseLoc;
1064       Ctx.Entity = cast<Decl>(S.CurContext);
1065       S.pushCodeSynthesisContext(Ctx);
1066 
1067       PushedCodeSynthesisContext = true;
1068     }
1069 
~SynthesizedFunctionScope()1070     ~SynthesizedFunctionScope() {
1071       if (PushedCodeSynthesisContext)
1072         S.popCodeSynthesisContext();
1073       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1074         FD->setWillHaveBody(false);
1075       S.PopExpressionEvaluationContext();
1076       S.PopFunctionScopeInfo();
1077     }
1078   };
1079 
1080   /// WeakUndeclaredIdentifiers - Identifiers contained in
1081   /// \#pragma weak before declared. rare. may alias another
1082   /// identifier, declared or undeclared
1083   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
1084 
1085   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1086   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
1087   /// to define functions that occur in multiple standards to call the version
1088   /// in the currently selected standard.
1089   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1090 
1091 
1092   /// Load weak undeclared identifiers from the external source.
1093   void LoadExternalWeakUndeclaredIdentifiers();
1094 
1095   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1096   /// \#pragma weak during processing of other Decls.
1097   /// I couldn't figure out a clean way to generate these in-line, so
1098   /// we store them here and handle separately -- which is a hack.
1099   /// It would be best to refactor this.
1100   SmallVector<Decl*,2> WeakTopLevelDecl;
1101 
1102   IdentifierResolver IdResolver;
1103 
1104   /// Translation Unit Scope - useful to Objective-C actions that need
1105   /// to lookup file scope declarations in the "ordinary" C decl namespace.
1106   /// For example, user-defined classes, built-in "id" type, etc.
1107   Scope *TUScope;
1108 
1109   /// The C++ "std" namespace, where the standard library resides.
1110   LazyDeclPtr StdNamespace;
1111 
1112   /// The C++ "std::bad_alloc" class, which is defined by the C++
1113   /// standard library.
1114   LazyDeclPtr StdBadAlloc;
1115 
1116   /// The C++ "std::align_val_t" enum class, which is defined by the C++
1117   /// standard library.
1118   LazyDeclPtr StdAlignValT;
1119 
1120   /// The C++ "std::experimental" namespace, where the experimental parts
1121   /// of the standard library resides.
1122   NamespaceDecl *StdExperimentalNamespaceCache;
1123 
1124   /// The C++ "std::initializer_list" template, which is defined in
1125   /// \<initializer_list>.
1126   ClassTemplateDecl *StdInitializerList;
1127 
1128   /// The C++ "std::coroutine_traits" template, which is defined in
1129   /// \<coroutine_traits>
1130   ClassTemplateDecl *StdCoroutineTraitsCache;
1131 
1132   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1133   RecordDecl *CXXTypeInfoDecl;
1134 
1135   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1136   RecordDecl *MSVCGuidDecl;
1137 
1138   /// Caches identifiers/selectors for NSFoundation APIs.
1139   std::unique_ptr<NSAPI> NSAPIObj;
1140 
1141   /// The declaration of the Objective-C NSNumber class.
1142   ObjCInterfaceDecl *NSNumberDecl;
1143 
1144   /// The declaration of the Objective-C NSValue class.
1145   ObjCInterfaceDecl *NSValueDecl;
1146 
1147   /// Pointer to NSNumber type (NSNumber *).
1148   QualType NSNumberPointer;
1149 
1150   /// Pointer to NSValue type (NSValue *).
1151   QualType NSValuePointer;
1152 
1153   /// The Objective-C NSNumber methods used to create NSNumber literals.
1154   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1155 
1156   /// The declaration of the Objective-C NSString class.
1157   ObjCInterfaceDecl *NSStringDecl;
1158 
1159   /// Pointer to NSString type (NSString *).
1160   QualType NSStringPointer;
1161 
1162   /// The declaration of the stringWithUTF8String: method.
1163   ObjCMethodDecl *StringWithUTF8StringMethod;
1164 
1165   /// The declaration of the valueWithBytes:objCType: method.
1166   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1167 
1168   /// The declaration of the Objective-C NSArray class.
1169   ObjCInterfaceDecl *NSArrayDecl;
1170 
1171   /// The declaration of the arrayWithObjects:count: method.
1172   ObjCMethodDecl *ArrayWithObjectsMethod;
1173 
1174   /// The declaration of the Objective-C NSDictionary class.
1175   ObjCInterfaceDecl *NSDictionaryDecl;
1176 
1177   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1178   ObjCMethodDecl *DictionaryWithObjectsMethod;
1179 
1180   /// id<NSCopying> type.
1181   QualType QIDNSCopying;
1182 
1183   /// will hold 'respondsToSelector:'
1184   Selector RespondsToSelectorSel;
1185 
1186   /// A flag to remember whether the implicit forms of operator new and delete
1187   /// have been declared.
1188   bool GlobalNewDeleteDeclared;
1189 
1190   /// Describes how the expressions currently being parsed are
1191   /// evaluated at run-time, if at all.
1192   enum class ExpressionEvaluationContext {
1193     /// The current expression and its subexpressions occur within an
1194     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1195     /// \c sizeof, where the type of the expression may be significant but
1196     /// no code will be generated to evaluate the value of the expression at
1197     /// run time.
1198     Unevaluated,
1199 
1200     /// The current expression occurs within a braced-init-list within
1201     /// an unevaluated operand. This is mostly like a regular unevaluated
1202     /// context, except that we still instantiate constexpr functions that are
1203     /// referenced here so that we can perform narrowing checks correctly.
1204     UnevaluatedList,
1205 
1206     /// The current expression occurs within a discarded statement.
1207     /// This behaves largely similarly to an unevaluated operand in preventing
1208     /// definitions from being required, but not in other ways.
1209     DiscardedStatement,
1210 
1211     /// The current expression occurs within an unevaluated
1212     /// operand that unconditionally permits abstract references to
1213     /// fields, such as a SIZE operator in MS-style inline assembly.
1214     UnevaluatedAbstract,
1215 
1216     /// The current context is "potentially evaluated" in C++11 terms,
1217     /// but the expression is evaluated at compile-time (like the values of
1218     /// cases in a switch statement).
1219     ConstantEvaluated,
1220 
1221     /// The current expression is potentially evaluated at run time,
1222     /// which means that code may be generated to evaluate the value of the
1223     /// expression at run time.
1224     PotentiallyEvaluated,
1225 
1226     /// The current expression is potentially evaluated, but any
1227     /// declarations referenced inside that expression are only used if
1228     /// in fact the current expression is used.
1229     ///
1230     /// This value is used when parsing default function arguments, for which
1231     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1232     /// through varargs) but do not want to mark declarations as "referenced"
1233     /// until the default argument is used.
1234     PotentiallyEvaluatedIfUsed
1235   };
1236 
1237   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1238 
1239   /// Data structure used to record current or nested
1240   /// expression evaluation contexts.
1241   struct ExpressionEvaluationContextRecord {
1242     /// The expression evaluation context.
1243     ExpressionEvaluationContext Context;
1244 
1245     /// Whether the enclosing context needed a cleanup.
1246     CleanupInfo ParentCleanup;
1247 
1248     /// The number of active cleanup objects when we entered
1249     /// this expression evaluation context.
1250     unsigned NumCleanupObjects;
1251 
1252     /// The number of typos encountered during this expression evaluation
1253     /// context (i.e. the number of TypoExprs created).
1254     unsigned NumTypos;
1255 
1256     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1257 
1258     /// The lambdas that are present within this context, if it
1259     /// is indeed an unevaluated context.
1260     SmallVector<LambdaExpr *, 2> Lambdas;
1261 
1262     /// The declaration that provides context for lambda expressions
1263     /// and block literals if the normal declaration context does not
1264     /// suffice, e.g., in a default function argument.
1265     Decl *ManglingContextDecl;
1266 
1267     /// If we are processing a decltype type, a set of call expressions
1268     /// for which we have deferred checking the completeness of the return type.
1269     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1270 
1271     /// If we are processing a decltype type, a set of temporary binding
1272     /// expressions for which we have deferred checking the destructor.
1273     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1274 
1275     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1276 
1277     /// Expressions appearing as the LHS of a volatile assignment in this
1278     /// context. We produce a warning for these when popping the context if
1279     /// they are not discarded-value expressions nor unevaluated operands.
1280     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1281 
1282     /// Set of candidates for starting an immediate invocation.
1283     llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1284 
1285     /// Set of DeclRefExprs referencing a consteval function when used in a
1286     /// context not already known to be immediately invoked.
1287     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1288 
1289     /// \brief Describes whether we are in an expression constext which we have
1290     /// to handle differently.
1291     enum ExpressionKind {
1292       EK_Decltype, EK_TemplateArgument, EK_Other
1293     } ExprContext;
1294 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1295     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1296                                       unsigned NumCleanupObjects,
1297                                       CleanupInfo ParentCleanup,
1298                                       Decl *ManglingContextDecl,
1299                                       ExpressionKind ExprContext)
1300         : Context(Context), ParentCleanup(ParentCleanup),
1301           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1302           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1303 
isUnevaluatedExpressionEvaluationContextRecord1304     bool isUnevaluated() const {
1305       return Context == ExpressionEvaluationContext::Unevaluated ||
1306              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1307              Context == ExpressionEvaluationContext::UnevaluatedList;
1308     }
isConstantEvaluatedExpressionEvaluationContextRecord1309     bool isConstantEvaluated() const {
1310       return Context == ExpressionEvaluationContext::ConstantEvaluated;
1311     }
1312   };
1313 
1314   /// A stack of expression evaluation contexts.
1315   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1316 
1317   // Set of failed immediate invocations to avoid double diagnosing.
1318   llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
1319 
1320   /// Emit a warning for all pending noderef expressions that we recorded.
1321   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1322 
1323   /// Compute the mangling number context for a lambda expression or
1324   /// block literal. Also return the extra mangling decl if any.
1325   ///
1326   /// \param DC - The DeclContext containing the lambda expression or
1327   /// block literal.
1328   std::tuple<MangleNumberingContext *, Decl *>
1329   getCurrentMangleNumberContext(const DeclContext *DC);
1330 
1331 
1332   /// SpecialMemberOverloadResult - The overloading result for a special member
1333   /// function.
1334   ///
1335   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1336   /// integer are used to determine whether overload resolution succeeded.
1337   class SpecialMemberOverloadResult {
1338   public:
1339     enum Kind {
1340       NoMemberOrDeleted,
1341       Ambiguous,
1342       Success
1343     };
1344 
1345   private:
1346     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1347 
1348   public:
SpecialMemberOverloadResult()1349     SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl * MD)1350     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1351         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1352 
getMethod()1353     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)1354     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1355 
getKind()1356     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)1357     void setKind(Kind K) { Pair.setInt(K); }
1358   };
1359 
1360   class SpecialMemberOverloadResultEntry
1361       : public llvm::FastFoldingSetNode,
1362         public SpecialMemberOverloadResult {
1363   public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1364     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1365       : FastFoldingSetNode(ID)
1366     {}
1367   };
1368 
1369   /// A cache of special member function overload resolution results
1370   /// for C++ records.
1371   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1372 
1373   /// A cache of the flags available in enumerations with the flag_bits
1374   /// attribute.
1375   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1376 
1377   /// The kind of translation unit we are processing.
1378   ///
1379   /// When we're processing a complete translation unit, Sema will perform
1380   /// end-of-translation-unit semantic tasks (such as creating
1381   /// initializers for tentative definitions in C) once parsing has
1382   /// completed. Modules and precompiled headers perform different kinds of
1383   /// checks.
1384   const TranslationUnitKind TUKind;
1385 
1386   llvm::BumpPtrAllocator BumpAlloc;
1387 
1388   /// The number of SFINAE diagnostics that have been trapped.
1389   unsigned NumSFINAEErrors;
1390 
1391   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1392     UnparsedDefaultArgInstantiationsMap;
1393 
1394   /// A mapping from parameters with unparsed default arguments to the
1395   /// set of instantiations of each parameter.
1396   ///
1397   /// This mapping is a temporary data structure used when parsing
1398   /// nested class templates or nested classes of class templates,
1399   /// where we might end up instantiating an inner class before the
1400   /// default arguments of its methods have been parsed.
1401   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1402 
1403   // Contains the locations of the beginning of unparsed default
1404   // argument locations.
1405   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1406 
1407   /// UndefinedInternals - all the used, undefined objects which require a
1408   /// definition in this translation unit.
1409   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1410 
1411   /// Determine if VD, which must be a variable or function, is an external
1412   /// symbol that nonetheless can't be referenced from outside this translation
1413   /// unit because its type has no linkage and it's not extern "C".
1414   bool isExternalWithNoLinkageType(ValueDecl *VD);
1415 
1416   /// Obtain a sorted list of functions that are undefined but ODR-used.
1417   void getUndefinedButUsed(
1418       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1419 
1420   /// Retrieves list of suspicious delete-expressions that will be checked at
1421   /// the end of translation unit.
1422   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1423   getMismatchingDeleteExpressions() const;
1424 
1425   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1426   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1427 
1428   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1429   /// We need to maintain a list, since selectors can have differing signatures
1430   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1431   /// of selectors are "overloaded").
1432   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1433   /// methods inside categories with a particular selector.
1434   GlobalMethodPool MethodPool;
1435 
1436   /// Method selectors used in a \@selector expression. Used for implementation
1437   /// of -Wselector.
1438   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1439 
1440   /// List of SourceLocations where 'self' is implicitly retained inside a
1441   /// block.
1442   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1443       ImplicitlyRetainedSelfLocs;
1444 
1445   /// Kinds of C++ special members.
1446   enum CXXSpecialMember {
1447     CXXDefaultConstructor,
1448     CXXCopyConstructor,
1449     CXXMoveConstructor,
1450     CXXCopyAssignment,
1451     CXXMoveAssignment,
1452     CXXDestructor,
1453     CXXInvalid
1454   };
1455 
1456   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1457       SpecialMemberDecl;
1458 
1459   /// The C++ special members which we are currently in the process of
1460   /// declaring. If this process recursively triggers the declaration of the
1461   /// same special member, we should act as if it is not yet declared.
1462   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1463 
1464   /// Kinds of defaulted comparison operator functions.
1465   enum class DefaultedComparisonKind : unsigned char {
1466     /// This is not a defaultable comparison operator.
1467     None,
1468     /// This is an operator== that should be implemented as a series of
1469     /// subobject comparisons.
1470     Equal,
1471     /// This is an operator<=> that should be implemented as a series of
1472     /// subobject comparisons.
1473     ThreeWay,
1474     /// This is an operator!= that should be implemented as a rewrite in terms
1475     /// of a == comparison.
1476     NotEqual,
1477     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1478     /// terms of a <=> comparison.
1479     Relational,
1480   };
1481 
1482   /// The function definitions which were renamed as part of typo-correction
1483   /// to match their respective declarations. We want to keep track of them
1484   /// to ensure that we don't emit a "redefinition" error if we encounter a
1485   /// correctly named definition after the renamed definition.
1486   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1487 
1488   /// Stack of types that correspond to the parameter entities that are
1489   /// currently being copy-initialized. Can be empty.
1490   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1491 
1492   void ReadMethodPool(Selector Sel);
1493   void updateOutOfDateSelector(Selector Sel);
1494 
1495   /// Private Helper predicate to check for 'self'.
1496   bool isSelfExpr(Expr *RExpr);
1497   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1498 
1499   /// Cause the active diagnostic on the DiagosticsEngine to be
1500   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1501   /// should not be used elsewhere.
1502   void EmitCurrentDiagnostic(unsigned DiagID);
1503 
1504   /// Records and restores the CurFPFeatures state on entry/exit of compound
1505   /// statements.
1506   class FPFeaturesStateRAII {
1507   public:
FPFeaturesStateRAII(Sema & S)1508     FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1509       OldOverrides = S.FpPragmaStack.CurrentValue;
1510     }
~FPFeaturesStateRAII()1511     ~FPFeaturesStateRAII() {
1512       S.CurFPFeatures = OldFPFeaturesState;
1513       S.FpPragmaStack.CurrentValue = OldOverrides;
1514     }
getOverrides()1515     FPOptionsOverride getOverrides() { return OldOverrides; }
1516 
1517   private:
1518     Sema& S;
1519     FPOptions OldFPFeaturesState;
1520     FPOptionsOverride OldOverrides;
1521   };
1522 
1523   void addImplicitTypedef(StringRef Name, QualType T);
1524 
1525   bool WarnedStackExhausted = false;
1526 
1527   /// Increment when we find a reference; decrement when we find an ignored
1528   /// assignment.  Ultimately the value is 0 if every reference is an ignored
1529   /// assignment.
1530   llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1531 
1532   Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1533 
1534 public:
1535   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1536        TranslationUnitKind TUKind = TU_Complete,
1537        CodeCompleteConsumer *CompletionConsumer = nullptr);
1538   ~Sema();
1539 
1540   /// Perform initialization that occurs after the parser has been
1541   /// initialized but before it parses anything.
1542   void Initialize();
1543 
1544   /// This virtual key function only exists to limit the emission of debug info
1545   /// describing the Sema class. GCC and Clang only emit debug info for a class
1546   /// with a vtable when the vtable is emitted. Sema is final and not
1547   /// polymorphic, but the debug info size savings are so significant that it is
1548   /// worth adding a vtable just to take advantage of this optimization.
1549   virtual void anchor();
1550 
getLangOpts()1551   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()1552   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getCurFPFeatures()1553   FPOptions     &getCurFPFeatures() { return CurFPFeatures; }
1554 
getDiagnostics()1555   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()1556   SourceManager &getSourceManager() const { return SourceMgr; }
getPreprocessor()1557   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()1558   ASTContext &getASTContext() const { return Context; }
getASTConsumer()1559   ASTConsumer &getASTConsumer() const { return Consumer; }
1560   ASTMutationListener *getASTMutationListener() const;
getExternalSource()1561   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1562   DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1563                                                          StringRef Platform);
1564 
1565   ///Registers an external source. If an external source already exists,
1566   /// creates a multiplex external source and appends to it.
1567   ///
1568   ///\param[in] E - A non-null external sema source.
1569   ///
1570   void addExternalSource(ExternalSemaSource *E);
1571 
1572   void PrintStats() const;
1573 
1574   /// Warn that the stack is nearly exhausted.
1575   void warnStackExhausted(SourceLocation Loc);
1576 
1577   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1578   /// guaranteed). Produces a warning if we're low on stack space and allocates
1579   /// more in that case. Use this in code that may recurse deeply (for example,
1580   /// in template instantiation) to avoid stack overflow.
1581   void runWithSufficientStackSpace(SourceLocation Loc,
1582                                    llvm::function_ref<void()> Fn);
1583 
1584   /// Helper class that creates diagnostics with optional
1585   /// template instantiation stacks.
1586   ///
1587   /// This class provides a wrapper around the basic DiagnosticBuilder
1588   /// class that emits diagnostics. ImmediateDiagBuilder is
1589   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1590   /// does) and, if the diagnostic comes from inside a template
1591   /// instantiation, printing the template instantiation stack as
1592   /// well.
1593   class ImmediateDiagBuilder : public DiagnosticBuilder {
1594     Sema &SemaRef;
1595     unsigned DiagID;
1596 
1597   public:
ImmediateDiagBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1598     ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1599         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
ImmediateDiagBuilder(DiagnosticBuilder && DB,Sema & SemaRef,unsigned DiagID)1600     ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1601         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1602 
1603     // This is a cunning lie. DiagnosticBuilder actually performs move
1604     // construction in its copy constructor (but due to varied uses, it's not
1605     // possible to conveniently express this as actual move construction). So
1606     // the default copy ctor here is fine, because the base class disables the
1607     // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1608     // in that case anwyay.
1609     ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1610 
~ImmediateDiagBuilder()1611     ~ImmediateDiagBuilder() {
1612       // If we aren't active, there is nothing to do.
1613       if (!isActive()) return;
1614 
1615       // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1616       // builder itself so it won't emit the diagnostic in its own destructor.
1617       //
1618       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1619       // do its own needless checks to see if the diagnostic needs to be
1620       // emitted. However, because we take care to ensure that the builder
1621       // objects never escape, a sufficiently smart compiler will be able to
1622       // eliminate that code.
1623       Clear();
1624 
1625       // Dispatch to Sema to emit the diagnostic.
1626       SemaRef.EmitCurrentDiagnostic(DiagID);
1627     }
1628 
1629     /// Teach operator<< to produce an object of the correct type.
1630     template <typename T>
1631     friend const ImmediateDiagBuilder &
1632     operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1633       const DiagnosticBuilder &BaseDiag = Diag;
1634       BaseDiag << Value;
1635       return Diag;
1636     }
1637 
1638     // It is necessary to limit this to rvalue reference to avoid calling this
1639     // function with a bitfield lvalue argument since non-const reference to
1640     // bitfield is not allowed.
1641     template <typename T, typename = typename std::enable_if<
1642                               !std::is_lvalue_reference<T>::value>::type>
1643     const ImmediateDiagBuilder &operator<<(T &&V) const {
1644       const DiagnosticBuilder &BaseDiag = *this;
1645       BaseDiag << std::move(V);
1646       return *this;
1647     }
1648   };
1649 
1650   /// A generic diagnostic builder for errors which may or may not be deferred.
1651   ///
1652   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1653   /// which are not allowed to appear inside __device__ functions and are
1654   /// allowed to appear in __host__ __device__ functions only if the host+device
1655   /// function is never codegen'ed.
1656   ///
1657   /// To handle this, we use the notion of "deferred diagnostics", where we
1658   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1659   ///
1660   /// This class lets you emit either a regular diagnostic, a deferred
1661   /// diagnostic, or no diagnostic at all, according to an argument you pass to
1662   /// its constructor, thus simplifying the process of creating these "maybe
1663   /// deferred" diagnostics.
1664   class SemaDiagnosticBuilder {
1665   public:
1666     enum Kind {
1667       /// Emit no diagnostics.
1668       K_Nop,
1669       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1670       K_Immediate,
1671       /// Emit the diagnostic immediately, and, if it's a warning or error, also
1672       /// emit a call stack showing how this function can be reached by an a
1673       /// priori known-emitted function.
1674       K_ImmediateWithCallStack,
1675       /// Create a deferred diagnostic, which is emitted only if the function
1676       /// it's attached to is codegen'ed.  Also emit a call stack as with
1677       /// K_ImmediateWithCallStack.
1678       K_Deferred
1679     };
1680 
1681     SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1682                           FunctionDecl *Fn, Sema &S);
1683     SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1684     SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1685     ~SemaDiagnosticBuilder();
1686 
isImmediate()1687     bool isImmediate() const { return ImmediateDiag.hasValue(); }
1688 
1689     /// Convertible to bool: True if we immediately emitted an error, false if
1690     /// we didn't emit an error or we created a deferred error.
1691     ///
1692     /// Example usage:
1693     ///
1694     ///   if (SemaDiagnosticBuilder(...) << foo << bar)
1695     ///     return ExprError();
1696     ///
1697     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1698     /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1699     operator bool() const { return isImmediate(); }
1700 
1701     template <typename T>
1702     friend const SemaDiagnosticBuilder &
1703     operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1704       if (Diag.ImmediateDiag.hasValue())
1705         *Diag.ImmediateDiag << Value;
1706       else if (Diag.PartialDiagId.hasValue())
1707         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1708             << Value;
1709       return Diag;
1710     }
1711 
1712     // It is necessary to limit this to rvalue reference to avoid calling this
1713     // function with a bitfield lvalue argument since non-const reference to
1714     // bitfield is not allowed.
1715     template <typename T, typename = typename std::enable_if<
1716                               !std::is_lvalue_reference<T>::value>::type>
1717     const SemaDiagnosticBuilder &operator<<(T &&V) const {
1718       if (ImmediateDiag.hasValue())
1719         *ImmediateDiag << std::move(V);
1720       else if (PartialDiagId.hasValue())
1721         S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1722       return *this;
1723     }
1724 
1725     friend const SemaDiagnosticBuilder &
1726     operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1727       if (Diag.ImmediateDiag.hasValue())
1728         PD.Emit(*Diag.ImmediateDiag);
1729       else if (Diag.PartialDiagId.hasValue())
1730         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1731       return Diag;
1732     }
1733 
AddFixItHint(const FixItHint & Hint)1734     void AddFixItHint(const FixItHint &Hint) const {
1735       if (ImmediateDiag.hasValue())
1736         ImmediateDiag->AddFixItHint(Hint);
1737       else if (PartialDiagId.hasValue())
1738         S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1739     }
1740 
ExprError(const SemaDiagnosticBuilder &)1741     friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1742       return ExprError();
1743     }
StmtError(const SemaDiagnosticBuilder &)1744     friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1745       return StmtError();
1746     }
ExprResult()1747     operator ExprResult() const { return ExprError(); }
StmtResult()1748     operator StmtResult() const { return StmtError(); }
TypeResult()1749     operator TypeResult() const { return TypeError(); }
DeclResult()1750     operator DeclResult() const { return DeclResult(true); }
MemInitResult()1751     operator MemInitResult() const { return MemInitResult(true); }
1752 
1753   private:
1754     Sema &S;
1755     SourceLocation Loc;
1756     unsigned DiagID;
1757     FunctionDecl *Fn;
1758     bool ShowCallStack;
1759 
1760     // Invariant: At most one of these Optionals has a value.
1761     // FIXME: Switch these to a Variant once that exists.
1762     llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1763     llvm::Optional<unsigned> PartialDiagId;
1764   };
1765 
1766   /// Is the last error level diagnostic immediate. This is used to determined
1767   /// whether the next info diagnostic should be immediate.
1768   bool IsLastErrorImmediate = true;
1769 
1770   /// Emit a diagnostic.
1771   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1772                              bool DeferHint = false);
1773 
1774   /// Emit a partial diagnostic.
1775   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1776                              bool DeferHint = false);
1777 
1778   /// Build a partial diagnostic.
1779   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1780 
1781   /// Whether deferrable diagnostics should be deferred.
1782   bool DeferDiags = false;
1783 
1784   /// RAII class to control scope of DeferDiags.
1785   class DeferDiagsRAII {
1786     Sema &S;
1787     bool SavedDeferDiags = false;
1788 
1789   public:
DeferDiagsRAII(Sema & S,bool DeferDiags)1790     DeferDiagsRAII(Sema &S, bool DeferDiags)
1791         : S(S), SavedDeferDiags(S.DeferDiags) {
1792       S.DeferDiags = DeferDiags;
1793     }
~DeferDiagsRAII()1794     ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1795   };
1796 
1797   /// Whether uncompilable error has occurred. This includes error happens
1798   /// in deferred diagnostics.
1799   bool hasUncompilableErrorOccurred() const;
1800 
1801   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1802 
1803   /// Get a string to suggest for zero-initialization of a type.
1804   std::string
1805   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1806   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1807 
1808   /// Calls \c Lexer::getLocForEndOfToken()
1809   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1810 
1811   /// Retrieve the module loader associated with the preprocessor.
1812   ModuleLoader &getModuleLoader() const;
1813 
1814   /// Invent a new identifier for parameters of abbreviated templates.
1815   IdentifierInfo *
1816   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1817                                              unsigned Index);
1818 
1819   void emitAndClearUnusedLocalTypedefWarnings();
1820 
1821   private:
1822     /// Function or variable declarations to be checked for whether the deferred
1823     /// diagnostics should be emitted.
1824     llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1825 
1826   public:
1827   // Emit all deferred diagnostics.
1828   void emitDeferredDiags();
1829 
1830   enum TUFragmentKind {
1831     /// The global module fragment, between 'module;' and a module-declaration.
1832     Global,
1833     /// A normal translation unit fragment. For a non-module unit, this is the
1834     /// entire translation unit. Otherwise, it runs from the module-declaration
1835     /// to the private-module-fragment (if any) or the end of the TU (if not).
1836     Normal,
1837     /// The private module fragment, between 'module :private;' and the end of
1838     /// the translation unit.
1839     Private
1840   };
1841 
1842   void ActOnStartOfTranslationUnit();
1843   void ActOnEndOfTranslationUnit();
1844   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1845 
1846   void CheckDelegatingCtorCycles();
1847 
1848   Scope *getScopeForContext(DeclContext *Ctx);
1849 
1850   void PushFunctionScope();
1851   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1852   sema::LambdaScopeInfo *PushLambdaScope();
1853 
1854   /// This is used to inform Sema what the current TemplateParameterDepth
1855   /// is during Parsing.  Currently it is used to pass on the depth
1856   /// when parsing generic lambda 'auto' parameters.
1857   void RecordParsingTemplateParameterDepth(unsigned Depth);
1858 
1859   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1860                                RecordDecl *RD, CapturedRegionKind K,
1861                                unsigned OpenMPCaptureLevel = 0);
1862 
1863   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1864   /// time after they've been popped.
1865   class PoppedFunctionScopeDeleter {
1866     Sema *Self;
1867 
1868   public:
PoppedFunctionScopeDeleter(Sema * Self)1869     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1870     void operator()(sema::FunctionScopeInfo *Scope) const;
1871   };
1872 
1873   using PoppedFunctionScopePtr =
1874       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1875 
1876   PoppedFunctionScopePtr
1877   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1878                        const Decl *D = nullptr,
1879                        QualType BlockType = QualType());
1880 
getCurFunction()1881   sema::FunctionScopeInfo *getCurFunction() const {
1882     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1883   }
1884 
1885   sema::FunctionScopeInfo *getEnclosingFunction() const;
1886 
1887   void setFunctionHasBranchIntoScope();
1888   void setFunctionHasBranchProtectedScope();
1889   void setFunctionHasIndirectGoto();
1890   void setFunctionHasMustTail();
1891 
1892   void PushCompoundScope(bool IsStmtExpr);
1893   void PopCompoundScope();
1894 
1895   sema::CompoundScopeInfo &getCurCompoundScope() const;
1896 
1897   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1898 
1899   /// Retrieve the current block, if any.
1900   sema::BlockScopeInfo *getCurBlock();
1901 
1902   /// Get the innermost lambda enclosing the current location, if any. This
1903   /// looks through intervening non-lambda scopes such as local functions and
1904   /// blocks.
1905   sema::LambdaScopeInfo *getEnclosingLambda() const;
1906 
1907   /// Retrieve the current lambda scope info, if any.
1908   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1909   /// lambda scope info ignoring all inner capturing scopes that are not
1910   /// lambda scopes.
1911   sema::LambdaScopeInfo *
1912   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1913 
1914   /// Retrieve the current generic lambda info, if any.
1915   sema::LambdaScopeInfo *getCurGenericLambda();
1916 
1917   /// Retrieve the current captured region, if any.
1918   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1919 
1920   /// Retrieve the current function, if any, that should be analyzed for
1921   /// potential availability violations.
1922   sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
1923 
1924   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
WeakTopLevelDecls()1925   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1926 
1927   /// Called before parsing a function declarator belonging to a function
1928   /// declaration.
1929   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1930                                                unsigned TemplateParameterDepth);
1931 
1932   /// Called after parsing a function declarator belonging to a function
1933   /// declaration.
1934   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1935 
1936   void ActOnComment(SourceRange Comment);
1937 
1938   //===--------------------------------------------------------------------===//
1939   // Type Analysis / Processing: SemaType.cpp.
1940   //
1941 
1942   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1943                               const DeclSpec *DS = nullptr);
1944   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1945                               const DeclSpec *DS = nullptr);
1946   QualType BuildPointerType(QualType T,
1947                             SourceLocation Loc, DeclarationName Entity);
1948   QualType BuildReferenceType(QualType T, bool LValueRef,
1949                               SourceLocation Loc, DeclarationName Entity);
1950   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1951                           Expr *ArraySize, unsigned Quals,
1952                           SourceRange Brackets, DeclarationName Entity);
1953   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1954   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1955                               SourceLocation AttrLoc);
1956   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1957                            SourceLocation AttrLoc);
1958 
1959   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1960                                  SourceLocation AttrLoc);
1961 
1962   /// Same as above, but constructs the AddressSpace index if not provided.
1963   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1964                                  SourceLocation AttrLoc);
1965 
1966   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1967 
1968   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1969 
1970   /// Build a function type.
1971   ///
1972   /// This routine checks the function type according to C++ rules and
1973   /// under the assumption that the result type and parameter types have
1974   /// just been instantiated from a template. It therefore duplicates
1975   /// some of the behavior of GetTypeForDeclarator, but in a much
1976   /// simpler form that is only suitable for this narrow use case.
1977   ///
1978   /// \param T The return type of the function.
1979   ///
1980   /// \param ParamTypes The parameter types of the function. This array
1981   /// will be modified to account for adjustments to the types of the
1982   /// function parameters.
1983   ///
1984   /// \param Loc The location of the entity whose type involves this
1985   /// function type or, if there is no such entity, the location of the
1986   /// type that will have function type.
1987   ///
1988   /// \param Entity The name of the entity that involves the function
1989   /// type, if known.
1990   ///
1991   /// \param EPI Extra information about the function type. Usually this will
1992   /// be taken from an existing function with the same prototype.
1993   ///
1994   /// \returns A suitable function type, if there are no errors. The
1995   /// unqualified type will always be a FunctionProtoType.
1996   /// Otherwise, returns a NULL type.
1997   QualType BuildFunctionType(QualType T,
1998                              MutableArrayRef<QualType> ParamTypes,
1999                              SourceLocation Loc, DeclarationName Entity,
2000                              const FunctionProtoType::ExtProtoInfo &EPI);
2001 
2002   QualType BuildMemberPointerType(QualType T, QualType Class,
2003                                   SourceLocation Loc,
2004                                   DeclarationName Entity);
2005   QualType BuildBlockPointerType(QualType T,
2006                                  SourceLocation Loc, DeclarationName Entity);
2007   QualType BuildParenType(QualType T);
2008   QualType BuildAtomicType(QualType T, SourceLocation Loc);
2009   QualType BuildReadPipeType(QualType T,
2010                          SourceLocation Loc);
2011   QualType BuildWritePipeType(QualType T,
2012                          SourceLocation Loc);
2013   QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2014 
2015   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2016   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2017 
2018   /// Package the given type and TSI into a ParsedType.
2019   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2020   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2021   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2022   static QualType GetTypeFromParser(ParsedType Ty,
2023                                     TypeSourceInfo **TInfo = nullptr);
2024   CanThrowResult canThrow(const Stmt *E);
2025   /// Determine whether the callee of a particular function call can throw.
2026   /// E, D and Loc are all optional.
2027   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2028                                        SourceLocation Loc = SourceLocation());
2029   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2030                                                 const FunctionProtoType *FPT);
2031   void UpdateExceptionSpec(FunctionDecl *FD,
2032                            const FunctionProtoType::ExceptionSpecInfo &ESI);
2033   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2034   bool CheckDistantExceptionSpec(QualType T);
2035   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2036   bool CheckEquivalentExceptionSpec(
2037       const FunctionProtoType *Old, SourceLocation OldLoc,
2038       const FunctionProtoType *New, SourceLocation NewLoc);
2039   bool CheckEquivalentExceptionSpec(
2040       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2041       const FunctionProtoType *Old, SourceLocation OldLoc,
2042       const FunctionProtoType *New, SourceLocation NewLoc);
2043   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2044   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2045                                 const PartialDiagnostic &NestedDiagID,
2046                                 const PartialDiagnostic &NoteID,
2047                                 const PartialDiagnostic &NoThrowDiagID,
2048                                 const FunctionProtoType *Superset,
2049                                 SourceLocation SuperLoc,
2050                                 const FunctionProtoType *Subset,
2051                                 SourceLocation SubLoc);
2052   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2053                                const PartialDiagnostic &NoteID,
2054                                const FunctionProtoType *Target,
2055                                SourceLocation TargetLoc,
2056                                const FunctionProtoType *Source,
2057                                SourceLocation SourceLoc);
2058 
2059   TypeResult ActOnTypeName(Scope *S, Declarator &D);
2060 
2061   /// The parser has parsed the context-sensitive type 'instancetype'
2062   /// in an Objective-C message declaration. Return the appropriate type.
2063   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2064 
2065   /// Abstract class used to diagnose incomplete types.
2066   struct TypeDiagnoser {
TypeDiagnoserTypeDiagnoser2067     TypeDiagnoser() {}
2068 
2069     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser2070     virtual ~TypeDiagnoser() {}
2071   };
2072 
getPrintable(int I)2073   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)2074   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)2075   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)2076   static const char * getPrintable(const char *S) { return S; }
getPrintable(StringRef S)2077   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)2078   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)2079   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2080     return II;
2081   }
getPrintable(DeclarationName N)2082   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)2083   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)2084   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)2085   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(const Expr * E)2086   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)2087   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2088 
2089   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2090   protected:
2091     unsigned DiagID;
2092     std::tuple<const Ts &...> Args;
2093 
2094     template <std::size_t... Is>
emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)2095     void emit(const SemaDiagnosticBuilder &DB,
2096               std::index_sequence<Is...>) const {
2097       // Apply all tuple elements to the builder in order.
2098       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2099       (void)Dummy;
2100     }
2101 
2102   public:
BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)2103     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2104         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2105       assert(DiagID != 0 && "no diagnostic for type diagnoser");
2106     }
2107 
diagnose(Sema & S,SourceLocation Loc,QualType T)2108     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2109       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2110       emit(DB, std::index_sequence_for<Ts...>());
2111       DB << T;
2112     }
2113   };
2114 
2115   /// Do a check to make sure \p Name looks like a legal argument for the
2116   /// swift_name attribute applied to decl \p D.  Raise a diagnostic if the name
2117   /// is invalid for the given declaration.
2118   ///
2119   /// \p AL is used to provide caret diagnostics in case of a malformed name.
2120   ///
2121   /// \returns true if the name is a valid swift name for \p D, false otherwise.
2122   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2123                          const ParsedAttr &AL, bool IsAsync);
2124 
2125   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2126   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2127   /// For example, a diagnostic with no other parameters would generally have
2128   /// the form "...%select{incomplete|sizeless}0 type %1...".
2129   template <typename... Ts>
2130   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2131   public:
SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)2132     SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2133         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2134 
diagnose(Sema & S,SourceLocation Loc,QualType T)2135     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2136       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2137       this->emit(DB, std::index_sequence_for<Ts...>());
2138       DB << T->isSizelessType() << T;
2139     }
2140   };
2141 
2142   enum class CompleteTypeKind {
2143     /// Apply the normal rules for complete types.  In particular,
2144     /// treat all sizeless types as incomplete.
2145     Normal,
2146 
2147     /// Relax the normal rules for complete types so that they include
2148     /// sizeless built-in types.
2149     AcceptSizeless,
2150 
2151     // FIXME: Eventually we should flip the default to Normal and opt in
2152     // to AcceptSizeless rather than opt out of it.
2153     Default = AcceptSizeless
2154   };
2155 
2156 private:
2157   /// Methods for marking which expressions involve dereferencing a pointer
2158   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2159   /// they are parsed, meaning that a noderef pointer may not be accessed. For
2160   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2161   /// `*p`, but need to check that `address of` is called on it. This requires
2162   /// keeping a container of all pending expressions and checking if the address
2163   /// of them are eventually taken.
2164   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2165   void CheckAddressOfNoDeref(const Expr *E);
2166   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2167 
2168   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2169                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2170 
2171   struct ModuleScope {
2172     SourceLocation BeginLoc;
2173     clang::Module *Module = nullptr;
2174     bool ModuleInterface = false;
2175     bool ImplicitGlobalModuleFragment = false;
2176     VisibleModuleSet OuterVisibleModules;
2177   };
2178   /// The modules we're currently parsing.
2179   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2180 
2181   /// Namespace definitions that we will export when they finish.
2182   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2183 
2184   /// Get the module whose scope we are currently within.
getCurrentModule()2185   Module *getCurrentModule() const {
2186     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2187   }
2188 
2189   VisibleModuleSet VisibleModules;
2190 
2191 public:
2192   /// Get the module owning an entity.
getOwningModule(const Decl * Entity)2193   Module *getOwningModule(const Decl *Entity) {
2194     return Entity->getOwningModule();
2195   }
2196 
2197   /// Make a merged definition of an existing hidden definition \p ND
2198   /// visible at the specified location.
2199   void makeMergedDefinitionVisible(NamedDecl *ND);
2200 
2201   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2202 
2203   // When loading a non-modular PCH files, this is used to restore module
2204   // visibility.
makeModuleVisible(Module * Mod,SourceLocation ImportLoc)2205   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2206     VisibleModules.setVisible(Mod, ImportLoc);
2207   }
2208 
2209   /// Determine whether a declaration is visible to name lookup.
isVisible(const NamedDecl * D)2210   bool isVisible(const NamedDecl *D) {
2211     return D->isUnconditionallyVisible() || isVisibleSlow(D);
2212   }
2213 
2214   /// Determine whether any declaration of an entity is visible.
2215   bool
2216   hasVisibleDeclaration(const NamedDecl *D,
2217                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2218     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2219   }
2220   bool hasVisibleDeclarationSlow(const NamedDecl *D,
2221                                  llvm::SmallVectorImpl<Module *> *Modules);
2222 
2223   bool hasVisibleMergedDefinition(NamedDecl *Def);
2224   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2225 
2226   /// Determine if \p D and \p Suggested have a structurally compatible
2227   /// layout as described in C11 6.2.7/1.
2228   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2229 
2230   /// Determine if \p D has a visible definition. If not, suggest a declaration
2231   /// that should be made visible to expose the definition.
2232   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2233                             bool OnlyNeedComplete = false);
hasVisibleDefinition(const NamedDecl * D)2234   bool hasVisibleDefinition(const NamedDecl *D) {
2235     NamedDecl *Hidden;
2236     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2237   }
2238 
2239   /// Determine if the template parameter \p D has a visible default argument.
2240   bool
2241   hasVisibleDefaultArgument(const NamedDecl *D,
2242                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2243 
2244   /// Determine if there is a visible declaration of \p D that is an explicit
2245   /// specialization declaration for a specialization of a template. (For a
2246   /// member specialization, use hasVisibleMemberSpecialization.)
2247   bool hasVisibleExplicitSpecialization(
2248       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2249 
2250   /// Determine if there is a visible declaration of \p D that is a member
2251   /// specialization declaration (as opposed to an instantiated declaration).
2252   bool hasVisibleMemberSpecialization(
2253       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2254 
2255   /// Determine if \p A and \p B are equivalent internal linkage declarations
2256   /// from different modules, and thus an ambiguity error can be downgraded to
2257   /// an extension warning.
2258   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2259                                               const NamedDecl *B);
2260   void diagnoseEquivalentInternalLinkageDeclarations(
2261       SourceLocation Loc, const NamedDecl *D,
2262       ArrayRef<const NamedDecl *> Equiv);
2263 
2264   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2265 
2266   bool isCompleteType(SourceLocation Loc, QualType T,
2267                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
2268     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2269   }
2270   bool RequireCompleteType(SourceLocation Loc, QualType T,
2271                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2272   bool RequireCompleteType(SourceLocation Loc, QualType T,
2273                            CompleteTypeKind Kind, unsigned DiagID);
2274 
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)2275   bool RequireCompleteType(SourceLocation Loc, QualType T,
2276                            TypeDiagnoser &Diagnoser) {
2277     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2278   }
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)2279   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2280     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2281   }
2282 
2283   template <typename... Ts>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2284   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2285                            const Ts &...Args) {
2286     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2287     return RequireCompleteType(Loc, T, Diagnoser);
2288   }
2289 
2290   template <typename... Ts>
RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2291   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2292                                 const Ts &... Args) {
2293     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2294     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2295   }
2296 
2297   /// Get the type of expression E, triggering instantiation to complete the
2298   /// type if necessary -- that is, if the expression refers to a templated
2299   /// static data member of incomplete array type.
2300   ///
2301   /// May still return an incomplete type if instantiation was not possible or
2302   /// if the type is incomplete for a different reason. Use
2303   /// RequireCompleteExprType instead if a diagnostic is expected for an
2304   /// incomplete expression type.
2305   QualType getCompletedType(Expr *E);
2306 
2307   void completeExprArrayBound(Expr *E);
2308   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2309                                TypeDiagnoser &Diagnoser);
2310   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2311 
2312   template <typename... Ts>
RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2313   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2314     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2315     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2316   }
2317 
2318   template <typename... Ts>
RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2319   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2320                                     const Ts &... Args) {
2321     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2322     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2323   }
2324 
2325   bool RequireLiteralType(SourceLocation Loc, QualType T,
2326                           TypeDiagnoser &Diagnoser);
2327   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2328 
2329   template <typename... Ts>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2330   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2331                           const Ts &...Args) {
2332     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2333     return RequireLiteralType(Loc, T, Diagnoser);
2334   }
2335 
2336   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2337                              const CXXScopeSpec &SS, QualType T,
2338                              TagDecl *OwnedTagDecl = nullptr);
2339 
2340   QualType getDecltypeForParenthesizedExpr(Expr *E);
2341   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
2342   /// If AsUnevaluated is false, E is treated as though it were an evaluated
2343   /// context, such as when building a type for decltype(auto).
2344   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
2345                              bool AsUnevaluated = true);
2346   QualType BuildUnaryTransformType(QualType BaseType,
2347                                    UnaryTransformType::UTTKind UKind,
2348                                    SourceLocation Loc);
2349 
2350   //===--------------------------------------------------------------------===//
2351   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2352   //
2353 
2354   struct SkipBodyInfo {
SkipBodyInfoSkipBodyInfo2355     SkipBodyInfo()
2356         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2357           New(nullptr) {}
2358     bool ShouldSkip;
2359     bool CheckSameAsPrevious;
2360     NamedDecl *Previous;
2361     NamedDecl *New;
2362   };
2363 
2364   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2365 
2366   void DiagnoseUseOfUnimplementedSelectors();
2367 
2368   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2369 
2370   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2371                          Scope *S, CXXScopeSpec *SS = nullptr,
2372                          bool isClassName = false, bool HasTrailingDot = false,
2373                          ParsedType ObjectType = nullptr,
2374                          bool IsCtorOrDtorName = false,
2375                          bool WantNontrivialTypeSourceInfo = false,
2376                          bool IsClassTemplateDeductionContext = true,
2377                          IdentifierInfo **CorrectedII = nullptr);
2378   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2379   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2380   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2381                                SourceLocation IILoc,
2382                                Scope *S,
2383                                CXXScopeSpec *SS,
2384                                ParsedType &SuggestedType,
2385                                bool IsTemplateName = false);
2386 
2387   /// Attempt to behave like MSVC in situations where lookup of an unqualified
2388   /// type name has failed in a dependent context. In these situations, we
2389   /// automatically form a DependentTypeName that will retry lookup in a related
2390   /// scope during instantiation.
2391   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2392                                       SourceLocation NameLoc,
2393                                       bool IsTemplateTypeArg);
2394 
2395   /// Describes the result of the name lookup and resolution performed
2396   /// by \c ClassifyName().
2397   enum NameClassificationKind {
2398     /// This name is not a type or template in this context, but might be
2399     /// something else.
2400     NC_Unknown,
2401     /// Classification failed; an error has been produced.
2402     NC_Error,
2403     /// The name has been typo-corrected to a keyword.
2404     NC_Keyword,
2405     /// The name was classified as a type.
2406     NC_Type,
2407     /// The name was classified as a specific non-type, non-template
2408     /// declaration. ActOnNameClassifiedAsNonType should be called to
2409     /// convert the declaration to an expression.
2410     NC_NonType,
2411     /// The name was classified as an ADL-only function name.
2412     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2413     /// result to an expression.
2414     NC_UndeclaredNonType,
2415     /// The name denotes a member of a dependent type that could not be
2416     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2417     /// convert the result to an expression.
2418     NC_DependentNonType,
2419     /// The name was classified as an overload set, and an expression
2420     /// representing that overload set has been formed.
2421     /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2422     /// expression referencing the overload set.
2423     NC_OverloadSet,
2424     /// The name was classified as a template whose specializations are types.
2425     NC_TypeTemplate,
2426     /// The name was classified as a variable template name.
2427     NC_VarTemplate,
2428     /// The name was classified as a function template name.
2429     NC_FunctionTemplate,
2430     /// The name was classified as an ADL-only function template name.
2431     NC_UndeclaredTemplate,
2432     /// The name was classified as a concept name.
2433     NC_Concept,
2434   };
2435 
2436   class NameClassification {
2437     NameClassificationKind Kind;
2438     union {
2439       ExprResult Expr;
2440       NamedDecl *NonTypeDecl;
2441       TemplateName Template;
2442       ParsedType Type;
2443     };
2444 
NameClassification(NameClassificationKind Kind)2445     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2446 
2447   public:
NameClassification(ParsedType Type)2448     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2449 
NameClassification(const IdentifierInfo * Keyword)2450     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2451 
Error()2452     static NameClassification Error() {
2453       return NameClassification(NC_Error);
2454     }
2455 
Unknown()2456     static NameClassification Unknown() {
2457       return NameClassification(NC_Unknown);
2458     }
2459 
OverloadSet(ExprResult E)2460     static NameClassification OverloadSet(ExprResult E) {
2461       NameClassification Result(NC_OverloadSet);
2462       Result.Expr = E;
2463       return Result;
2464     }
2465 
NonType(NamedDecl * D)2466     static NameClassification NonType(NamedDecl *D) {
2467       NameClassification Result(NC_NonType);
2468       Result.NonTypeDecl = D;
2469       return Result;
2470     }
2471 
UndeclaredNonType()2472     static NameClassification UndeclaredNonType() {
2473       return NameClassification(NC_UndeclaredNonType);
2474     }
2475 
DependentNonType()2476     static NameClassification DependentNonType() {
2477       return NameClassification(NC_DependentNonType);
2478     }
2479 
TypeTemplate(TemplateName Name)2480     static NameClassification TypeTemplate(TemplateName Name) {
2481       NameClassification Result(NC_TypeTemplate);
2482       Result.Template = Name;
2483       return Result;
2484     }
2485 
VarTemplate(TemplateName Name)2486     static NameClassification VarTemplate(TemplateName Name) {
2487       NameClassification Result(NC_VarTemplate);
2488       Result.Template = Name;
2489       return Result;
2490     }
2491 
FunctionTemplate(TemplateName Name)2492     static NameClassification FunctionTemplate(TemplateName Name) {
2493       NameClassification Result(NC_FunctionTemplate);
2494       Result.Template = Name;
2495       return Result;
2496     }
2497 
Concept(TemplateName Name)2498     static NameClassification Concept(TemplateName Name) {
2499       NameClassification Result(NC_Concept);
2500       Result.Template = Name;
2501       return Result;
2502     }
2503 
UndeclaredTemplate(TemplateName Name)2504     static NameClassification UndeclaredTemplate(TemplateName Name) {
2505       NameClassification Result(NC_UndeclaredTemplate);
2506       Result.Template = Name;
2507       return Result;
2508     }
2509 
getKind()2510     NameClassificationKind getKind() const { return Kind; }
2511 
getExpression()2512     ExprResult getExpression() const {
2513       assert(Kind == NC_OverloadSet);
2514       return Expr;
2515     }
2516 
getType()2517     ParsedType getType() const {
2518       assert(Kind == NC_Type);
2519       return Type;
2520     }
2521 
getNonTypeDecl()2522     NamedDecl *getNonTypeDecl() const {
2523       assert(Kind == NC_NonType);
2524       return NonTypeDecl;
2525     }
2526 
getTemplateName()2527     TemplateName getTemplateName() const {
2528       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2529              Kind == NC_VarTemplate || Kind == NC_Concept ||
2530              Kind == NC_UndeclaredTemplate);
2531       return Template;
2532     }
2533 
getTemplateNameKind()2534     TemplateNameKind getTemplateNameKind() const {
2535       switch (Kind) {
2536       case NC_TypeTemplate:
2537         return TNK_Type_template;
2538       case NC_FunctionTemplate:
2539         return TNK_Function_template;
2540       case NC_VarTemplate:
2541         return TNK_Var_template;
2542       case NC_Concept:
2543         return TNK_Concept_template;
2544       case NC_UndeclaredTemplate:
2545         return TNK_Undeclared_template;
2546       default:
2547         llvm_unreachable("unsupported name classification.");
2548       }
2549     }
2550   };
2551 
2552   /// Perform name lookup on the given name, classifying it based on
2553   /// the results of name lookup and the following token.
2554   ///
2555   /// This routine is used by the parser to resolve identifiers and help direct
2556   /// parsing. When the identifier cannot be found, this routine will attempt
2557   /// to correct the typo and classify based on the resulting name.
2558   ///
2559   /// \param S The scope in which we're performing name lookup.
2560   ///
2561   /// \param SS The nested-name-specifier that precedes the name.
2562   ///
2563   /// \param Name The identifier. If typo correction finds an alternative name,
2564   /// this pointer parameter will be updated accordingly.
2565   ///
2566   /// \param NameLoc The location of the identifier.
2567   ///
2568   /// \param NextToken The token following the identifier. Used to help
2569   /// disambiguate the name.
2570   ///
2571   /// \param CCC The correction callback, if typo correction is desired.
2572   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2573                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2574                                   const Token &NextToken,
2575                                   CorrectionCandidateCallback *CCC = nullptr);
2576 
2577   /// Act on the result of classifying a name as an undeclared (ADL-only)
2578   /// non-type declaration.
2579   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2580                                                     SourceLocation NameLoc);
2581   /// Act on the result of classifying a name as an undeclared member of a
2582   /// dependent base class.
2583   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2584                                                    IdentifierInfo *Name,
2585                                                    SourceLocation NameLoc,
2586                                                    bool IsAddressOfOperand);
2587   /// Act on the result of classifying a name as a specific non-type
2588   /// declaration.
2589   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2590                                           NamedDecl *Found,
2591                                           SourceLocation NameLoc,
2592                                           const Token &NextToken);
2593   /// Act on the result of classifying a name as an overload set.
2594   ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2595 
2596   /// Describes the detailed kind of a template name. Used in diagnostics.
2597   enum class TemplateNameKindForDiagnostics {
2598     ClassTemplate,
2599     FunctionTemplate,
2600     VarTemplate,
2601     AliasTemplate,
2602     TemplateTemplateParam,
2603     Concept,
2604     DependentTemplate
2605   };
2606   TemplateNameKindForDiagnostics
2607   getTemplateNameKindForDiagnostics(TemplateName Name);
2608 
2609   /// Determine whether it's plausible that E was intended to be a
2610   /// template-name.
mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2611   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2612     if (!getLangOpts().CPlusPlus || E.isInvalid())
2613       return false;
2614     Dependent = false;
2615     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2616       return !DRE->hasExplicitTemplateArgs();
2617     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2618       return !ME->hasExplicitTemplateArgs();
2619     Dependent = true;
2620     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2621       return !DSDRE->hasExplicitTemplateArgs();
2622     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2623       return !DSME->hasExplicitTemplateArgs();
2624     // Any additional cases recognized here should also be handled by
2625     // diagnoseExprIntendedAsTemplateName.
2626     return false;
2627   }
2628   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2629                                           SourceLocation Less,
2630                                           SourceLocation Greater);
2631 
2632   void warnOnReservedIdentifier(const NamedDecl *D);
2633 
2634   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2635 
2636   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2637                               MultiTemplateParamsArg TemplateParameterLists);
2638   bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2639                                        QualType &T, SourceLocation Loc,
2640                                        unsigned FailedFoldDiagID);
2641   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2642   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2643   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2644                                     DeclarationName Name, SourceLocation Loc,
2645                                     bool IsTemplateId);
2646   void
2647   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2648                             SourceLocation FallbackLoc,
2649                             SourceLocation ConstQualLoc = SourceLocation(),
2650                             SourceLocation VolatileQualLoc = SourceLocation(),
2651                             SourceLocation RestrictQualLoc = SourceLocation(),
2652                             SourceLocation AtomicQualLoc = SourceLocation(),
2653                             SourceLocation UnalignedQualLoc = SourceLocation());
2654 
2655   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2656   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2657   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2658                                     const LookupResult &R);
2659   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2660   NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2661                                     const LookupResult &R);
2662   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2663                    const LookupResult &R);
2664   void CheckShadow(Scope *S, VarDecl *D);
2665 
2666   /// Warn if 'E', which is an expression that is about to be modified, refers
2667   /// to a shadowing declaration.
2668   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2669 
2670   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2671 
2672 private:
2673   /// Map of current shadowing declarations to shadowed declarations. Warn if
2674   /// it looks like the user is trying to modify the shadowing declaration.
2675   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2676 
2677 public:
2678   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2679   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2680   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2681                                     TypedefNameDecl *NewTD);
2682   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2683   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2684                                     TypeSourceInfo *TInfo,
2685                                     LookupResult &Previous);
2686   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2687                                   LookupResult &Previous, bool &Redeclaration);
2688   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2689                                      TypeSourceInfo *TInfo,
2690                                      LookupResult &Previous,
2691                                      MultiTemplateParamsArg TemplateParamLists,
2692                                      bool &AddToScope,
2693                                      ArrayRef<BindingDecl *> Bindings = None);
2694   NamedDecl *
2695   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2696                                MultiTemplateParamsArg TemplateParamLists);
2697   // Returns true if the variable declaration is a redeclaration
2698   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2699   void CheckVariableDeclarationType(VarDecl *NewVD);
2700   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2701                                      Expr *Init);
2702   void CheckCompleteVariableDeclaration(VarDecl *VD);
2703   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2704   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2705 
2706   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2707                                      TypeSourceInfo *TInfo,
2708                                      LookupResult &Previous,
2709                                      MultiTemplateParamsArg TemplateParamLists,
2710                                      bool &AddToScope);
2711   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2712 
2713   enum class CheckConstexprKind {
2714     /// Diagnose issues that are non-constant or that are extensions.
2715     Diagnose,
2716     /// Identify whether this function satisfies the formal rules for constexpr
2717     /// functions in the current lanugage mode (with no extensions).
2718     CheckValid
2719   };
2720 
2721   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2722                                         CheckConstexprKind Kind);
2723 
2724   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2725   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2726                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2727   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2728                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2729   // Returns true if the function declaration is a redeclaration
2730   bool CheckFunctionDeclaration(Scope *S,
2731                                 FunctionDecl *NewFD, LookupResult &Previous,
2732                                 bool IsMemberSpecialization);
2733   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2734   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2735                                       QualType NewT, QualType OldT);
2736   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2737   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2738   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2739                                                    bool IsDefinition);
2740   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2741   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2742   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2743                                           SourceLocation Loc,
2744                                           QualType T);
2745   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2746                               SourceLocation NameLoc, IdentifierInfo *Name,
2747                               QualType T, TypeSourceInfo *TSInfo,
2748                               StorageClass SC);
2749   void ActOnParamDefaultArgument(Decl *param,
2750                                  SourceLocation EqualLoc,
2751                                  Expr *defarg);
2752   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2753                                          SourceLocation ArgLoc);
2754   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2755   ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2756                                          SourceLocation EqualLoc);
2757   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2758                                SourceLocation EqualLoc);
2759 
2760   // Contexts where using non-trivial C union types can be disallowed. This is
2761   // passed to err_non_trivial_c_union_in_invalid_context.
2762   enum NonTrivialCUnionContext {
2763     // Function parameter.
2764     NTCUC_FunctionParam,
2765     // Function return.
2766     NTCUC_FunctionReturn,
2767     // Default-initialized object.
2768     NTCUC_DefaultInitializedObject,
2769     // Variable with automatic storage duration.
2770     NTCUC_AutoVar,
2771     // Initializer expression that might copy from another object.
2772     NTCUC_CopyInit,
2773     // Assignment.
2774     NTCUC_Assignment,
2775     // Compound literal.
2776     NTCUC_CompoundLiteral,
2777     // Block capture.
2778     NTCUC_BlockCapture,
2779     // lvalue-to-rvalue conversion of volatile type.
2780     NTCUC_LValueToRValueVolatile,
2781   };
2782 
2783   /// Emit diagnostics if the initializer or any of its explicit or
2784   /// implicitly-generated subexpressions require copying or
2785   /// default-initializing a type that is or contains a C union type that is
2786   /// non-trivial to copy or default-initialize.
2787   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2788 
2789   // These flags are passed to checkNonTrivialCUnion.
2790   enum NonTrivialCUnionKind {
2791     NTCUK_Init = 0x1,
2792     NTCUK_Destruct = 0x2,
2793     NTCUK_Copy = 0x4,
2794   };
2795 
2796   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2797   /// a non-trivial C union is used in an invalid context.
2798   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2799                              NonTrivialCUnionContext UseContext,
2800                              unsigned NonTrivialKind);
2801 
2802   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2803   void ActOnUninitializedDecl(Decl *dcl);
2804   void ActOnInitializerError(Decl *Dcl);
2805 
2806   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2807   void ActOnCXXForRangeDecl(Decl *D);
2808   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2809                                         IdentifierInfo *Ident,
2810                                         ParsedAttributes &Attrs,
2811                                         SourceLocation AttrEnd);
2812   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2813   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2814   void CheckStaticLocalForDllExport(VarDecl *VD);
2815   void FinalizeDeclaration(Decl *D);
2816   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2817                                          ArrayRef<Decl *> Group);
2818   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2819 
2820   /// Should be called on all declarations that might have attached
2821   /// documentation comments.
2822   void ActOnDocumentableDecl(Decl *D);
2823   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2824 
2825   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2826                                        SourceLocation LocAfterDecls);
2827   void CheckForFunctionRedefinition(
2828       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2829       SkipBodyInfo *SkipBody = nullptr);
2830   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2831                                 MultiTemplateParamsArg TemplateParamLists,
2832                                 SkipBodyInfo *SkipBody = nullptr);
2833   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2834                                 SkipBodyInfo *SkipBody = nullptr);
2835   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2836   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2837   ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2838   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
isObjCMethodDecl(Decl * D)2839   bool isObjCMethodDecl(Decl *D) {
2840     return D && isa<ObjCMethodDecl>(D);
2841   }
2842 
2843   /// Determine whether we can delay parsing the body of a function or
2844   /// function template until it is used, assuming we don't care about emitting
2845   /// code for that function.
2846   ///
2847   /// This will be \c false if we may need the body of the function in the
2848   /// middle of parsing an expression (where it's impractical to switch to
2849   /// parsing a different function), for instance, if it's constexpr in C++11
2850   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2851   bool canDelayFunctionBody(const Declarator &D);
2852 
2853   /// Determine whether we can skip parsing the body of a function
2854   /// definition, assuming we don't care about analyzing its body or emitting
2855   /// code for that function.
2856   ///
2857   /// This will be \c false only if we may need the body of the function in
2858   /// order to parse the rest of the program (for instance, if it is
2859   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2860   bool canSkipFunctionBody(Decl *D);
2861 
2862   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2863   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2864   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2865   Decl *ActOnSkippedFunctionBody(Decl *Decl);
2866   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2867 
2868   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2869   /// attribute for which parsing is delayed.
2870   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2871 
2872   /// Diagnose any unused parameters in the given sequence of
2873   /// ParmVarDecl pointers.
2874   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2875 
2876   /// Diagnose whether the size of parameters or return value of a
2877   /// function or obj-c method definition is pass-by-value and larger than a
2878   /// specified threshold.
2879   void
2880   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2881                                          QualType ReturnTy, NamedDecl *D);
2882 
2883   void DiagnoseInvalidJumps(Stmt *Body);
2884   Decl *ActOnFileScopeAsmDecl(Expr *expr,
2885                               SourceLocation AsmLoc,
2886                               SourceLocation RParenLoc);
2887 
2888   /// Handle a C++11 empty-declaration and attribute-declaration.
2889   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2890                               SourceLocation SemiLoc);
2891 
2892   enum class ModuleDeclKind {
2893     Interface,      ///< 'export module X;'
2894     Implementation, ///< 'module X;'
2895   };
2896 
2897   /// The parser has processed a module-declaration that begins the definition
2898   /// of a module interface or implementation.
2899   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2900                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2901                                  ModuleIdPath Path, bool IsFirstDecl);
2902 
2903   /// The parser has processed a global-module-fragment declaration that begins
2904   /// the definition of the global module fragment of the current module unit.
2905   /// \param ModuleLoc The location of the 'module' keyword.
2906   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2907 
2908   /// The parser has processed a private-module-fragment declaration that begins
2909   /// the definition of the private module fragment of the current module unit.
2910   /// \param ModuleLoc The location of the 'module' keyword.
2911   /// \param PrivateLoc The location of the 'private' keyword.
2912   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2913                                                 SourceLocation PrivateLoc);
2914 
2915   /// The parser has processed a module import declaration.
2916   ///
2917   /// \param StartLoc The location of the first token in the declaration. This
2918   ///        could be the location of an '@', 'export', or 'import'.
2919   /// \param ExportLoc The location of the 'export' keyword, if any.
2920   /// \param ImportLoc The location of the 'import' keyword.
2921   /// \param Path The module access path.
2922   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2923                                SourceLocation ExportLoc,
2924                                SourceLocation ImportLoc, ModuleIdPath Path);
2925   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2926                                SourceLocation ExportLoc,
2927                                SourceLocation ImportLoc, Module *M,
2928                                ModuleIdPath Path = {});
2929 
2930   /// The parser has processed a module import translated from a
2931   /// #include or similar preprocessing directive.
2932   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2933   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2934 
2935   /// The parsed has entered a submodule.
2936   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2937   /// The parser has left a submodule.
2938   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2939 
2940   /// Create an implicit import of the given module at the given
2941   /// source location, for error recovery, if possible.
2942   ///
2943   /// This routine is typically used when an entity found by name lookup
2944   /// is actually hidden within a module that we know about but the user
2945   /// has forgotten to import.
2946   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2947                                                   Module *Mod);
2948 
2949   /// Kinds of missing import. Note, the values of these enumerators correspond
2950   /// to %select values in diagnostics.
2951   enum class MissingImportKind {
2952     Declaration,
2953     Definition,
2954     DefaultArgument,
2955     ExplicitSpecialization,
2956     PartialSpecialization
2957   };
2958 
2959   /// Diagnose that the specified declaration needs to be visible but
2960   /// isn't, and suggest a module import that would resolve the problem.
2961   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2962                              MissingImportKind MIK, bool Recover = true);
2963   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2964                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2965                              MissingImportKind MIK, bool Recover);
2966 
2967   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2968                              SourceLocation LBraceLoc);
2969   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2970                               SourceLocation RBraceLoc);
2971 
2972   /// We've found a use of a templated declaration that would trigger an
2973   /// implicit instantiation. Check that any relevant explicit specializations
2974   /// and partial specializations are visible, and diagnose if not.
2975   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2976 
2977   /// Retrieve a suitable printing policy for diagnostics.
getPrintingPolicy()2978   PrintingPolicy getPrintingPolicy() const {
2979     return getPrintingPolicy(Context, PP);
2980   }
2981 
2982   /// Retrieve a suitable printing policy for diagnostics.
2983   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2984                                           const Preprocessor &PP);
2985 
2986   /// Scope actions.
2987   void ActOnPopScope(SourceLocation Loc, Scope *S);
2988   void ActOnTranslationUnitScope(Scope *S);
2989 
2990   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2991                                    RecordDecl *&AnonRecord);
2992   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2993                                    MultiTemplateParamsArg TemplateParams,
2994                                    bool IsExplicitInstantiation,
2995                                    RecordDecl *&AnonRecord);
2996 
2997   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2998                                     AccessSpecifier AS,
2999                                     RecordDecl *Record,
3000                                     const PrintingPolicy &Policy);
3001 
3002   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3003                                        RecordDecl *Record);
3004 
3005   /// Common ways to introduce type names without a tag for use in diagnostics.
3006   /// Keep in sync with err_tag_reference_non_tag.
3007   enum NonTagKind {
3008     NTK_NonStruct,
3009     NTK_NonClass,
3010     NTK_NonUnion,
3011     NTK_NonEnum,
3012     NTK_Typedef,
3013     NTK_TypeAlias,
3014     NTK_Template,
3015     NTK_TypeAliasTemplate,
3016     NTK_TemplateTemplateArgument,
3017   };
3018 
3019   /// Given a non-tag type declaration, returns an enum useful for indicating
3020   /// what kind of non-tag type this is.
3021   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3022 
3023   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3024                                     TagTypeKind NewTag, bool isDefinition,
3025                                     SourceLocation NewTagLoc,
3026                                     const IdentifierInfo *Name);
3027 
3028   enum TagUseKind {
3029     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
3030     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
3031     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
3032     TUK_Friend       // Friend declaration:  'friend struct foo;'
3033   };
3034 
3035   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3036                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3037                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
3038                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3039                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3040                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3041                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3042                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3043                  SkipBodyInfo *SkipBody = nullptr);
3044 
3045   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3046                                 unsigned TagSpec, SourceLocation TagLoc,
3047                                 CXXScopeSpec &SS, IdentifierInfo *Name,
3048                                 SourceLocation NameLoc,
3049                                 const ParsedAttributesView &Attr,
3050                                 MultiTemplateParamsArg TempParamLists);
3051 
3052   TypeResult ActOnDependentTag(Scope *S,
3053                                unsigned TagSpec,
3054                                TagUseKind TUK,
3055                                const CXXScopeSpec &SS,
3056                                IdentifierInfo *Name,
3057                                SourceLocation TagLoc,
3058                                SourceLocation NameLoc);
3059 
3060   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3061                  IdentifierInfo *ClassName,
3062                  SmallVectorImpl<Decl *> &Decls);
3063   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3064                    Declarator &D, Expr *BitfieldWidth);
3065 
3066   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3067                          Declarator &D, Expr *BitfieldWidth,
3068                          InClassInitStyle InitStyle,
3069                          AccessSpecifier AS);
3070   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3071                                    SourceLocation DeclStart, Declarator &D,
3072                                    Expr *BitfieldWidth,
3073                                    InClassInitStyle InitStyle,
3074                                    AccessSpecifier AS,
3075                                    const ParsedAttr &MSPropertyAttr);
3076 
3077   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3078                             TypeSourceInfo *TInfo,
3079                             RecordDecl *Record, SourceLocation Loc,
3080                             bool Mutable, Expr *BitfieldWidth,
3081                             InClassInitStyle InitStyle,
3082                             SourceLocation TSSL,
3083                             AccessSpecifier AS, NamedDecl *PrevDecl,
3084                             Declarator *D = nullptr);
3085 
3086   bool CheckNontrivialField(FieldDecl *FD);
3087   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3088 
3089   enum TrivialABIHandling {
3090     /// The triviality of a method unaffected by "trivial_abi".
3091     TAH_IgnoreTrivialABI,
3092 
3093     /// The triviality of a method affected by "trivial_abi".
3094     TAH_ConsiderTrivialABI
3095   };
3096 
3097   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3098                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3099                               bool Diagnose = false);
3100 
3101   /// For a defaulted function, the kind of defaulted function that it is.
3102   class DefaultedFunctionKind {
3103     CXXSpecialMember SpecialMember : 8;
3104     DefaultedComparisonKind Comparison : 8;
3105 
3106   public:
DefaultedFunctionKind()3107     DefaultedFunctionKind()
3108         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3109     }
DefaultedFunctionKind(CXXSpecialMember CSM)3110     DefaultedFunctionKind(CXXSpecialMember CSM)
3111         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)3112     DefaultedFunctionKind(DefaultedComparisonKind Comp)
3113         : SpecialMember(CXXInvalid), Comparison(Comp) {}
3114 
isSpecialMember()3115     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
isComparison()3116     bool isComparison() const {
3117       return Comparison != DefaultedComparisonKind::None;
3118     }
3119 
3120     explicit operator bool() const {
3121       return isSpecialMember() || isComparison();
3122     }
3123 
asSpecialMember()3124     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
asComparison()3125     DefaultedComparisonKind asComparison() const { return Comparison; }
3126 
3127     /// Get the index of this function kind for use in diagnostics.
getDiagnosticIndex()3128     unsigned getDiagnosticIndex() const {
3129       static_assert(CXXInvalid > CXXDestructor,
3130                     "invalid should have highest index");
3131       static_assert((unsigned)DefaultedComparisonKind::None == 0,
3132                     "none should be equal to zero");
3133       return SpecialMember + (unsigned)Comparison;
3134     }
3135   };
3136 
3137   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3138 
getSpecialMember(const CXXMethodDecl * MD)3139   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3140     return getDefaultedFunctionKind(MD).asSpecialMember();
3141   }
getDefaultedComparisonKind(const FunctionDecl * FD)3142   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3143     return getDefaultedFunctionKind(FD).asComparison();
3144   }
3145 
3146   void ActOnLastBitfield(SourceLocation DeclStart,
3147                          SmallVectorImpl<Decl *> &AllIvarDecls);
3148   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3149                   Declarator &D, Expr *BitfieldWidth,
3150                   tok::ObjCKeywordKind visibility);
3151 
3152   // This is used for both record definitions and ObjC interface declarations.
3153   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3154                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
3155                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
3156 
3157   /// ActOnTagStartDefinition - Invoked when we have entered the
3158   /// scope of a tag's definition (e.g., for an enumeration, class,
3159   /// struct, or union).
3160   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3161 
3162   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3163   /// Differently from C++, actually parse the body and reject / error out
3164   /// in case of a structural mismatch.
3165   bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
3166                                 SkipBodyInfo &SkipBody);
3167 
3168   typedef void *SkippedDefinitionContext;
3169 
3170   /// Invoked when we enter a tag definition that we're skipping.
3171   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3172 
3173   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
3174 
3175   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3176   /// C++ record definition's base-specifiers clause and are starting its
3177   /// member declarations.
3178   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3179                                        SourceLocation FinalLoc,
3180                                        bool IsFinalSpelledSealed,
3181                                        bool IsAbstract,
3182                                        SourceLocation LBraceLoc);
3183 
3184   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3185   /// the definition of a tag (enumeration, class, struct, or union).
3186   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3187                                 SourceRange BraceRange);
3188 
3189   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3190 
3191   void ActOnObjCContainerFinishDefinition();
3192 
3193   /// Invoked when we must temporarily exit the objective-c container
3194   /// scope for parsing/looking-up C constructs.
3195   ///
3196   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3197   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
3198   void ActOnObjCReenterContainerContext(DeclContext *DC);
3199 
3200   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3201   /// error parsing the definition of a tag.
3202   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3203 
3204   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3205                                       EnumConstantDecl *LastEnumConst,
3206                                       SourceLocation IdLoc,
3207                                       IdentifierInfo *Id,
3208                                       Expr *val);
3209   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3210   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3211                               QualType EnumUnderlyingTy, bool IsFixed,
3212                               const EnumDecl *Prev);
3213 
3214   /// Determine whether the body of an anonymous enumeration should be skipped.
3215   /// \param II The name of the first enumerator.
3216   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3217                                       SourceLocation IILoc);
3218 
3219   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3220                           SourceLocation IdLoc, IdentifierInfo *Id,
3221                           const ParsedAttributesView &Attrs,
3222                           SourceLocation EqualLoc, Expr *Val);
3223   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3224                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3225                      const ParsedAttributesView &Attr);
3226 
3227   /// Set the current declaration context until it gets popped.
3228   void PushDeclContext(Scope *S, DeclContext *DC);
3229   void PopDeclContext();
3230 
3231   /// EnterDeclaratorContext - Used when we must lookup names in the context
3232   /// of a declarator's nested name specifier.
3233   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3234   void ExitDeclaratorContext(Scope *S);
3235 
3236   /// Enter a template parameter scope, after it's been associated with a particular
3237   /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3238   /// in the correct order.
3239   void EnterTemplatedContext(Scope *S, DeclContext *DC);
3240 
3241   /// Push the parameters of D, which must be a function, into scope.
3242   void ActOnReenterFunctionContext(Scope* S, Decl* D);
3243   void ActOnExitFunctionContext();
3244 
3245   DeclContext *getFunctionLevelDeclContext();
3246 
3247   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
3248   /// to the function decl for the function being parsed.  If we're currently
3249   /// in a 'block', this returns the containing context.
3250   FunctionDecl *getCurFunctionDecl();
3251 
3252   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3253   /// the method decl for the method being parsed.  If we're currently
3254   /// in a 'block', this returns the containing context.
3255   ObjCMethodDecl *getCurMethodDecl();
3256 
3257   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3258   /// or C function we're in, otherwise return null.  If we're currently
3259   /// in a 'block', this returns the containing context.
3260   NamedDecl *getCurFunctionOrMethodDecl();
3261 
3262   /// Add this decl to the scope shadowed decl chains.
3263   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3264 
3265   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3266   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3267   /// true if 'D' belongs to the given declaration context.
3268   ///
3269   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3270   ///        enclosing namespace set of the context, rather than contained
3271   ///        directly within it.
3272   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3273                      bool AllowInlineNamespace = false);
3274 
3275   /// Finds the scope corresponding to the given decl context, if it
3276   /// happens to be an enclosing scope.  Otherwise return NULL.
3277   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3278 
3279   /// Subroutines of ActOnDeclarator().
3280   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3281                                 TypeSourceInfo *TInfo);
3282   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3283 
3284   /// Describes the kind of merge to perform for availability
3285   /// attributes (including "deprecated", "unavailable", and "availability").
3286   enum AvailabilityMergeKind {
3287     /// Don't merge availability attributes at all.
3288     AMK_None,
3289     /// Merge availability attributes for a redeclaration, which requires
3290     /// an exact match.
3291     AMK_Redeclaration,
3292     /// Merge availability attributes for an override, which requires
3293     /// an exact match or a weakening of constraints.
3294     AMK_Override,
3295     /// Merge availability attributes for an implementation of
3296     /// a protocol requirement.
3297     AMK_ProtocolImplementation,
3298     /// Merge availability attributes for an implementation of
3299     /// an optional protocol requirement.
3300     AMK_OptionalProtocolImplementation
3301   };
3302 
3303   /// Describes the kind of priority given to an availability attribute.
3304   ///
3305   /// The sum of priorities deteremines the final priority of the attribute.
3306   /// The final priority determines how the attribute will be merged.
3307   /// An attribute with a lower priority will always remove higher priority
3308   /// attributes for the specified platform when it is being applied. An
3309   /// attribute with a higher priority will not be applied if the declaration
3310   /// already has an availability attribute with a lower priority for the
3311   /// specified platform. The final prirority values are not expected to match
3312   /// the values in this enumeration, but instead should be treated as a plain
3313   /// integer value. This enumeration just names the priority weights that are
3314   /// used to calculate that final vaue.
3315   enum AvailabilityPriority : int {
3316     /// The availability attribute was specified explicitly next to the
3317     /// declaration.
3318     AP_Explicit = 0,
3319 
3320     /// The availability attribute was applied using '#pragma clang attribute'.
3321     AP_PragmaClangAttribute = 1,
3322 
3323     /// The availability attribute for a specific platform was inferred from
3324     /// an availability attribute for another platform.
3325     AP_InferredFromOtherPlatform = 2
3326   };
3327 
3328   /// Attribute merging methods. Return true if a new attribute was added.
3329   AvailabilityAttr *
3330   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3331                         IdentifierInfo *Platform, bool Implicit,
3332                         VersionTuple Introduced, VersionTuple Deprecated,
3333                         VersionTuple Obsoleted, bool IsUnavailable,
3334                         StringRef Message, bool IsStrict, StringRef Replacement,
3335                         AvailabilityMergeKind AMK, int Priority);
3336   TypeVisibilityAttr *
3337   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3338                           TypeVisibilityAttr::VisibilityType Vis);
3339   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3340                                       VisibilityAttr::VisibilityType Vis);
3341   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3342                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3343   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3344   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3345   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3346                                             const AttributeCommonInfo &CI,
3347                                             bool BestCase,
3348                                             MSInheritanceModel Model);
3349   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3350                               IdentifierInfo *Format, int FormatIdx,
3351                               int FirstArg);
3352   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3353                                 StringRef Name);
3354   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3355                                 StringRef Name);
3356   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3357                                           const AttributeCommonInfo &CI,
3358                                           const IdentifierInfo *Ident);
3359   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3360   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3361                                     StringRef Name);
3362   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3363                                           const AttributeCommonInfo &CI);
3364   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3365   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3366                                                 const InternalLinkageAttr &AL);
3367   WebAssemblyImportNameAttr *mergeImportNameAttr(
3368       Decl *D, const WebAssemblyImportNameAttr &AL);
3369   WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3370       Decl *D, const WebAssemblyImportModuleAttr &AL);
3371   EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3372   EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3373                                               const EnforceTCBLeafAttr &AL);
3374 
3375   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3376                            AvailabilityMergeKind AMK = AMK_Redeclaration);
3377   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3378                             LookupResult &OldDecls);
3379   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3380                          bool MergeTypeWithOld);
3381   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3382                                     Scope *S, bool MergeTypeWithOld);
3383   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3384   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3385   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3386   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3387   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3388   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3389   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3390 
3391   // AssignmentAction - This is used by all the assignment diagnostic functions
3392   // to represent what is actually causing the operation
3393   enum AssignmentAction {
3394     AA_Assigning,
3395     AA_Passing,
3396     AA_Returning,
3397     AA_Converting,
3398     AA_Initializing,
3399     AA_Sending,
3400     AA_Casting,
3401     AA_Passing_CFAudited
3402   };
3403 
3404   /// C++ Overloading.
3405   enum OverloadKind {
3406     /// This is a legitimate overload: the existing declarations are
3407     /// functions or function templates with different signatures.
3408     Ovl_Overload,
3409 
3410     /// This is not an overload because the signature exactly matches
3411     /// an existing declaration.
3412     Ovl_Match,
3413 
3414     /// This is not an overload because the lookup results contain a
3415     /// non-function.
3416     Ovl_NonFunction
3417   };
3418   OverloadKind CheckOverload(Scope *S,
3419                              FunctionDecl *New,
3420                              const LookupResult &OldDecls,
3421                              NamedDecl *&OldDecl,
3422                              bool IsForUsingDecl);
3423   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3424                   bool ConsiderCudaAttrs = true,
3425                   bool ConsiderRequiresClauses = true);
3426 
3427   enum class AllowedExplicit {
3428     /// Allow no explicit functions to be used.
3429     None,
3430     /// Allow explicit conversion functions but not explicit constructors.
3431     Conversions,
3432     /// Allow both explicit conversion functions and explicit constructors.
3433     All
3434   };
3435 
3436   ImplicitConversionSequence
3437   TryImplicitConversion(Expr *From, QualType ToType,
3438                         bool SuppressUserConversions,
3439                         AllowedExplicit AllowExplicit,
3440                         bool InOverloadResolution,
3441                         bool CStyle,
3442                         bool AllowObjCWritebackConversion);
3443 
3444   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3445   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3446   bool IsComplexPromotion(QualType FromType, QualType ToType);
3447   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3448                            bool InOverloadResolution,
3449                            QualType& ConvertedType, bool &IncompatibleObjC);
3450   bool isObjCPointerConversion(QualType FromType, QualType ToType,
3451                                QualType& ConvertedType, bool &IncompatibleObjC);
3452   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3453                                  QualType &ConvertedType);
3454   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3455                                 QualType& ConvertedType);
3456   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3457                                   const FunctionProtoType *NewType,
3458                                   unsigned *ArgPos = nullptr);
3459   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3460                                   QualType FromType, QualType ToType);
3461 
3462   void maybeExtendBlockObject(ExprResult &E);
3463   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3464   bool CheckPointerConversion(Expr *From, QualType ToType,
3465                               CastKind &Kind,
3466                               CXXCastPath& BasePath,
3467                               bool IgnoreBaseAccess,
3468                               bool Diagnose = true);
3469   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3470                                  bool InOverloadResolution,
3471                                  QualType &ConvertedType);
3472   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3473                                     CastKind &Kind,
3474                                     CXXCastPath &BasePath,
3475                                     bool IgnoreBaseAccess);
3476   bool IsQualificationConversion(QualType FromType, QualType ToType,
3477                                  bool CStyle, bool &ObjCLifetimeConversion);
3478   bool IsFunctionConversion(QualType FromType, QualType ToType,
3479                             QualType &ResultTy);
3480   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3481   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3482 
3483   bool CanPerformAggregateInitializationForOverloadResolution(
3484       const InitializedEntity &Entity, InitListExpr *From);
3485 
3486   bool IsStringInit(Expr *Init, const ArrayType *AT);
3487 
3488   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3489                                     ExprResult Init);
3490   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3491                                        SourceLocation EqualLoc,
3492                                        ExprResult Init,
3493                                        bool TopLevelOfInitList = false,
3494                                        bool AllowExplicit = false);
3495   ExprResult PerformObjectArgumentInitialization(Expr *From,
3496                                                  NestedNameSpecifier *Qualifier,
3497                                                  NamedDecl *FoundDecl,
3498                                                  CXXMethodDecl *Method);
3499 
3500   /// Check that the lifetime of the initializer (and its subobjects) is
3501   /// sufficient for initializing the entity, and perform lifetime extension
3502   /// (when permitted) if not.
3503   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3504 
3505   ExprResult PerformContextuallyConvertToBool(Expr *From);
3506   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3507 
3508   /// Contexts in which a converted constant expression is required.
3509   enum CCEKind {
3510     CCEK_CaseValue,   ///< Expression in a case label.
3511     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
3512     CCEK_TemplateArg, ///< Value of a non-type template parameter.
3513     CCEK_ArrayBound,  ///< Array bound in array declarator or new-expression.
3514     CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3515   };
3516   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3517                                               llvm::APSInt &Value, CCEKind CCE);
3518   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3519                                               APValue &Value, CCEKind CCE,
3520                                               NamedDecl *Dest = nullptr);
3521 
3522   /// Abstract base class used to perform a contextual implicit
3523   /// conversion from an expression to any type passing a filter.
3524   class ContextualImplicitConverter {
3525   public:
3526     bool Suppress;
3527     bool SuppressConversion;
3528 
3529     ContextualImplicitConverter(bool Suppress = false,
3530                                 bool SuppressConversion = false)
Suppress(Suppress)3531         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3532 
3533     /// Determine whether the specified type is a valid destination type
3534     /// for this conversion.
3535     virtual bool match(QualType T) = 0;
3536 
3537     /// Emits a diagnostic complaining that the expression does not have
3538     /// integral or enumeration type.
3539     virtual SemaDiagnosticBuilder
3540     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3541 
3542     /// Emits a diagnostic when the expression has incomplete class type.
3543     virtual SemaDiagnosticBuilder
3544     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3545 
3546     /// Emits a diagnostic when the only matching conversion function
3547     /// is explicit.
3548     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3549         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3550 
3551     /// Emits a note for the explicit conversion function.
3552     virtual SemaDiagnosticBuilder
3553     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3554 
3555     /// Emits a diagnostic when there are multiple possible conversion
3556     /// functions.
3557     virtual SemaDiagnosticBuilder
3558     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3559 
3560     /// Emits a note for one of the candidate conversions.
3561     virtual SemaDiagnosticBuilder
3562     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3563 
3564     /// Emits a diagnostic when we picked a conversion function
3565     /// (for cases when we are not allowed to pick a conversion function).
3566     virtual SemaDiagnosticBuilder diagnoseConversion(
3567         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3568 
~ContextualImplicitConverter()3569     virtual ~ContextualImplicitConverter() {}
3570   };
3571 
3572   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3573     bool AllowScopedEnumerations;
3574 
3575   public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)3576     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3577                         bool Suppress, bool SuppressConversion)
3578         : ContextualImplicitConverter(Suppress, SuppressConversion),
3579           AllowScopedEnumerations(AllowScopedEnumerations) {}
3580 
3581     /// Match an integral or (possibly scoped) enumeration type.
3582     bool match(QualType T) override;
3583 
3584     SemaDiagnosticBuilder
diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)3585     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3586       return diagnoseNotInt(S, Loc, T);
3587     }
3588 
3589     /// Emits a diagnostic complaining that the expression does not have
3590     /// integral or enumeration type.
3591     virtual SemaDiagnosticBuilder
3592     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3593   };
3594 
3595   /// Perform a contextual implicit conversion.
3596   ExprResult PerformContextualImplicitConversion(
3597       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3598 
3599 
3600   enum ObjCSubscriptKind {
3601     OS_Array,
3602     OS_Dictionary,
3603     OS_Error
3604   };
3605   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3606 
3607   // Note that LK_String is intentionally after the other literals, as
3608   // this is used for diagnostics logic.
3609   enum ObjCLiteralKind {
3610     LK_Array,
3611     LK_Dictionary,
3612     LK_Numeric,
3613     LK_Boxed,
3614     LK_String,
3615     LK_Block,
3616     LK_None
3617   };
3618   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3619 
3620   ExprResult PerformObjectMemberConversion(Expr *From,
3621                                            NestedNameSpecifier *Qualifier,
3622                                            NamedDecl *FoundDecl,
3623                                            NamedDecl *Member);
3624 
3625   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3626   // TODO: make this is a typesafe union.
3627   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3628   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3629 
3630   using ADLCallKind = CallExpr::ADLCallKind;
3631 
3632   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3633                             ArrayRef<Expr *> Args,
3634                             OverloadCandidateSet &CandidateSet,
3635                             bool SuppressUserConversions = false,
3636                             bool PartialOverloading = false,
3637                             bool AllowExplicit = true,
3638                             bool AllowExplicitConversion = false,
3639                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3640                             ConversionSequenceList EarlyConversions = None,
3641                             OverloadCandidateParamOrder PO = {});
3642   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3643                       ArrayRef<Expr *> Args,
3644                       OverloadCandidateSet &CandidateSet,
3645                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3646                       bool SuppressUserConversions = false,
3647                       bool PartialOverloading = false,
3648                       bool FirstArgumentIsBase = false);
3649   void AddMethodCandidate(DeclAccessPair FoundDecl,
3650                           QualType ObjectType,
3651                           Expr::Classification ObjectClassification,
3652                           ArrayRef<Expr *> Args,
3653                           OverloadCandidateSet& CandidateSet,
3654                           bool SuppressUserConversion = false,
3655                           OverloadCandidateParamOrder PO = {});
3656   void AddMethodCandidate(CXXMethodDecl *Method,
3657                           DeclAccessPair FoundDecl,
3658                           CXXRecordDecl *ActingContext, QualType ObjectType,
3659                           Expr::Classification ObjectClassification,
3660                           ArrayRef<Expr *> Args,
3661                           OverloadCandidateSet& CandidateSet,
3662                           bool SuppressUserConversions = false,
3663                           bool PartialOverloading = false,
3664                           ConversionSequenceList EarlyConversions = None,
3665                           OverloadCandidateParamOrder PO = {});
3666   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3667                                   DeclAccessPair FoundDecl,
3668                                   CXXRecordDecl *ActingContext,
3669                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3670                                   QualType ObjectType,
3671                                   Expr::Classification ObjectClassification,
3672                                   ArrayRef<Expr *> Args,
3673                                   OverloadCandidateSet& CandidateSet,
3674                                   bool SuppressUserConversions = false,
3675                                   bool PartialOverloading = false,
3676                                   OverloadCandidateParamOrder PO = {});
3677   void AddTemplateOverloadCandidate(
3678       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3679       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3680       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3681       bool PartialOverloading = false, bool AllowExplicit = true,
3682       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3683       OverloadCandidateParamOrder PO = {});
3684   bool CheckNonDependentConversions(
3685       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3686       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3687       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3688       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3689       Expr::Classification ObjectClassification = {},
3690       OverloadCandidateParamOrder PO = {});
3691   void AddConversionCandidate(
3692       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3693       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3694       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3695       bool AllowExplicit, bool AllowResultConversion = true);
3696   void AddTemplateConversionCandidate(
3697       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3698       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3699       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3700       bool AllowExplicit, bool AllowResultConversion = true);
3701   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3702                              DeclAccessPair FoundDecl,
3703                              CXXRecordDecl *ActingContext,
3704                              const FunctionProtoType *Proto,
3705                              Expr *Object, ArrayRef<Expr *> Args,
3706                              OverloadCandidateSet& CandidateSet);
3707   void AddNonMemberOperatorCandidates(
3708       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3709       OverloadCandidateSet &CandidateSet,
3710       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3711   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3712                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3713                                    OverloadCandidateSet &CandidateSet,
3714                                    OverloadCandidateParamOrder PO = {});
3715   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3716                            OverloadCandidateSet& CandidateSet,
3717                            bool IsAssignmentOperator = false,
3718                            unsigned NumContextualBoolArguments = 0);
3719   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3720                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3721                                     OverloadCandidateSet& CandidateSet);
3722   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3723                                             SourceLocation Loc,
3724                                             ArrayRef<Expr *> Args,
3725                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3726                                             OverloadCandidateSet& CandidateSet,
3727                                             bool PartialOverloading = false);
3728 
3729   // Emit as a 'note' the specific overload candidate
3730   void NoteOverloadCandidate(
3731       NamedDecl *Found, FunctionDecl *Fn,
3732       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3733       QualType DestType = QualType(), bool TakingAddress = false);
3734 
3735   // Emit as a series of 'note's all template and non-templates identified by
3736   // the expression Expr
3737   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3738                                  bool TakingAddress = false);
3739 
3740   /// Check the enable_if expressions on the given function. Returns the first
3741   /// failing attribute, or NULL if they were all successful.
3742   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3743                               ArrayRef<Expr *> Args,
3744                               bool MissingImplicitThis = false);
3745 
3746   /// Find the failed Boolean condition within a given Boolean
3747   /// constant expression, and describe it with a string.
3748   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3749 
3750   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3751   /// non-ArgDependent DiagnoseIfAttrs.
3752   ///
3753   /// Argument-dependent diagnose_if attributes should be checked each time a
3754   /// function is used as a direct callee of a function call.
3755   ///
3756   /// Returns true if any errors were emitted.
3757   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3758                                            const Expr *ThisArg,
3759                                            ArrayRef<const Expr *> Args,
3760                                            SourceLocation Loc);
3761 
3762   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3763   /// ArgDependent DiagnoseIfAttrs.
3764   ///
3765   /// Argument-independent diagnose_if attributes should be checked on every use
3766   /// of a function.
3767   ///
3768   /// Returns true if any errors were emitted.
3769   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3770                                              SourceLocation Loc);
3771 
3772   /// Returns whether the given function's address can be taken or not,
3773   /// optionally emitting a diagnostic if the address can't be taken.
3774   ///
3775   /// Returns false if taking the address of the function is illegal.
3776   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3777                                          bool Complain = false,
3778                                          SourceLocation Loc = SourceLocation());
3779 
3780   // [PossiblyAFunctionType]  -->   [Return]
3781   // NonFunctionType --> NonFunctionType
3782   // R (A) --> R(A)
3783   // R (*)(A) --> R (A)
3784   // R (&)(A) --> R (A)
3785   // R (S::*)(A) --> R (A)
3786   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3787 
3788   FunctionDecl *
3789   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3790                                      QualType TargetType,
3791                                      bool Complain,
3792                                      DeclAccessPair &Found,
3793                                      bool *pHadMultipleCandidates = nullptr);
3794 
3795   FunctionDecl *
3796   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3797 
3798   bool resolveAndFixAddressOfSingleOverloadCandidate(
3799       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3800 
3801   FunctionDecl *
3802   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3803                                               bool Complain = false,
3804                                               DeclAccessPair *Found = nullptr);
3805 
3806   bool ResolveAndFixSingleFunctionTemplateSpecialization(
3807                       ExprResult &SrcExpr,
3808                       bool DoFunctionPointerConverion = false,
3809                       bool Complain = false,
3810                       SourceRange OpRangeForComplaining = SourceRange(),
3811                       QualType DestTypeForComplaining = QualType(),
3812                       unsigned DiagIDForComplaining = 0);
3813 
3814 
3815   Expr *FixOverloadedFunctionReference(Expr *E,
3816                                        DeclAccessPair FoundDecl,
3817                                        FunctionDecl *Fn);
3818   ExprResult FixOverloadedFunctionReference(ExprResult,
3819                                             DeclAccessPair FoundDecl,
3820                                             FunctionDecl *Fn);
3821 
3822   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3823                                    ArrayRef<Expr *> Args,
3824                                    OverloadCandidateSet &CandidateSet,
3825                                    bool PartialOverloading = false);
3826   void AddOverloadedCallCandidates(
3827       LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3828       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3829 
3830   // An enum used to represent the different possible results of building a
3831   // range-based for loop.
3832   enum ForRangeStatus {
3833     FRS_Success,
3834     FRS_NoViableFunction,
3835     FRS_DiagnosticIssued
3836   };
3837 
3838   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3839                                            SourceLocation RangeLoc,
3840                                            const DeclarationNameInfo &NameInfo,
3841                                            LookupResult &MemberLookup,
3842                                            OverloadCandidateSet *CandidateSet,
3843                                            Expr *Range, ExprResult *CallExpr);
3844 
3845   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3846                                      UnresolvedLookupExpr *ULE,
3847                                      SourceLocation LParenLoc,
3848                                      MultiExprArg Args,
3849                                      SourceLocation RParenLoc,
3850                                      Expr *ExecConfig,
3851                                      bool AllowTypoCorrection=true,
3852                                      bool CalleesAddressIsTaken=false);
3853 
3854   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3855                               MultiExprArg Args, SourceLocation RParenLoc,
3856                               OverloadCandidateSet *CandidateSet,
3857                               ExprResult *Result);
3858 
3859   ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
3860                                         NestedNameSpecifierLoc NNSLoc,
3861                                         DeclarationNameInfo DNI,
3862                                         const UnresolvedSetImpl &Fns,
3863                                         bool PerformADL = true);
3864 
3865   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3866                                      UnaryOperatorKind Opc,
3867                                      const UnresolvedSetImpl &Fns,
3868                                      Expr *input, bool RequiresADL = true);
3869 
3870   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3871                              OverloadedOperatorKind Op,
3872                              const UnresolvedSetImpl &Fns,
3873                              ArrayRef<Expr *> Args, bool RequiresADL = true);
3874   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3875                                    BinaryOperatorKind Opc,
3876                                    const UnresolvedSetImpl &Fns,
3877                                    Expr *LHS, Expr *RHS,
3878                                    bool RequiresADL = true,
3879                                    bool AllowRewrittenCandidates = true,
3880                                    FunctionDecl *DefaultedFn = nullptr);
3881   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3882                                                 const UnresolvedSetImpl &Fns,
3883                                                 Expr *LHS, Expr *RHS,
3884                                                 FunctionDecl *DefaultedFn);
3885 
3886   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3887                                                 SourceLocation RLoc,
3888                                                 Expr *Base,Expr *Idx);
3889 
3890   ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3891                                        SourceLocation LParenLoc,
3892                                        MultiExprArg Args,
3893                                        SourceLocation RParenLoc,
3894                                        bool AllowRecovery = false);
3895   ExprResult
3896   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3897                                MultiExprArg Args,
3898                                SourceLocation RParenLoc);
3899 
3900   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3901                                       SourceLocation OpLoc,
3902                                       bool *NoArrowOperatorFound = nullptr);
3903 
3904   /// CheckCallReturnType - Checks that a call expression's return type is
3905   /// complete. Returns true on failure. The location passed in is the location
3906   /// that best represents the call.
3907   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3908                            CallExpr *CE, FunctionDecl *FD);
3909 
3910   /// Helpers for dealing with blocks and functions.
3911   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3912                                 bool CheckParameterNames);
3913   void CheckCXXDefaultArguments(FunctionDecl *FD);
3914   void CheckExtraCXXDefaultArguments(Declarator &D);
3915   Scope *getNonFieldDeclScope(Scope *S);
3916 
3917   /// \name Name lookup
3918   ///
3919   /// These routines provide name lookup that is used during semantic
3920   /// analysis to resolve the various kinds of names (identifiers,
3921   /// overloaded operator names, constructor names, etc.) into zero or
3922   /// more declarations within a particular scope. The major entry
3923   /// points are LookupName, which performs unqualified name lookup,
3924   /// and LookupQualifiedName, which performs qualified name lookup.
3925   ///
3926   /// All name lookup is performed based on some specific criteria,
3927   /// which specify what names will be visible to name lookup and how
3928   /// far name lookup should work. These criteria are important both
3929   /// for capturing language semantics (certain lookups will ignore
3930   /// certain names, for example) and for performance, since name
3931   /// lookup is often a bottleneck in the compilation of C++. Name
3932   /// lookup criteria is specified via the LookupCriteria enumeration.
3933   ///
3934   /// The results of name lookup can vary based on the kind of name
3935   /// lookup performed, the current language, and the translation
3936   /// unit. In C, for example, name lookup will either return nothing
3937   /// (no entity found) or a single declaration. In C++, name lookup
3938   /// can additionally refer to a set of overloaded functions or
3939   /// result in an ambiguity. All of the possible results of name
3940   /// lookup are captured by the LookupResult class, which provides
3941   /// the ability to distinguish among them.
3942   //@{
3943 
3944   /// Describes the kind of name lookup to perform.
3945   enum LookupNameKind {
3946     /// Ordinary name lookup, which finds ordinary names (functions,
3947     /// variables, typedefs, etc.) in C and most kinds of names
3948     /// (functions, variables, members, types, etc.) in C++.
3949     LookupOrdinaryName = 0,
3950     /// Tag name lookup, which finds the names of enums, classes,
3951     /// structs, and unions.
3952     LookupTagName,
3953     /// Label name lookup.
3954     LookupLabel,
3955     /// Member name lookup, which finds the names of
3956     /// class/struct/union members.
3957     LookupMemberName,
3958     /// Look up of an operator name (e.g., operator+) for use with
3959     /// operator overloading. This lookup is similar to ordinary name
3960     /// lookup, but will ignore any declarations that are class members.
3961     LookupOperatorName,
3962     /// Look up a name following ~ in a destructor name. This is an ordinary
3963     /// lookup, but prefers tags to typedefs.
3964     LookupDestructorName,
3965     /// Look up of a name that precedes the '::' scope resolution
3966     /// operator in C++. This lookup completely ignores operator, object,
3967     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3968     LookupNestedNameSpecifierName,
3969     /// Look up a namespace name within a C++ using directive or
3970     /// namespace alias definition, ignoring non-namespace names (C++
3971     /// [basic.lookup.udir]p1).
3972     LookupNamespaceName,
3973     /// Look up all declarations in a scope with the given name,
3974     /// including resolved using declarations.  This is appropriate
3975     /// for checking redeclarations for a using declaration.
3976     LookupUsingDeclName,
3977     /// Look up an ordinary name that is going to be redeclared as a
3978     /// name with linkage. This lookup ignores any declarations that
3979     /// are outside of the current scope unless they have linkage. See
3980     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3981     LookupRedeclarationWithLinkage,
3982     /// Look up a friend of a local class. This lookup does not look
3983     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3984     LookupLocalFriendName,
3985     /// Look up the name of an Objective-C protocol.
3986     LookupObjCProtocolName,
3987     /// Look up implicit 'self' parameter of an objective-c method.
3988     LookupObjCImplicitSelfParam,
3989     /// Look up the name of an OpenMP user-defined reduction operation.
3990     LookupOMPReductionName,
3991     /// Look up the name of an OpenMP user-defined mapper.
3992     LookupOMPMapperName,
3993     /// Look up any declaration with any name.
3994     LookupAnyName
3995   };
3996 
3997   /// Specifies whether (or how) name lookup is being performed for a
3998   /// redeclaration (vs. a reference).
3999   enum RedeclarationKind {
4000     /// The lookup is a reference to this name that is not for the
4001     /// purpose of redeclaring the name.
4002     NotForRedeclaration = 0,
4003     /// The lookup results will be used for redeclaration of a name,
4004     /// if an entity by that name already exists and is visible.
4005     ForVisibleRedeclaration,
4006     /// The lookup results will be used for redeclaration of a name
4007     /// with external linkage; non-visible lookup results with external linkage
4008     /// may also be found.
4009     ForExternalRedeclaration
4010   };
4011 
forRedeclarationInCurContext()4012   RedeclarationKind forRedeclarationInCurContext() {
4013     // A declaration with an owning module for linkage can never link against
4014     // anything that is not visible. We don't need to check linkage here; if
4015     // the context has internal linkage, redeclaration lookup won't find things
4016     // from other TUs, and we can't safely compute linkage yet in general.
4017     if (cast<Decl>(CurContext)
4018             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4019       return ForVisibleRedeclaration;
4020     return ForExternalRedeclaration;
4021   }
4022 
4023   /// The possible outcomes of name lookup for a literal operator.
4024   enum LiteralOperatorLookupResult {
4025     /// The lookup resulted in an error.
4026     LOLR_Error,
4027     /// The lookup found no match but no diagnostic was issued.
4028     LOLR_ErrorNoDiagnostic,
4029     /// The lookup found a single 'cooked' literal operator, which
4030     /// expects a normal literal to be built and passed to it.
4031     LOLR_Cooked,
4032     /// The lookup found a single 'raw' literal operator, which expects
4033     /// a string literal containing the spelling of the literal token.
4034     LOLR_Raw,
4035     /// The lookup found an overload set of literal operator templates,
4036     /// which expect the characters of the spelling of the literal token to be
4037     /// passed as a non-type template argument pack.
4038     LOLR_Template,
4039     /// The lookup found an overload set of literal operator templates,
4040     /// which expect the character type and characters of the spelling of the
4041     /// string literal token to be passed as template arguments.
4042     LOLR_StringTemplatePack,
4043   };
4044 
4045   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4046                                                   CXXSpecialMember SM,
4047                                                   bool ConstArg,
4048                                                   bool VolatileArg,
4049                                                   bool RValueThis,
4050                                                   bool ConstThis,
4051                                                   bool VolatileThis);
4052 
4053   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4054   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4055       TypoRecoveryCallback;
4056 
4057 private:
4058   bool CppLookupName(LookupResult &R, Scope *S);
4059 
4060   struct TypoExprState {
4061     std::unique_ptr<TypoCorrectionConsumer> Consumer;
4062     TypoDiagnosticGenerator DiagHandler;
4063     TypoRecoveryCallback RecoveryHandler;
4064     TypoExprState();
4065     TypoExprState(TypoExprState &&other) noexcept;
4066     TypoExprState &operator=(TypoExprState &&other) noexcept;
4067   };
4068 
4069   /// The set of unhandled TypoExprs and their associated state.
4070   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4071 
4072   /// Creates a new TypoExpr AST node.
4073   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4074                               TypoDiagnosticGenerator TDG,
4075                               TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4076 
4077   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4078   //
4079   // The boolean value will be true to indicate that the namespace was loaded
4080   // from an AST/PCH file, or false otherwise.
4081   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4082 
4083   /// Whether we have already loaded known namespaces from an extenal
4084   /// source.
4085   bool LoadedExternalKnownNamespaces;
4086 
4087   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4088   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4089   /// should be skipped entirely.
4090   std::unique_ptr<TypoCorrectionConsumer>
4091   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4092                              Sema::LookupNameKind LookupKind, Scope *S,
4093                              CXXScopeSpec *SS,
4094                              CorrectionCandidateCallback &CCC,
4095                              DeclContext *MemberContext, bool EnteringContext,
4096                              const ObjCObjectPointerType *OPT,
4097                              bool ErrorRecovery);
4098 
4099 public:
4100   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4101 
4102   /// Clears the state of the given TypoExpr.
4103   void clearDelayedTypo(TypoExpr *TE);
4104 
4105   /// Look up a name, looking for a single declaration.  Return
4106   /// null if the results were absent, ambiguous, or overloaded.
4107   ///
4108   /// It is preferable to use the elaborated form and explicitly handle
4109   /// ambiguity and overloaded.
4110   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4111                               SourceLocation Loc,
4112                               LookupNameKind NameKind,
4113                               RedeclarationKind Redecl
4114                                 = NotForRedeclaration);
4115   bool LookupBuiltin(LookupResult &R);
4116   void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4117   bool LookupName(LookupResult &R, Scope *S,
4118                   bool AllowBuiltinCreation = false);
4119   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4120                            bool InUnqualifiedLookup = false);
4121   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4122                            CXXScopeSpec &SS);
4123   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4124                         bool AllowBuiltinCreation = false,
4125                         bool EnteringContext = false);
4126   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4127                                    RedeclarationKind Redecl
4128                                      = NotForRedeclaration);
4129   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4130 
4131   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4132                                     UnresolvedSetImpl &Functions);
4133 
4134   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4135                                  SourceLocation GnuLabelLoc = SourceLocation());
4136 
4137   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4138   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4139   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4140                                                unsigned Quals);
4141   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4142                                          bool RValueThis, unsigned ThisQuals);
4143   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4144                                               unsigned Quals);
4145   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4146                                         bool RValueThis, unsigned ThisQuals);
4147   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4148 
4149   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4150                               bool IsUDSuffix);
4151   LiteralOperatorLookupResult
4152   LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4153                         bool AllowRaw, bool AllowTemplate,
4154                         bool AllowStringTemplate, bool DiagnoseMissing,
4155                         StringLiteral *StringLit = nullptr);
4156   bool isKnownName(StringRef name);
4157 
4158   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4159   enum class FunctionEmissionStatus {
4160     Emitted,
4161     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
4162     OMPDiscarded,      // Discarded due to OpenMP hostness
4163     TemplateDiscarded, // Discarded due to uninstantiated templates
4164     Unknown,
4165   };
4166   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4167                                            bool Final = false);
4168 
4169   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4170   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4171 
4172   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4173                                ArrayRef<Expr *> Args, ADLResult &Functions);
4174 
4175   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4176                           VisibleDeclConsumer &Consumer,
4177                           bool IncludeGlobalScope = true,
4178                           bool LoadExternal = true);
4179   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4180                           VisibleDeclConsumer &Consumer,
4181                           bool IncludeGlobalScope = true,
4182                           bool IncludeDependentBases = false,
4183                           bool LoadExternal = true);
4184 
4185   enum CorrectTypoKind {
4186     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
4187     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4188   };
4189 
4190   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4191                              Sema::LookupNameKind LookupKind,
4192                              Scope *S, CXXScopeSpec *SS,
4193                              CorrectionCandidateCallback &CCC,
4194                              CorrectTypoKind Mode,
4195                              DeclContext *MemberContext = nullptr,
4196                              bool EnteringContext = false,
4197                              const ObjCObjectPointerType *OPT = nullptr,
4198                              bool RecordFailure = true);
4199 
4200   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4201                                Sema::LookupNameKind LookupKind, Scope *S,
4202                                CXXScopeSpec *SS,
4203                                CorrectionCandidateCallback &CCC,
4204                                TypoDiagnosticGenerator TDG,
4205                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4206                                DeclContext *MemberContext = nullptr,
4207                                bool EnteringContext = false,
4208                                const ObjCObjectPointerType *OPT = nullptr);
4209 
4210   /// Process any TypoExprs in the given Expr and its children,
4211   /// generating diagnostics as appropriate and returning a new Expr if there
4212   /// were typos that were all successfully corrected and ExprError if one or
4213   /// more typos could not be corrected.
4214   ///
4215   /// \param E The Expr to check for TypoExprs.
4216   ///
4217   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4218   /// initializer.
4219   ///
4220   /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4221   /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4222   ///
4223   /// \param Filter A function applied to a newly rebuilt Expr to determine if
4224   /// it is an acceptable/usable result from a single combination of typo
4225   /// corrections. As long as the filter returns ExprError, different
4226   /// combinations of corrections will be tried until all are exhausted.
4227   ExprResult CorrectDelayedTyposInExpr(
4228       Expr *E, VarDecl *InitDecl = nullptr,
4229       bool RecoverUncorrectedTypos = false,
4230       llvm::function_ref<ExprResult(Expr *)> Filter =
4231           [](Expr *E) -> ExprResult { return E; });
4232 
4233   ExprResult CorrectDelayedTyposInExpr(
4234       ExprResult ER, VarDecl *InitDecl = nullptr,
4235       bool RecoverUncorrectedTypos = false,
4236       llvm::function_ref<ExprResult(Expr *)> Filter =
4237           [](Expr *E) -> ExprResult { return E; }) {
4238     return ER.isInvalid()
4239                ? ER
4240                : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4241                                            RecoverUncorrectedTypos, Filter);
4242   }
4243 
4244   void diagnoseTypo(const TypoCorrection &Correction,
4245                     const PartialDiagnostic &TypoDiag,
4246                     bool ErrorRecovery = true);
4247 
4248   void diagnoseTypo(const TypoCorrection &Correction,
4249                     const PartialDiagnostic &TypoDiag,
4250                     const PartialDiagnostic &PrevNote,
4251                     bool ErrorRecovery = true);
4252 
4253   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4254 
4255   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4256                                           ArrayRef<Expr *> Args,
4257                                    AssociatedNamespaceSet &AssociatedNamespaces,
4258                                    AssociatedClassSet &AssociatedClasses);
4259 
4260   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4261                             bool ConsiderLinkage, bool AllowInlineNamespace);
4262 
4263   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4264 
4265   void DiagnoseAmbiguousLookup(LookupResult &Result);
4266   //@}
4267 
4268   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4269   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4270                                 ArrayRef<Expr *> SubExprs,
4271                                 QualType T = QualType());
4272 
4273   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4274                                           SourceLocation IdLoc,
4275                                           bool TypoCorrection = false);
4276   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4277                               SourceLocation Loc);
4278   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4279                                  Scope *S, bool ForRedeclaration,
4280                                  SourceLocation Loc);
4281   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4282                                       Scope *S);
4283   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4284       FunctionDecl *FD);
4285   void AddKnownFunctionAttributes(FunctionDecl *FD);
4286 
4287   // More parsing and symbol table subroutines.
4288 
4289   void ProcessPragmaWeak(Scope *S, Decl *D);
4290   // Decl attributes - this routine is the top level dispatcher.
4291   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4292   // Helper for delayed processing of attributes.
4293   void ProcessDeclAttributeDelayed(Decl *D,
4294                                    const ParsedAttributesView &AttrList);
4295   void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4296                              bool IncludeCXX11Attributes = true);
4297   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4298                                    const ParsedAttributesView &AttrList);
4299 
4300   void checkUnusedDeclAttributes(Declarator &D);
4301 
4302   /// Handles semantic checking for features that are common to all attributes,
4303   /// such as checking whether a parameter was properly specified, or the
4304   /// correct number of arguments were passed, etc. Returns true if the
4305   /// attribute has been diagnosed.
4306   bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A);
4307   bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A);
4308 
4309   /// Determine if type T is a valid subject for a nonnull and similar
4310   /// attributes. By default, we look through references (the behavior used by
4311   /// nonnull), but if the second parameter is true, then we treat a reference
4312   /// type as valid.
4313   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4314 
4315   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4316   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4317                             const FunctionDecl *FD = nullptr);
4318   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4319   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4320   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4321                                       StringRef &Str,
4322                                       SourceLocation *ArgLocation = nullptr);
4323   llvm::Error isValidSectionSpecifier(StringRef Str);
4324   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4325   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4326   bool checkMSInheritanceAttrOnDefinition(
4327       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4328       MSInheritanceModel SemanticSpelling);
4329 
4330   void CheckAlignasUnderalignment(Decl *D);
4331 
4332   /// Adjust the calling convention of a method to be the ABI default if it
4333   /// wasn't specified explicitly.  This handles method types formed from
4334   /// function type typedefs and typename template arguments.
4335   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4336                               SourceLocation Loc);
4337 
4338   // Check if there is an explicit attribute, but only look through parens.
4339   // The intent is to look for an attribute on the current declarator, but not
4340   // one that came from a typedef.
4341   bool hasExplicitCallingConv(QualType T);
4342 
4343   /// Get the outermost AttributedType node that sets a calling convention.
4344   /// Valid types should not have multiple attributes with different CCs.
4345   const AttributedType *getCallingConvAttributedType(QualType T) const;
4346 
4347   /// Process the attributes before creating an attributed statement. Returns
4348   /// the semantic attributes that have been processed.
4349   void ProcessStmtAttributes(Stmt *Stmt,
4350                              const ParsedAttributesWithRange &InAttrs,
4351                              SmallVectorImpl<const Attr *> &OutAttrs);
4352 
4353   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4354                                    ObjCMethodDecl *MethodDecl,
4355                                    bool IsProtocolMethodDecl);
4356 
4357   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4358                                    ObjCMethodDecl *Overridden,
4359                                    bool IsProtocolMethodDecl);
4360 
4361   /// WarnExactTypedMethods - This routine issues a warning if method
4362   /// implementation declaration matches exactly that of its declaration.
4363   void WarnExactTypedMethods(ObjCMethodDecl *Method,
4364                              ObjCMethodDecl *MethodDecl,
4365                              bool IsProtocolMethodDecl);
4366 
4367   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4368 
4369   /// CheckImplementationIvars - This routine checks if the instance variables
4370   /// listed in the implelementation match those listed in the interface.
4371   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4372                                 ObjCIvarDecl **Fields, unsigned nIvars,
4373                                 SourceLocation Loc);
4374 
4375   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4376   /// remains unimplemented in the class or category \@implementation.
4377   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4378                                  ObjCContainerDecl* IDecl,
4379                                  bool IncompleteImpl = false);
4380 
4381   /// DiagnoseUnimplementedProperties - This routine warns on those properties
4382   /// which must be implemented by this implementation.
4383   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4384                                        ObjCContainerDecl *CDecl,
4385                                        bool SynthesizeProperties);
4386 
4387   /// Diagnose any null-resettable synthesized setters.
4388   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4389 
4390   /// DefaultSynthesizeProperties - This routine default synthesizes all
4391   /// properties which must be synthesized in the class's \@implementation.
4392   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4393                                    ObjCInterfaceDecl *IDecl,
4394                                    SourceLocation AtEnd);
4395   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4396 
4397   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4398   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4399   /// declared in class 'IFace'.
4400   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4401                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4402 
4403   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4404   /// backs the property is not used in the property's accessor.
4405   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4406                                            const ObjCImplementationDecl *ImplD);
4407 
4408   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4409   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4410   /// It also returns ivar's property on success.
4411   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4412                                                const ObjCPropertyDecl *&PDecl) const;
4413 
4414   /// Called by ActOnProperty to handle \@property declarations in
4415   /// class extensions.
4416   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4417                       SourceLocation AtLoc,
4418                       SourceLocation LParenLoc,
4419                       FieldDeclarator &FD,
4420                       Selector GetterSel,
4421                       SourceLocation GetterNameLoc,
4422                       Selector SetterSel,
4423                       SourceLocation SetterNameLoc,
4424                       const bool isReadWrite,
4425                       unsigned &Attributes,
4426                       const unsigned AttributesAsWritten,
4427                       QualType T,
4428                       TypeSourceInfo *TSI,
4429                       tok::ObjCKeywordKind MethodImplKind);
4430 
4431   /// Called by ActOnProperty and HandlePropertyInClassExtension to
4432   /// handle creating the ObjcPropertyDecl for a category or \@interface.
4433   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4434                                        ObjCContainerDecl *CDecl,
4435                                        SourceLocation AtLoc,
4436                                        SourceLocation LParenLoc,
4437                                        FieldDeclarator &FD,
4438                                        Selector GetterSel,
4439                                        SourceLocation GetterNameLoc,
4440                                        Selector SetterSel,
4441                                        SourceLocation SetterNameLoc,
4442                                        const bool isReadWrite,
4443                                        const unsigned Attributes,
4444                                        const unsigned AttributesAsWritten,
4445                                        QualType T,
4446                                        TypeSourceInfo *TSI,
4447                                        tok::ObjCKeywordKind MethodImplKind,
4448                                        DeclContext *lexicalDC = nullptr);
4449 
4450   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4451   /// warning) when atomic property has one but not the other user-declared
4452   /// setter or getter.
4453   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4454                                        ObjCInterfaceDecl* IDecl);
4455 
4456   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4457 
4458   void DiagnoseMissingDesignatedInitOverrides(
4459                                           const ObjCImplementationDecl *ImplD,
4460                                           const ObjCInterfaceDecl *IFD);
4461 
4462   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4463 
4464   enum MethodMatchStrategy {
4465     MMS_loose,
4466     MMS_strict
4467   };
4468 
4469   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4470   /// true, or false, accordingly.
4471   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4472                                   const ObjCMethodDecl *PrevMethod,
4473                                   MethodMatchStrategy strategy = MMS_strict);
4474 
4475   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4476   /// or protocol against those declared in their implementations.
4477   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4478                                   const SelectorSet &ClsMap,
4479                                   SelectorSet &InsMapSeen,
4480                                   SelectorSet &ClsMapSeen,
4481                                   ObjCImplDecl* IMPDecl,
4482                                   ObjCContainerDecl* IDecl,
4483                                   bool &IncompleteImpl,
4484                                   bool ImmediateClass,
4485                                   bool WarnCategoryMethodImpl=false);
4486 
4487   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4488   /// category matches with those implemented in its primary class and
4489   /// warns each time an exact match is found.
4490   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4491 
4492   /// Add the given method to the list of globally-known methods.
4493   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4494 
4495   /// Returns default addr space for method qualifiers.
4496   LangAS getDefaultCXXMethodAddrSpace() const;
4497 
4498 private:
4499   /// AddMethodToGlobalPool - Add an instance or factory method to the global
4500   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4501   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4502 
4503   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4504   /// optionally warns if there are multiple signatures.
4505   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4506                                            bool receiverIdOrClass,
4507                                            bool instance);
4508 
4509 public:
4510   /// - Returns instance or factory methods in global method pool for
4511   /// given selector. It checks the desired kind first, if none is found, and
4512   /// parameter checkTheOther is set, it then checks the other kind. If no such
4513   /// method or only one method is found, function returns false; otherwise, it
4514   /// returns true.
4515   bool
4516   CollectMultipleMethodsInGlobalPool(Selector Sel,
4517                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4518                                      bool InstanceFirst, bool CheckTheOther,
4519                                      const ObjCObjectType *TypeBound = nullptr);
4520 
4521   bool
4522   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4523                                  SourceRange R, bool receiverIdOrClass,
4524                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4525 
4526   void
4527   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4528                                      Selector Sel, SourceRange R,
4529                                      bool receiverIdOrClass);
4530 
4531 private:
4532   /// - Returns a selector which best matches given argument list or
4533   /// nullptr if none could be found
4534   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4535                                    bool IsInstance,
4536                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4537 
4538 
4539   /// Record the typo correction failure and return an empty correction.
4540   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4541                                   bool RecordFailure = true) {
4542     if (RecordFailure)
4543       TypoCorrectionFailures[Typo].insert(TypoLoc);
4544     return TypoCorrection();
4545   }
4546 
4547 public:
4548   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4549   /// unit are added to a global pool. This allows us to efficiently associate
4550   /// a selector with a method declaraation for purposes of typechecking
4551   /// messages sent to "id" (where the class of the object is unknown).
4552   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4553     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4554   }
4555 
4556   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4557   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4558     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4559   }
4560 
4561   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4562   /// pool.
4563   void AddAnyMethodToGlobalPool(Decl *D);
4564 
4565   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4566   /// there are multiple signatures.
4567   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4568                                                    bool receiverIdOrClass=false) {
4569     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4570                                     /*instance*/true);
4571   }
4572 
4573   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4574   /// there are multiple signatures.
4575   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4576                                                   bool receiverIdOrClass=false) {
4577     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4578                                     /*instance*/false);
4579   }
4580 
4581   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4582                               QualType ObjectType=QualType());
4583   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4584   /// implementation.
4585   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4586 
4587   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4588   /// initialization.
4589   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4590                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4591 
4592   //===--------------------------------------------------------------------===//
4593   // Statement Parsing Callbacks: SemaStmt.cpp.
4594 public:
4595   class FullExprArg {
4596   public:
FullExprArg()4597     FullExprArg() : E(nullptr) { }
FullExprArg(Sema & actions)4598     FullExprArg(Sema &actions) : E(nullptr) { }
4599 
release()4600     ExprResult release() {
4601       return E;
4602     }
4603 
get()4604     Expr *get() const { return E; }
4605 
4606     Expr *operator->() {
4607       return E;
4608     }
4609 
4610   private:
4611     // FIXME: No need to make the entire Sema class a friend when it's just
4612     // Sema::MakeFullExpr that needs access to the constructor below.
4613     friend class Sema;
4614 
FullExprArg(Expr * expr)4615     explicit FullExprArg(Expr *expr) : E(expr) {}
4616 
4617     Expr *E;
4618   };
4619 
MakeFullExpr(Expr * Arg)4620   FullExprArg MakeFullExpr(Expr *Arg) {
4621     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4622   }
MakeFullExpr(Expr * Arg,SourceLocation CC)4623   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4624     return FullExprArg(
4625         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4626   }
MakeFullDiscardedValueExpr(Expr * Arg)4627   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4628     ExprResult FE =
4629         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4630                             /*DiscardedValue*/ true);
4631     return FullExprArg(FE.get());
4632   }
4633 
4634   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4635   StmtResult ActOnExprStmtError();
4636 
4637   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4638                            bool HasLeadingEmptyMacro = false);
4639 
4640   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4641   void ActOnAfterCompoundStatementLeadingPragmas();
4642   void ActOnFinishOfCompoundStmt();
4643   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4644                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4645 
4646   /// A RAII object to enter scope of a compound statement.
4647   class CompoundScopeRAII {
4648   public:
S(S)4649     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4650       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4651     }
4652 
~CompoundScopeRAII()4653     ~CompoundScopeRAII() {
4654       S.ActOnFinishOfCompoundStmt();
4655     }
4656 
4657   private:
4658     Sema &S;
4659   };
4660 
4661   /// An RAII helper that pops function a function scope on exit.
4662   struct FunctionScopeRAII {
4663     Sema &S;
4664     bool Active;
FunctionScopeRAIIFunctionScopeRAII4665     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAIIFunctionScopeRAII4666     ~FunctionScopeRAII() {
4667       if (Active)
4668         S.PopFunctionScopeInfo();
4669     }
disableFunctionScopeRAII4670     void disable() { Active = false; }
4671   };
4672 
4673   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4674                                    SourceLocation StartLoc,
4675                                    SourceLocation EndLoc);
4676   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4677   StmtResult ActOnForEachLValueExpr(Expr *E);
4678   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4679   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4680                            SourceLocation DotDotDotLoc, ExprResult RHS,
4681                            SourceLocation ColonLoc);
4682   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4683 
4684   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4685                                       SourceLocation ColonLoc,
4686                                       Stmt *SubStmt, Scope *CurScope);
4687   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4688                             SourceLocation ColonLoc, Stmt *SubStmt);
4689 
4690   StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
4691                                  ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
4692   StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList,
4693                                  Stmt *SubStmt);
4694 
4695   class ConditionResult;
4696   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4697                          SourceLocation LParenLoc, Stmt *InitStmt,
4698                          ConditionResult Cond, SourceLocation RParenLoc,
4699                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4700   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4701                          SourceLocation LParenLoc, Stmt *InitStmt,
4702                          ConditionResult Cond, SourceLocation RParenLoc,
4703                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4704   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4705                                     SourceLocation LParenLoc, Stmt *InitStmt,
4706                                     ConditionResult Cond,
4707                                     SourceLocation RParenLoc);
4708   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4709                                            Stmt *Switch, Stmt *Body);
4710   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4711                             ConditionResult Cond, SourceLocation RParenLoc,
4712                             Stmt *Body);
4713   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4714                          SourceLocation WhileLoc, SourceLocation CondLParen,
4715                          Expr *Cond, SourceLocation CondRParen);
4716 
4717   StmtResult ActOnForStmt(SourceLocation ForLoc,
4718                           SourceLocation LParenLoc,
4719                           Stmt *First,
4720                           ConditionResult Second,
4721                           FullExprArg Third,
4722                           SourceLocation RParenLoc,
4723                           Stmt *Body);
4724   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4725                                            Expr *collection);
4726   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4727                                         Stmt *First, Expr *collection,
4728                                         SourceLocation RParenLoc);
4729   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4730 
4731   enum BuildForRangeKind {
4732     /// Initial building of a for-range statement.
4733     BFRK_Build,
4734     /// Instantiation or recovery rebuild of a for-range statement. Don't
4735     /// attempt any typo-correction.
4736     BFRK_Rebuild,
4737     /// Determining whether a for-range statement could be built. Avoid any
4738     /// unnecessary or irreversible actions.
4739     BFRK_Check
4740   };
4741 
4742   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4743                                   SourceLocation CoawaitLoc,
4744                                   Stmt *InitStmt,
4745                                   Stmt *LoopVar,
4746                                   SourceLocation ColonLoc, Expr *Collection,
4747                                   SourceLocation RParenLoc,
4748                                   BuildForRangeKind Kind);
4749   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4750                                   SourceLocation CoawaitLoc,
4751                                   Stmt *InitStmt,
4752                                   SourceLocation ColonLoc,
4753                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4754                                   Expr *Cond, Expr *Inc,
4755                                   Stmt *LoopVarDecl,
4756                                   SourceLocation RParenLoc,
4757                                   BuildForRangeKind Kind);
4758   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4759 
4760   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4761                            SourceLocation LabelLoc,
4762                            LabelDecl *TheDecl);
4763   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4764                                    SourceLocation StarLoc,
4765                                    Expr *DestExp);
4766   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4767   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4768 
4769   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4770                                 CapturedRegionKind Kind, unsigned NumParams);
4771   typedef std::pair<StringRef, QualType> CapturedParamNameType;
4772   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4773                                 CapturedRegionKind Kind,
4774                                 ArrayRef<CapturedParamNameType> Params,
4775                                 unsigned OpenMPCaptureLevel = 0);
4776   StmtResult ActOnCapturedRegionEnd(Stmt *S);
4777   void ActOnCapturedRegionError();
4778   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4779                                            SourceLocation Loc,
4780                                            unsigned NumParams);
4781 
4782   struct NamedReturnInfo {
4783     const VarDecl *Candidate;
4784 
4785     enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
4786     Status S;
4787 
isMoveEligibleNamedReturnInfo4788     bool isMoveEligible() const { return S != None; };
isCopyElidableNamedReturnInfo4789     bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
4790   };
4791   enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
4792   NamedReturnInfo getNamedReturnInfo(
4793       Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
4794   NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
4795   const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
4796                                          QualType ReturnType);
4797 
4798   ExprResult
4799   PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
4800                                   const NamedReturnInfo &NRInfo, Expr *Value,
4801                                   bool SupressSimplerImplicitMoves = false);
4802 
4803   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4804                              Scope *CurScope);
4805   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4806   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4807                                      NamedReturnInfo &NRInfo,
4808                                      bool SupressSimplerImplicitMoves);
4809 
4810   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4811                              bool IsVolatile, unsigned NumOutputs,
4812                              unsigned NumInputs, IdentifierInfo **Names,
4813                              MultiExprArg Constraints, MultiExprArg Exprs,
4814                              Expr *AsmString, MultiExprArg Clobbers,
4815                              unsigned NumLabels,
4816                              SourceLocation RParenLoc);
4817 
4818   void FillInlineAsmIdentifierInfo(Expr *Res,
4819                                    llvm::InlineAsmIdentifierInfo &Info);
4820   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4821                                        SourceLocation TemplateKWLoc,
4822                                        UnqualifiedId &Id,
4823                                        bool IsUnevaluatedContext);
4824   bool LookupInlineAsmField(StringRef Base, StringRef Member,
4825                             unsigned &Offset, SourceLocation AsmLoc);
4826   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4827                                          SourceLocation AsmLoc);
4828   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4829                             ArrayRef<Token> AsmToks,
4830                             StringRef AsmString,
4831                             unsigned NumOutputs, unsigned NumInputs,
4832                             ArrayRef<StringRef> Constraints,
4833                             ArrayRef<StringRef> Clobbers,
4834                             ArrayRef<Expr*> Exprs,
4835                             SourceLocation EndLoc);
4836   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4837                                    SourceLocation Location,
4838                                    bool AlwaysCreate);
4839 
4840   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4841                                   SourceLocation StartLoc,
4842                                   SourceLocation IdLoc, IdentifierInfo *Id,
4843                                   bool Invalid = false);
4844 
4845   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4846 
4847   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4848                                   Decl *Parm, Stmt *Body);
4849 
4850   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4851 
4852   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4853                                 MultiStmtArg Catch, Stmt *Finally);
4854 
4855   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4856   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4857                                   Scope *CurScope);
4858   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4859                                             Expr *operand);
4860   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4861                                          Expr *SynchExpr,
4862                                          Stmt *SynchBody);
4863 
4864   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4865 
4866   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4867                                      SourceLocation StartLoc,
4868                                      SourceLocation IdLoc,
4869                                      IdentifierInfo *Id);
4870 
4871   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4872 
4873   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4874                                 Decl *ExDecl, Stmt *HandlerBlock);
4875   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4876                               ArrayRef<Stmt *> Handlers);
4877 
4878   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4879                               SourceLocation TryLoc, Stmt *TryBlock,
4880                               Stmt *Handler);
4881   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4882                                  Expr *FilterExpr,
4883                                  Stmt *Block);
4884   void ActOnStartSEHFinallyBlock();
4885   void ActOnAbortSEHFinallyBlock();
4886   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4887   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4888 
4889   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4890 
4891   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4892 
4893   /// If it's a file scoped decl that must warn if not used, keep track
4894   /// of it.
4895   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4896 
4897   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4898   /// whose result is unused, warn.
4899   void DiagnoseUnusedExprResult(const Stmt *S);
4900   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4901   void DiagnoseUnusedDecl(const NamedDecl *ND);
4902 
4903   /// If VD is set but not otherwise used, diagnose, for a parameter or a
4904   /// variable.
4905   void DiagnoseUnusedButSetDecl(const VarDecl *VD);
4906 
4907   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4908   /// statement as a \p Body, and it is located on the same line.
4909   ///
4910   /// This helps prevent bugs due to typos, such as:
4911   ///     if (condition);
4912   ///       do_stuff();
4913   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4914                              const Stmt *Body,
4915                              unsigned DiagID);
4916 
4917   /// Warn if a for/while loop statement \p S, which is followed by
4918   /// \p PossibleBody, has a suspicious null statement as a body.
4919   void DiagnoseEmptyLoopBody(const Stmt *S,
4920                              const Stmt *PossibleBody);
4921 
4922   /// Warn if a value is moved to itself.
4923   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4924                         SourceLocation OpLoc);
4925 
4926   /// Warn if we're implicitly casting from a _Nullable pointer type to a
4927   /// _Nonnull one.
4928   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4929                                            SourceLocation Loc);
4930 
4931   /// Warn when implicitly casting 0 to nullptr.
4932   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4933 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)4934   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4935     return DelayedDiagnostics.push(pool);
4936   }
4937   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4938 
4939   typedef ProcessingContextState ParsingClassState;
PushParsingClass()4940   ParsingClassState PushParsingClass() {
4941     ParsingClassDepth++;
4942     return DelayedDiagnostics.pushUndelayed();
4943   }
PopParsingClass(ParsingClassState state)4944   void PopParsingClass(ParsingClassState state) {
4945     ParsingClassDepth--;
4946     DelayedDiagnostics.popUndelayed(state);
4947   }
4948 
4949   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4950 
4951   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4952                                   const ObjCInterfaceDecl *UnknownObjCClass,
4953                                   bool ObjCPropertyAccess,
4954                                   bool AvoidPartialAvailabilityChecks = false,
4955                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
4956 
4957   bool makeUnavailableInSystemHeader(SourceLocation loc,
4958                                      UnavailableAttr::ImplicitReason reason);
4959 
4960   /// Issue any -Wunguarded-availability warnings in \c FD
4961   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4962 
4963   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4964 
4965   //===--------------------------------------------------------------------===//
4966   // Expression Parsing Callbacks: SemaExpr.cpp.
4967 
4968   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4969   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4970                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4971                          bool ObjCPropertyAccess = false,
4972                          bool AvoidPartialAvailabilityChecks = false,
4973                          ObjCInterfaceDecl *ClassReciever = nullptr);
4974   void NoteDeletedFunction(FunctionDecl *FD);
4975   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4976   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4977                                         ObjCMethodDecl *Getter,
4978                                         SourceLocation Loc);
4979   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4980                              ArrayRef<Expr *> Args);
4981 
4982   void PushExpressionEvaluationContext(
4983       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4984       ExpressionEvaluationContextRecord::ExpressionKind Type =
4985           ExpressionEvaluationContextRecord::EK_Other);
4986   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4987   void PushExpressionEvaluationContext(
4988       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4989       ExpressionEvaluationContextRecord::ExpressionKind Type =
4990           ExpressionEvaluationContextRecord::EK_Other);
4991   void PopExpressionEvaluationContext();
4992 
4993   void DiscardCleanupsInEvaluationContext();
4994 
4995   ExprResult TransformToPotentiallyEvaluated(Expr *E);
4996   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4997 
4998   ExprResult CheckUnevaluatedOperand(Expr *E);
4999   void CheckUnusedVolatileAssignment(Expr *E);
5000 
5001   ExprResult ActOnConstantExpression(ExprResult Res);
5002 
5003   // Functions for marking a declaration referenced.  These functions also
5004   // contain the relevant logic for marking if a reference to a function or
5005   // variable is an odr-use (in the C++11 sense).  There are separate variants
5006   // for expressions referring to a decl; these exist because odr-use marking
5007   // needs to be delayed for some constant variables when we build one of the
5008   // named expressions.
5009   //
5010   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5011   // should usually be true. This only needs to be set to false if the lack of
5012   // odr-use cannot be determined from the current context (for instance,
5013   // because the name denotes a virtual function and was written without an
5014   // explicit nested-name-specifier).
5015   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5016   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5017                               bool MightBeOdrUse = true);
5018   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5019   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5020   void MarkMemberReferenced(MemberExpr *E);
5021   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5022   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
5023                                          unsigned CapturingScopeIndex);
5024 
5025   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5026   void CleanupVarDeclMarking();
5027 
5028   enum TryCaptureKind {
5029     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5030   };
5031 
5032   /// Try to capture the given variable.
5033   ///
5034   /// \param Var The variable to capture.
5035   ///
5036   /// \param Loc The location at which the capture occurs.
5037   ///
5038   /// \param Kind The kind of capture, which may be implicit (for either a
5039   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5040   ///
5041   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5042   /// an explicit lambda capture.
5043   ///
5044   /// \param BuildAndDiagnose Whether we are actually supposed to add the
5045   /// captures or diagnose errors. If false, this routine merely check whether
5046   /// the capture can occur without performing the capture itself or complaining
5047   /// if the variable cannot be captured.
5048   ///
5049   /// \param CaptureType Will be set to the type of the field used to capture
5050   /// this variable in the innermost block or lambda. Only valid when the
5051   /// variable can be captured.
5052   ///
5053   /// \param DeclRefType Will be set to the type of a reference to the capture
5054   /// from within the current scope. Only valid when the variable can be
5055   /// captured.
5056   ///
5057   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5058   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5059   /// This is useful when enclosing lambdas must speculatively capture
5060   /// variables that may or may not be used in certain specializations of
5061   /// a nested generic lambda.
5062   ///
5063   /// \returns true if an error occurred (i.e., the variable cannot be
5064   /// captured) and false if the capture succeeded.
5065   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
5066                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
5067                           QualType &CaptureType,
5068                           QualType &DeclRefType,
5069                           const unsigned *const FunctionScopeIndexToStopAt);
5070 
5071   /// Try to capture the given variable.
5072   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
5073                           TryCaptureKind Kind = TryCapture_Implicit,
5074                           SourceLocation EllipsisLoc = SourceLocation());
5075 
5076   /// Checks if the variable must be captured.
5077   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
5078 
5079   /// Given a variable, determine the type that a reference to that
5080   /// variable will have in the given scope.
5081   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
5082 
5083   /// Mark all of the declarations referenced within a particular AST node as
5084   /// referenced. Used when template instantiation instantiates a non-dependent
5085   /// type -- entities referenced by the type are now referenced.
5086   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5087   void MarkDeclarationsReferencedInExpr(Expr *E,
5088                                         bool SkipLocalVariables = false);
5089 
5090   /// Try to recover by turning the given expression into a
5091   /// call.  Returns true if recovery was attempted or an error was
5092   /// emitted; this may also leave the ExprResult invalid.
5093   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5094                             bool ForceComplain = false,
5095                             bool (*IsPlausibleResult)(QualType) = nullptr);
5096 
5097   /// Figure out if an expression could be turned into a call.
5098   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5099                      UnresolvedSetImpl &NonTemplateOverloads);
5100 
5101   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5102   /// conversion.
5103   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5104 
5105   /// Conditionally issue a diagnostic based on the current
5106   /// evaluation context.
5107   ///
5108   /// \param Statement If Statement is non-null, delay reporting the
5109   /// diagnostic until the function body is parsed, and then do a basic
5110   /// reachability analysis to determine if the statement is reachable.
5111   /// If it is unreachable, the diagnostic will not be emitted.
5112   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5113                            const PartialDiagnostic &PD);
5114   /// Similar, but diagnostic is only produced if all the specified statements
5115   /// are reachable.
5116   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5117                            const PartialDiagnostic &PD);
5118 
5119   // Primary Expressions.
5120   SourceRange getExprRange(Expr *E) const;
5121 
5122   ExprResult ActOnIdExpression(
5123       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5124       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5125       CorrectionCandidateCallback *CCC = nullptr,
5126       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5127 
5128   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5129                               TemplateArgumentListInfo &Buffer,
5130                               DeclarationNameInfo &NameInfo,
5131                               const TemplateArgumentListInfo *&TemplateArgs);
5132 
5133   bool DiagnoseDependentMemberLookup(LookupResult &R);
5134 
5135   bool
5136   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5137                       CorrectionCandidateCallback &CCC,
5138                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5139                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
5140 
5141   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5142                                     IdentifierInfo *II);
5143   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5144 
5145   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5146                                 IdentifierInfo *II,
5147                                 bool AllowBuiltinCreation=false);
5148 
5149   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5150                                         SourceLocation TemplateKWLoc,
5151                                         const DeclarationNameInfo &NameInfo,
5152                                         bool isAddressOfOperand,
5153                                 const TemplateArgumentListInfo *TemplateArgs);
5154 
5155   /// If \p D cannot be odr-used in the current expression evaluation context,
5156   /// return a reason explaining why. Otherwise, return NOUR_None.
5157   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5158 
5159   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5160                                 SourceLocation Loc,
5161                                 const CXXScopeSpec *SS = nullptr);
5162   DeclRefExpr *
5163   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5164                    const DeclarationNameInfo &NameInfo,
5165                    const CXXScopeSpec *SS = nullptr,
5166                    NamedDecl *FoundD = nullptr,
5167                    SourceLocation TemplateKWLoc = SourceLocation(),
5168                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5169   DeclRefExpr *
5170   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5171                    const DeclarationNameInfo &NameInfo,
5172                    NestedNameSpecifierLoc NNS,
5173                    NamedDecl *FoundD = nullptr,
5174                    SourceLocation TemplateKWLoc = SourceLocation(),
5175                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5176 
5177   ExprResult
5178   BuildAnonymousStructUnionMemberReference(
5179       const CXXScopeSpec &SS,
5180       SourceLocation nameLoc,
5181       IndirectFieldDecl *indirectField,
5182       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5183       Expr *baseObjectExpr = nullptr,
5184       SourceLocation opLoc = SourceLocation());
5185 
5186   ExprResult BuildPossibleImplicitMemberExpr(
5187       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5188       const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5189       UnresolvedLookupExpr *AsULE = nullptr);
5190   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5191                                      SourceLocation TemplateKWLoc,
5192                                      LookupResult &R,
5193                                 const TemplateArgumentListInfo *TemplateArgs,
5194                                      bool IsDefiniteInstance,
5195                                      const Scope *S);
5196   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5197                                   const LookupResult &R,
5198                                   bool HasTrailingLParen);
5199 
5200   ExprResult
5201   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5202                                     const DeclarationNameInfo &NameInfo,
5203                                     bool IsAddressOfOperand, const Scope *S,
5204                                     TypeSourceInfo **RecoveryTSI = nullptr);
5205 
5206   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5207                                        SourceLocation TemplateKWLoc,
5208                                 const DeclarationNameInfo &NameInfo,
5209                                 const TemplateArgumentListInfo *TemplateArgs);
5210 
5211   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5212                                       LookupResult &R,
5213                                       bool NeedsADL,
5214                                       bool AcceptInvalidDecl = false);
5215   ExprResult BuildDeclarationNameExpr(
5216       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5217       NamedDecl *FoundD = nullptr,
5218       const TemplateArgumentListInfo *TemplateArgs = nullptr,
5219       bool AcceptInvalidDecl = false);
5220 
5221   ExprResult BuildLiteralOperatorCall(LookupResult &R,
5222                       DeclarationNameInfo &SuffixInfo,
5223                       ArrayRef<Expr *> Args,
5224                       SourceLocation LitEndLoc,
5225                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5226 
5227   ExprResult BuildPredefinedExpr(SourceLocation Loc,
5228                                  PredefinedExpr::IdentKind IK);
5229   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5230   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5231 
5232   ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5233                                            SourceLocation LParen,
5234                                            SourceLocation RParen,
5235                                            TypeSourceInfo *TSI);
5236   ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5237                                            SourceLocation LParen,
5238                                            SourceLocation RParen,
5239                                            ParsedType ParsedTy);
5240 
5241   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5242 
5243   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5244   ExprResult ActOnCharacterConstant(const Token &Tok,
5245                                     Scope *UDLScope = nullptr);
5246   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5247   ExprResult ActOnParenListExpr(SourceLocation L,
5248                                 SourceLocation R,
5249                                 MultiExprArg Val);
5250 
5251   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5252   /// fragments (e.g. "foo" "bar" L"baz").
5253   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5254                                 Scope *UDLScope = nullptr);
5255 
5256   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5257                                        SourceLocation DefaultLoc,
5258                                        SourceLocation RParenLoc,
5259                                        Expr *ControllingExpr,
5260                                        ArrayRef<ParsedType> ArgTypes,
5261                                        ArrayRef<Expr *> ArgExprs);
5262   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5263                                         SourceLocation DefaultLoc,
5264                                         SourceLocation RParenLoc,
5265                                         Expr *ControllingExpr,
5266                                         ArrayRef<TypeSourceInfo *> Types,
5267                                         ArrayRef<Expr *> Exprs);
5268 
5269   // Binary/Unary Operators.  'Tok' is the token for the operator.
5270   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5271                                   Expr *InputExpr);
5272   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5273                           UnaryOperatorKind Opc, Expr *Input);
5274   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5275                           tok::TokenKind Op, Expr *Input);
5276 
5277   bool isQualifiedMemberAccess(Expr *E);
5278   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5279 
5280   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5281                                             SourceLocation OpLoc,
5282                                             UnaryExprOrTypeTrait ExprKind,
5283                                             SourceRange R);
5284   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5285                                             UnaryExprOrTypeTrait ExprKind);
5286   ExprResult
5287     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5288                                   UnaryExprOrTypeTrait ExprKind,
5289                                   bool IsType, void *TyOrEx,
5290                                   SourceRange ArgRange);
5291 
5292   ExprResult CheckPlaceholderExpr(Expr *E);
5293   bool CheckVecStepExpr(Expr *E);
5294 
5295   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5296   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5297                                         SourceRange ExprRange,
5298                                         UnaryExprOrTypeTrait ExprKind);
5299   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5300                                           SourceLocation OpLoc,
5301                                           IdentifierInfo &Name,
5302                                           SourceLocation NameLoc,
5303                                           SourceLocation RParenLoc);
5304   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5305                                  tok::TokenKind Kind, Expr *Input);
5306 
5307   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5308                                      Expr *Idx, SourceLocation RLoc);
5309   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5310                                              Expr *Idx, SourceLocation RLoc);
5311 
5312   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5313                                               Expr *ColumnIdx,
5314                                               SourceLocation RBLoc);
5315 
5316   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5317                                       Expr *LowerBound,
5318                                       SourceLocation ColonLocFirst,
5319                                       SourceLocation ColonLocSecond,
5320                                       Expr *Length, Expr *Stride,
5321                                       SourceLocation RBLoc);
5322   ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5323                                       SourceLocation RParenLoc,
5324                                       ArrayRef<Expr *> Dims,
5325                                       ArrayRef<SourceRange> Brackets);
5326 
5327   /// Data structure for iterator expression.
5328   struct OMPIteratorData {
5329     IdentifierInfo *DeclIdent = nullptr;
5330     SourceLocation DeclIdentLoc;
5331     ParsedType Type;
5332     OMPIteratorExpr::IteratorRange Range;
5333     SourceLocation AssignLoc;
5334     SourceLocation ColonLoc;
5335     SourceLocation SecColonLoc;
5336   };
5337 
5338   ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5339                                   SourceLocation LLoc, SourceLocation RLoc,
5340                                   ArrayRef<OMPIteratorData> Data);
5341 
5342   // This struct is for use by ActOnMemberAccess to allow
5343   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5344   // changing the access operator from a '.' to a '->' (to see if that is the
5345   // change needed to fix an error about an unknown member, e.g. when the class
5346   // defines a custom operator->).
5347   struct ActOnMemberAccessExtraArgs {
5348     Scope *S;
5349     UnqualifiedId &Id;
5350     Decl *ObjCImpDecl;
5351   };
5352 
5353   ExprResult BuildMemberReferenceExpr(
5354       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5355       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5356       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5357       const TemplateArgumentListInfo *TemplateArgs,
5358       const Scope *S,
5359       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5360 
5361   ExprResult
5362   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5363                            bool IsArrow, const CXXScopeSpec &SS,
5364                            SourceLocation TemplateKWLoc,
5365                            NamedDecl *FirstQualifierInScope, LookupResult &R,
5366                            const TemplateArgumentListInfo *TemplateArgs,
5367                            const Scope *S,
5368                            bool SuppressQualifierCheck = false,
5369                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5370 
5371   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5372                                      SourceLocation OpLoc,
5373                                      const CXXScopeSpec &SS, FieldDecl *Field,
5374                                      DeclAccessPair FoundDecl,
5375                                      const DeclarationNameInfo &MemberNameInfo);
5376 
5377   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5378 
5379   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5380                                      const CXXScopeSpec &SS,
5381                                      const LookupResult &R);
5382 
5383   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5384                                       bool IsArrow, SourceLocation OpLoc,
5385                                       const CXXScopeSpec &SS,
5386                                       SourceLocation TemplateKWLoc,
5387                                       NamedDecl *FirstQualifierInScope,
5388                                const DeclarationNameInfo &NameInfo,
5389                                const TemplateArgumentListInfo *TemplateArgs);
5390 
5391   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5392                                    SourceLocation OpLoc,
5393                                    tok::TokenKind OpKind,
5394                                    CXXScopeSpec &SS,
5395                                    SourceLocation TemplateKWLoc,
5396                                    UnqualifiedId &Member,
5397                                    Decl *ObjCImpDecl);
5398 
5399   MemberExpr *
5400   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5401                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5402                   ValueDecl *Member, DeclAccessPair FoundDecl,
5403                   bool HadMultipleCandidates,
5404                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5405                   ExprValueKind VK, ExprObjectKind OK,
5406                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5407   MemberExpr *
5408   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5409                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5410                   ValueDecl *Member, DeclAccessPair FoundDecl,
5411                   bool HadMultipleCandidates,
5412                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5413                   ExprValueKind VK, ExprObjectKind OK,
5414                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5415 
5416   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5417   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5418                                FunctionDecl *FDecl,
5419                                const FunctionProtoType *Proto,
5420                                ArrayRef<Expr *> Args,
5421                                SourceLocation RParenLoc,
5422                                bool ExecConfig = false);
5423   void CheckStaticArrayArgument(SourceLocation CallLoc,
5424                                 ParmVarDecl *Param,
5425                                 const Expr *ArgExpr);
5426 
5427   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5428   /// This provides the location of the left/right parens and a list of comma
5429   /// locations.
5430   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5431                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5432                            Expr *ExecConfig = nullptr);
5433   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5434                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5435                            Expr *ExecConfig = nullptr,
5436                            bool IsExecConfig = false,
5437                            bool AllowRecovery = false);
5438   Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5439                              MultiExprArg CallArgs);
5440   enum class AtomicArgumentOrder { API, AST };
5441   ExprResult
5442   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5443                   SourceLocation RParenLoc, MultiExprArg Args,
5444                   AtomicExpr::AtomicOp Op,
5445                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5446   ExprResult
5447   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5448                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5449                         Expr *Config = nullptr, bool IsExecConfig = false,
5450                         ADLCallKind UsesADL = ADLCallKind::NotADL);
5451 
5452   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5453                                      MultiExprArg ExecConfig,
5454                                      SourceLocation GGGLoc);
5455 
5456   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5457                            Declarator &D, ParsedType &Ty,
5458                            SourceLocation RParenLoc, Expr *CastExpr);
5459   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5460                                  TypeSourceInfo *Ty,
5461                                  SourceLocation RParenLoc,
5462                                  Expr *Op);
5463   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5464 
5465   /// Build an altivec or OpenCL literal.
5466   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5467                                 SourceLocation RParenLoc, Expr *E,
5468                                 TypeSourceInfo *TInfo);
5469 
5470   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5471 
5472   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5473                                   ParsedType Ty,
5474                                   SourceLocation RParenLoc,
5475                                   Expr *InitExpr);
5476 
5477   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5478                                       TypeSourceInfo *TInfo,
5479                                       SourceLocation RParenLoc,
5480                                       Expr *LiteralExpr);
5481 
5482   ExprResult ActOnInitList(SourceLocation LBraceLoc,
5483                            MultiExprArg InitArgList,
5484                            SourceLocation RBraceLoc);
5485 
5486   ExprResult BuildInitList(SourceLocation LBraceLoc,
5487                            MultiExprArg InitArgList,
5488                            SourceLocation RBraceLoc);
5489 
5490   ExprResult ActOnDesignatedInitializer(Designation &Desig,
5491                                         SourceLocation EqualOrColonLoc,
5492                                         bool GNUSyntax,
5493                                         ExprResult Init);
5494 
5495 private:
5496   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5497 
5498 public:
5499   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5500                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5501   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5502                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5503   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5504                                 Expr *LHSExpr, Expr *RHSExpr);
5505   void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5506                    UnresolvedSetImpl &Functions);
5507 
5508   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5509 
5510   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5511   /// in the case of a the GNU conditional expr extension.
5512   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5513                                 SourceLocation ColonLoc,
5514                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5515 
5516   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5517   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5518                             LabelDecl *TheDecl);
5519 
5520   void ActOnStartStmtExpr();
5521   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5522                            SourceLocation RPLoc);
5523   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5524                            SourceLocation RPLoc, unsigned TemplateDepth);
5525   // Handle the final expression in a statement expression.
5526   ExprResult ActOnStmtExprResult(ExprResult E);
5527   void ActOnStmtExprError();
5528 
5529   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5530   struct OffsetOfComponent {
5531     SourceLocation LocStart, LocEnd;
5532     bool isBrackets;  // true if [expr], false if .ident
5533     union {
5534       IdentifierInfo *IdentInfo;
5535       Expr *E;
5536     } U;
5537   };
5538 
5539   /// __builtin_offsetof(type, a.b[123][456].c)
5540   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5541                                   TypeSourceInfo *TInfo,
5542                                   ArrayRef<OffsetOfComponent> Components,
5543                                   SourceLocation RParenLoc);
5544   ExprResult ActOnBuiltinOffsetOf(Scope *S,
5545                                   SourceLocation BuiltinLoc,
5546                                   SourceLocation TypeLoc,
5547                                   ParsedType ParsedArgTy,
5548                                   ArrayRef<OffsetOfComponent> Components,
5549                                   SourceLocation RParenLoc);
5550 
5551   // __builtin_choose_expr(constExpr, expr1, expr2)
5552   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5553                              Expr *CondExpr, Expr *LHSExpr,
5554                              Expr *RHSExpr, SourceLocation RPLoc);
5555 
5556   // __builtin_va_arg(expr, type)
5557   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5558                         SourceLocation RPLoc);
5559   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5560                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
5561 
5562   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5563   // __builtin_COLUMN()
5564   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5565                                 SourceLocation BuiltinLoc,
5566                                 SourceLocation RPLoc);
5567 
5568   // Build a potentially resolved SourceLocExpr.
5569   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5570                                 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5571                                 DeclContext *ParentContext);
5572 
5573   // __null
5574   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5575 
5576   bool CheckCaseExpression(Expr *E);
5577 
5578   /// Describes the result of an "if-exists" condition check.
5579   enum IfExistsResult {
5580     /// The symbol exists.
5581     IER_Exists,
5582 
5583     /// The symbol does not exist.
5584     IER_DoesNotExist,
5585 
5586     /// The name is a dependent name, so the results will differ
5587     /// from one instantiation to the next.
5588     IER_Dependent,
5589 
5590     /// An error occurred.
5591     IER_Error
5592   };
5593 
5594   IfExistsResult
5595   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5596                                const DeclarationNameInfo &TargetNameInfo);
5597 
5598   IfExistsResult
5599   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5600                                bool IsIfExists, CXXScopeSpec &SS,
5601                                UnqualifiedId &Name);
5602 
5603   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5604                                         bool IsIfExists,
5605                                         NestedNameSpecifierLoc QualifierLoc,
5606                                         DeclarationNameInfo NameInfo,
5607                                         Stmt *Nested);
5608   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5609                                         bool IsIfExists,
5610                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5611                                         Stmt *Nested);
5612 
5613   //===------------------------- "Block" Extension ------------------------===//
5614 
5615   /// ActOnBlockStart - This callback is invoked when a block literal is
5616   /// started.
5617   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5618 
5619   /// ActOnBlockArguments - This callback allows processing of block arguments.
5620   /// If there are no arguments, this is still invoked.
5621   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5622                            Scope *CurScope);
5623 
5624   /// ActOnBlockError - If there is an error parsing a block, this callback
5625   /// is invoked to pop the information about the block from the action impl.
5626   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5627 
5628   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5629   /// literal was successfully completed.  ^(int x){...}
5630   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5631                                 Scope *CurScope);
5632 
5633   //===---------------------------- Clang Extensions ----------------------===//
5634 
5635   /// __builtin_convertvector(...)
5636   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5637                                     SourceLocation BuiltinLoc,
5638                                     SourceLocation RParenLoc);
5639 
5640   //===---------------------------- OpenCL Features -----------------------===//
5641 
5642   /// __builtin_astype(...)
5643   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5644                              SourceLocation BuiltinLoc,
5645                              SourceLocation RParenLoc);
5646   ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
5647                              SourceLocation BuiltinLoc,
5648                              SourceLocation RParenLoc);
5649 
5650   //===---------------------------- C++ Features --------------------------===//
5651 
5652   // Act on C++ namespaces
5653   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5654                                SourceLocation NamespaceLoc,
5655                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5656                                SourceLocation LBrace,
5657                                const ParsedAttributesView &AttrList,
5658                                UsingDirectiveDecl *&UsingDecl);
5659   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5660 
5661   NamespaceDecl *getStdNamespace() const;
5662   NamespaceDecl *getOrCreateStdNamespace();
5663 
5664   NamespaceDecl *lookupStdExperimentalNamespace();
5665 
5666   CXXRecordDecl *getStdBadAlloc() const;
5667   EnumDecl *getStdAlignValT() const;
5668 
5669 private:
5670   // A cache representing if we've fully checked the various comparison category
5671   // types stored in ASTContext. The bit-index corresponds to the integer value
5672   // of a ComparisonCategoryType enumerator.
5673   llvm::SmallBitVector FullyCheckedComparisonCategories;
5674 
5675   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5676                                          CXXScopeSpec &SS,
5677                                          ParsedType TemplateTypeTy,
5678                                          IdentifierInfo *MemberOrBase);
5679 
5680 public:
5681   enum class ComparisonCategoryUsage {
5682     /// The '<=>' operator was used in an expression and a builtin operator
5683     /// was selected.
5684     OperatorInExpression,
5685     /// A defaulted 'operator<=>' needed the comparison category. This
5686     /// typically only applies to 'std::strong_ordering', due to the implicit
5687     /// fallback return value.
5688     DefaultedOperator,
5689   };
5690 
5691   /// Lookup the specified comparison category types in the standard
5692   ///   library, an check the VarDecls possibly returned by the operator<=>
5693   ///   builtins for that type.
5694   ///
5695   /// \return The type of the comparison category type corresponding to the
5696   ///   specified Kind, or a null type if an error occurs
5697   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5698                                        SourceLocation Loc,
5699                                        ComparisonCategoryUsage Usage);
5700 
5701   /// Tests whether Ty is an instance of std::initializer_list and, if
5702   /// it is and Element is not NULL, assigns the element type to Element.
5703   bool isStdInitializerList(QualType Ty, QualType *Element);
5704 
5705   /// Looks for the std::initializer_list template and instantiates it
5706   /// with Element, or emits an error if it's not found.
5707   ///
5708   /// \returns The instantiated template, or null on error.
5709   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5710 
5711   /// Determine whether Ctor is an initializer-list constructor, as
5712   /// defined in [dcl.init.list]p2.
5713   bool isInitListConstructor(const FunctionDecl *Ctor);
5714 
5715   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5716                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5717                             SourceLocation IdentLoc,
5718                             IdentifierInfo *NamespcName,
5719                             const ParsedAttributesView &AttrList);
5720 
5721   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5722 
5723   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5724                                SourceLocation NamespaceLoc,
5725                                SourceLocation AliasLoc,
5726                                IdentifierInfo *Alias,
5727                                CXXScopeSpec &SS,
5728                                SourceLocation IdentLoc,
5729                                IdentifierInfo *Ident);
5730 
5731   void FilterUsingLookup(Scope *S, LookupResult &lookup);
5732   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5733   bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5734                             const LookupResult &PreviousDecls,
5735                             UsingShadowDecl *&PrevShadow);
5736   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5737                                         NamedDecl *Target,
5738                                         UsingShadowDecl *PrevDecl);
5739 
5740   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5741                                    bool HasTypenameKeyword,
5742                                    const CXXScopeSpec &SS,
5743                                    SourceLocation NameLoc,
5744                                    const LookupResult &Previous);
5745   bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5746                                const CXXScopeSpec &SS,
5747                                const DeclarationNameInfo &NameInfo,
5748                                SourceLocation NameLoc,
5749                                const LookupResult *R = nullptr,
5750                                const UsingDecl *UD = nullptr);
5751 
5752   NamedDecl *BuildUsingDeclaration(
5753       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5754       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5755       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5756       const ParsedAttributesView &AttrList, bool IsInstantiation,
5757       bool IsUsingIfExists);
5758   NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5759                                        SourceLocation UsingLoc,
5760                                        SourceLocation EnumLoc,
5761                                        SourceLocation NameLoc, EnumDecl *ED);
5762   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5763                                 ArrayRef<NamedDecl *> Expansions);
5764 
5765   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5766 
5767   /// Given a derived-class using shadow declaration for a constructor and the
5768   /// correspnding base class constructor, find or create the implicit
5769   /// synthesized derived class constructor to use for this initialization.
5770   CXXConstructorDecl *
5771   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5772                             ConstructorUsingShadowDecl *DerivedShadow);
5773 
5774   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5775                               SourceLocation UsingLoc,
5776                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
5777                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
5778                               const ParsedAttributesView &AttrList);
5779   Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5780                                   SourceLocation UsingLoc,
5781                                   SourceLocation EnumLoc, const DeclSpec &);
5782   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5783                               MultiTemplateParamsArg TemplateParams,
5784                               SourceLocation UsingLoc, UnqualifiedId &Name,
5785                               const ParsedAttributesView &AttrList,
5786                               TypeResult Type, Decl *DeclFromDeclSpec);
5787 
5788   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5789   /// including handling of its default argument expressions.
5790   ///
5791   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5792   ExprResult
5793   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5794                         NamedDecl *FoundDecl,
5795                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5796                         bool HadMultipleCandidates, bool IsListInitialization,
5797                         bool IsStdInitListInitialization,
5798                         bool RequiresZeroInit, unsigned ConstructKind,
5799                         SourceRange ParenRange);
5800 
5801   /// Build a CXXConstructExpr whose constructor has already been resolved if
5802   /// it denotes an inherited constructor.
5803   ExprResult
5804   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5805                         CXXConstructorDecl *Constructor, bool Elidable,
5806                         MultiExprArg Exprs,
5807                         bool HadMultipleCandidates, bool IsListInitialization,
5808                         bool IsStdInitListInitialization,
5809                         bool RequiresZeroInit, unsigned ConstructKind,
5810                         SourceRange ParenRange);
5811 
5812   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5813   // the constructor can be elidable?
5814   ExprResult
5815   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5816                         NamedDecl *FoundDecl,
5817                         CXXConstructorDecl *Constructor, bool Elidable,
5818                         MultiExprArg Exprs, bool HadMultipleCandidates,
5819                         bool IsListInitialization,
5820                         bool IsStdInitListInitialization, bool RequiresZeroInit,
5821                         unsigned ConstructKind, SourceRange ParenRange);
5822 
5823   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5824 
5825 
5826   /// Instantiate or parse a C++ default argument expression as necessary.
5827   /// Return true on error.
5828   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5829                               ParmVarDecl *Param);
5830 
5831   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5832   /// the default expr if needed.
5833   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5834                                     FunctionDecl *FD,
5835                                     ParmVarDecl *Param);
5836 
5837   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5838   /// constructed variable.
5839   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5840 
5841   /// Helper class that collects exception specifications for
5842   /// implicitly-declared special member functions.
5843   class ImplicitExceptionSpecification {
5844     // Pointer to allow copying
5845     Sema *Self;
5846     // We order exception specifications thus:
5847     // noexcept is the most restrictive, but is only used in C++11.
5848     // throw() comes next.
5849     // Then a throw(collected exceptions)
5850     // Finally no specification, which is expressed as noexcept(false).
5851     // throw(...) is used instead if any called function uses it.
5852     ExceptionSpecificationType ComputedEST;
5853     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5854     SmallVector<QualType, 4> Exceptions;
5855 
ClearExceptions()5856     void ClearExceptions() {
5857       ExceptionsSeen.clear();
5858       Exceptions.clear();
5859     }
5860 
5861   public:
ImplicitExceptionSpecification(Sema & Self)5862     explicit ImplicitExceptionSpecification(Sema &Self)
5863       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5864       if (!Self.getLangOpts().CPlusPlus11)
5865         ComputedEST = EST_DynamicNone;
5866     }
5867 
5868     /// Get the computed exception specification type.
getExceptionSpecType()5869     ExceptionSpecificationType getExceptionSpecType() const {
5870       assert(!isComputedNoexcept(ComputedEST) &&
5871              "noexcept(expr) should not be a possible result");
5872       return ComputedEST;
5873     }
5874 
5875     /// The number of exceptions in the exception specification.
size()5876     unsigned size() const { return Exceptions.size(); }
5877 
5878     /// The set of exceptions in the exception specification.
data()5879     const QualType *data() const { return Exceptions.data(); }
5880 
5881     /// Integrate another called method into the collected data.
5882     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5883 
5884     /// Integrate an invoked expression into the collected data.
CalledExpr(Expr * E)5885     void CalledExpr(Expr *E) { CalledStmt(E); }
5886 
5887     /// Integrate an invoked statement into the collected data.
5888     void CalledStmt(Stmt *S);
5889 
5890     /// Overwrite an EPI's exception specification with this
5891     /// computed exception specification.
getExceptionSpec()5892     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5893       FunctionProtoType::ExceptionSpecInfo ESI;
5894       ESI.Type = getExceptionSpecType();
5895       if (ESI.Type == EST_Dynamic) {
5896         ESI.Exceptions = Exceptions;
5897       } else if (ESI.Type == EST_None) {
5898         /// C++11 [except.spec]p14:
5899         ///   The exception-specification is noexcept(false) if the set of
5900         ///   potential exceptions of the special member function contains "any"
5901         ESI.Type = EST_NoexceptFalse;
5902         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5903                                                      tok::kw_false).get();
5904       }
5905       return ESI;
5906     }
5907   };
5908 
5909   /// Evaluate the implicit exception specification for a defaulted
5910   /// special member function.
5911   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5912 
5913   /// Check the given noexcept-specifier, convert its expression, and compute
5914   /// the appropriate ExceptionSpecificationType.
5915   ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5916                                ExceptionSpecificationType &EST);
5917 
5918   /// Check the given exception-specification and update the
5919   /// exception specification information with the results.
5920   void checkExceptionSpecification(bool IsTopLevel,
5921                                    ExceptionSpecificationType EST,
5922                                    ArrayRef<ParsedType> DynamicExceptions,
5923                                    ArrayRef<SourceRange> DynamicExceptionRanges,
5924                                    Expr *NoexceptExpr,
5925                                    SmallVectorImpl<QualType> &Exceptions,
5926                                    FunctionProtoType::ExceptionSpecInfo &ESI);
5927 
5928   /// Determine if we're in a case where we need to (incorrectly) eagerly
5929   /// parse an exception specification to work around a libstdc++ bug.
5930   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5931 
5932   /// Add an exception-specification to the given member function
5933   /// (or member function template). The exception-specification was parsed
5934   /// after the method itself was declared.
5935   void actOnDelayedExceptionSpecification(Decl *Method,
5936          ExceptionSpecificationType EST,
5937          SourceRange SpecificationRange,
5938          ArrayRef<ParsedType> DynamicExceptions,
5939          ArrayRef<SourceRange> DynamicExceptionRanges,
5940          Expr *NoexceptExpr);
5941 
5942   class InheritedConstructorInfo;
5943 
5944   /// Determine if a special member function should have a deleted
5945   /// definition when it is defaulted.
5946   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5947                                  InheritedConstructorInfo *ICI = nullptr,
5948                                  bool Diagnose = false);
5949 
5950   /// Produce notes explaining why a defaulted function was defined as deleted.
5951   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5952 
5953   /// Declare the implicit default constructor for the given class.
5954   ///
5955   /// \param ClassDecl The class declaration into which the implicit
5956   /// default constructor will be added.
5957   ///
5958   /// \returns The implicitly-declared default constructor.
5959   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5960                                                      CXXRecordDecl *ClassDecl);
5961 
5962   /// DefineImplicitDefaultConstructor - Checks for feasibility of
5963   /// defining this constructor as the default constructor.
5964   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5965                                         CXXConstructorDecl *Constructor);
5966 
5967   /// Declare the implicit destructor for the given class.
5968   ///
5969   /// \param ClassDecl The class declaration into which the implicit
5970   /// destructor will be added.
5971   ///
5972   /// \returns The implicitly-declared destructor.
5973   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5974 
5975   /// DefineImplicitDestructor - Checks for feasibility of
5976   /// defining this destructor as the default destructor.
5977   void DefineImplicitDestructor(SourceLocation CurrentLocation,
5978                                 CXXDestructorDecl *Destructor);
5979 
5980   /// Build an exception spec for destructors that don't have one.
5981   ///
5982   /// C++11 says that user-defined destructors with no exception spec get one
5983   /// that looks as if the destructor was implicitly declared.
5984   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5985 
5986   /// Define the specified inheriting constructor.
5987   void DefineInheritingConstructor(SourceLocation UseLoc,
5988                                    CXXConstructorDecl *Constructor);
5989 
5990   /// Declare the implicit copy constructor for the given class.
5991   ///
5992   /// \param ClassDecl The class declaration into which the implicit
5993   /// copy constructor will be added.
5994   ///
5995   /// \returns The implicitly-declared copy constructor.
5996   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5997 
5998   /// DefineImplicitCopyConstructor - Checks for feasibility of
5999   /// defining this constructor as the copy constructor.
6000   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6001                                      CXXConstructorDecl *Constructor);
6002 
6003   /// Declare the implicit move constructor for the given class.
6004   ///
6005   /// \param ClassDecl The Class declaration into which the implicit
6006   /// move constructor will be added.
6007   ///
6008   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6009   /// declared.
6010   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6011 
6012   /// DefineImplicitMoveConstructor - Checks for feasibility of
6013   /// defining this constructor as the move constructor.
6014   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6015                                      CXXConstructorDecl *Constructor);
6016 
6017   /// Declare the implicit copy assignment operator for the given class.
6018   ///
6019   /// \param ClassDecl The class declaration into which the implicit
6020   /// copy assignment operator will be added.
6021   ///
6022   /// \returns The implicitly-declared copy assignment operator.
6023   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6024 
6025   /// Defines an implicitly-declared copy assignment operator.
6026   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6027                                     CXXMethodDecl *MethodDecl);
6028 
6029   /// Declare the implicit move assignment operator for the given class.
6030   ///
6031   /// \param ClassDecl The Class declaration into which the implicit
6032   /// move assignment operator will be added.
6033   ///
6034   /// \returns The implicitly-declared move assignment operator, or NULL if it
6035   /// wasn't declared.
6036   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6037 
6038   /// Defines an implicitly-declared move assignment operator.
6039   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6040                                     CXXMethodDecl *MethodDecl);
6041 
6042   /// Force the declaration of any implicitly-declared members of this
6043   /// class.
6044   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6045 
6046   /// Check a completed declaration of an implicit special member.
6047   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6048 
6049   /// Determine whether the given function is an implicitly-deleted
6050   /// special member function.
6051   bool isImplicitlyDeleted(FunctionDecl *FD);
6052 
6053   /// Check whether 'this' shows up in the type of a static member
6054   /// function after the (naturally empty) cv-qualifier-seq would be.
6055   ///
6056   /// \returns true if an error occurred.
6057   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6058 
6059   /// Whether this' shows up in the exception specification of a static
6060   /// member function.
6061   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6062 
6063   /// Check whether 'this' shows up in the attributes of the given
6064   /// static member function.
6065   ///
6066   /// \returns true if an error occurred.
6067   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6068 
6069   /// MaybeBindToTemporary - If the passed in expression has a record type with
6070   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6071   /// it simply returns the passed in expression.
6072   ExprResult MaybeBindToTemporary(Expr *E);
6073 
6074   /// Wrap the expression in a ConstantExpr if it is a potential immediate
6075   /// invocation.
6076   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6077 
6078   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6079                                QualType DeclInitType, MultiExprArg ArgsPtr,
6080                                SourceLocation Loc,
6081                                SmallVectorImpl<Expr *> &ConvertedArgs,
6082                                bool AllowExplicit = false,
6083                                bool IsListInitialization = false);
6084 
6085   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6086                                           SourceLocation NameLoc,
6087                                           IdentifierInfo &Name);
6088 
6089   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6090                                 Scope *S, CXXScopeSpec &SS,
6091                                 bool EnteringContext);
6092   ParsedType getDestructorName(SourceLocation TildeLoc,
6093                                IdentifierInfo &II, SourceLocation NameLoc,
6094                                Scope *S, CXXScopeSpec &SS,
6095                                ParsedType ObjectType,
6096                                bool EnteringContext);
6097 
6098   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6099                                           ParsedType ObjectType);
6100 
6101   // Checks that reinterpret casts don't have undefined behavior.
6102   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6103                                       bool IsDereference, SourceRange Range);
6104 
6105   // Checks that the vector type should be initialized from a scalar
6106   // by splatting the value rather than populating a single element.
6107   // This is the case for AltiVecVector types as well as with
6108   // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6109   bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6110 
6111   /// ActOnCXXNamedCast - Parse
6112   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6113   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6114                                tok::TokenKind Kind,
6115                                SourceLocation LAngleBracketLoc,
6116                                Declarator &D,
6117                                SourceLocation RAngleBracketLoc,
6118                                SourceLocation LParenLoc,
6119                                Expr *E,
6120                                SourceLocation RParenLoc);
6121 
6122   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6123                                tok::TokenKind Kind,
6124                                TypeSourceInfo *Ty,
6125                                Expr *E,
6126                                SourceRange AngleBrackets,
6127                                SourceRange Parens);
6128 
6129   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6130                                      ExprResult Operand,
6131                                      SourceLocation RParenLoc);
6132 
6133   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6134                                      Expr *Operand, SourceLocation RParenLoc);
6135 
6136   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6137                             SourceLocation TypeidLoc,
6138                             TypeSourceInfo *Operand,
6139                             SourceLocation RParenLoc);
6140   ExprResult BuildCXXTypeId(QualType TypeInfoType,
6141                             SourceLocation TypeidLoc,
6142                             Expr *Operand,
6143                             SourceLocation RParenLoc);
6144 
6145   /// ActOnCXXTypeid - Parse typeid( something ).
6146   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6147                             SourceLocation LParenLoc, bool isType,
6148                             void *TyOrExpr,
6149                             SourceLocation RParenLoc);
6150 
6151   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6152                             SourceLocation TypeidLoc,
6153                             TypeSourceInfo *Operand,
6154                             SourceLocation RParenLoc);
6155   ExprResult BuildCXXUuidof(QualType TypeInfoType,
6156                             SourceLocation TypeidLoc,
6157                             Expr *Operand,
6158                             SourceLocation RParenLoc);
6159 
6160   /// ActOnCXXUuidof - Parse __uuidof( something ).
6161   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6162                             SourceLocation LParenLoc, bool isType,
6163                             void *TyOrExpr,
6164                             SourceLocation RParenLoc);
6165 
6166   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6167   ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6168                               tok::TokenKind Operator,
6169                               SourceLocation EllipsisLoc, Expr *RHS,
6170                               SourceLocation RParenLoc);
6171   ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6172                               SourceLocation LParenLoc, Expr *LHS,
6173                               BinaryOperatorKind Operator,
6174                               SourceLocation EllipsisLoc, Expr *RHS,
6175                               SourceLocation RParenLoc,
6176                               Optional<unsigned> NumExpansions);
6177   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6178                                    BinaryOperatorKind Operator);
6179 
6180   //// ActOnCXXThis -  Parse 'this' pointer.
6181   ExprResult ActOnCXXThis(SourceLocation loc);
6182 
6183   /// Build a CXXThisExpr and mark it referenced in the current context.
6184   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6185   void MarkThisReferenced(CXXThisExpr *This);
6186 
6187   /// Try to retrieve the type of the 'this' pointer.
6188   ///
6189   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6190   QualType getCurrentThisType();
6191 
6192   /// When non-NULL, the C++ 'this' expression is allowed despite the
6193   /// current context not being a non-static member function. In such cases,
6194   /// this provides the type used for 'this'.
6195   QualType CXXThisTypeOverride;
6196 
6197   /// RAII object used to temporarily allow the C++ 'this' expression
6198   /// to be used, with the given qualifiers on the current class type.
6199   class CXXThisScopeRAII {
6200     Sema &S;
6201     QualType OldCXXThisTypeOverride;
6202     bool Enabled;
6203 
6204   public:
6205     /// Introduce a new scope where 'this' may be allowed (when enabled),
6206     /// using the given declaration (which is either a class template or a
6207     /// class) along with the given qualifiers.
6208     /// along with the qualifiers placed on '*this'.
6209     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6210                      bool Enabled = true);
6211 
6212     ~CXXThisScopeRAII();
6213   };
6214 
6215   /// Make sure the value of 'this' is actually available in the current
6216   /// context, if it is a potentially evaluated context.
6217   ///
6218   /// \param Loc The location at which the capture of 'this' occurs.
6219   ///
6220   /// \param Explicit Whether 'this' is explicitly captured in a lambda
6221   /// capture list.
6222   ///
6223   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6224   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6225   /// This is useful when enclosing lambdas must speculatively capture
6226   /// 'this' that may or may not be used in certain specializations of
6227   /// a nested generic lambda (depending on whether the name resolves to
6228   /// a non-static member function or a static function).
6229   /// \return returns 'true' if failed, 'false' if success.
6230   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6231       bool BuildAndDiagnose = true,
6232       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6233       bool ByCopy = false);
6234 
6235   /// Determine whether the given type is the type of *this that is used
6236   /// outside of the body of a member function for a type that is currently
6237   /// being defined.
6238   bool isThisOutsideMemberFunctionBody(QualType BaseType);
6239 
6240   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6241   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6242 
6243 
6244   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6245   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6246 
6247   ExprResult
6248   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6249                                  SourceLocation AtLoc, SourceLocation RParen);
6250 
6251   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6252   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6253 
6254   //// ActOnCXXThrow -  Parse throw expressions.
6255   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6256   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6257                            bool IsThrownVarInScope);
6258   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6259 
6260   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6261   /// Can be interpreted either as function-style casting ("int(x)")
6262   /// or class type construction ("ClassType(x,y,z)")
6263   /// or creation of a value-initialized type ("int()").
6264   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6265                                        SourceLocation LParenOrBraceLoc,
6266                                        MultiExprArg Exprs,
6267                                        SourceLocation RParenOrBraceLoc,
6268                                        bool ListInitialization);
6269 
6270   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6271                                        SourceLocation LParenLoc,
6272                                        MultiExprArg Exprs,
6273                                        SourceLocation RParenLoc,
6274                                        bool ListInitialization);
6275 
6276   /// ActOnCXXNew - Parsed a C++ 'new' expression.
6277   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6278                          SourceLocation PlacementLParen,
6279                          MultiExprArg PlacementArgs,
6280                          SourceLocation PlacementRParen,
6281                          SourceRange TypeIdParens, Declarator &D,
6282                          Expr *Initializer);
6283   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6284                          SourceLocation PlacementLParen,
6285                          MultiExprArg PlacementArgs,
6286                          SourceLocation PlacementRParen,
6287                          SourceRange TypeIdParens,
6288                          QualType AllocType,
6289                          TypeSourceInfo *AllocTypeInfo,
6290                          Optional<Expr *> ArraySize,
6291                          SourceRange DirectInitRange,
6292                          Expr *Initializer);
6293 
6294   /// Determine whether \p FD is an aligned allocation or deallocation
6295   /// function that is unavailable.
6296   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6297 
6298   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6299   /// function that is unavailable.
6300   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6301                                             SourceLocation Loc);
6302 
6303   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6304                           SourceRange R);
6305 
6306   /// The scope in which to find allocation functions.
6307   enum AllocationFunctionScope {
6308     /// Only look for allocation functions in the global scope.
6309     AFS_Global,
6310     /// Only look for allocation functions in the scope of the
6311     /// allocated class.
6312     AFS_Class,
6313     /// Look for allocation functions in both the global scope
6314     /// and in the scope of the allocated class.
6315     AFS_Both
6316   };
6317 
6318   /// Finds the overloads of operator new and delete that are appropriate
6319   /// for the allocation.
6320   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6321                                AllocationFunctionScope NewScope,
6322                                AllocationFunctionScope DeleteScope,
6323                                QualType AllocType, bool IsArray,
6324                                bool &PassAlignment, MultiExprArg PlaceArgs,
6325                                FunctionDecl *&OperatorNew,
6326                                FunctionDecl *&OperatorDelete,
6327                                bool Diagnose = true);
6328   void DeclareGlobalNewDelete();
6329   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6330                                        ArrayRef<QualType> Params);
6331 
6332   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6333                                 DeclarationName Name, FunctionDecl* &Operator,
6334                                 bool Diagnose = true);
6335   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6336                                               bool CanProvideSize,
6337                                               bool Overaligned,
6338                                               DeclarationName Name);
6339   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6340                                                       CXXRecordDecl *RD);
6341 
6342   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6343   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6344                             bool UseGlobal, bool ArrayForm,
6345                             Expr *Operand);
6346   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6347                             bool IsDelete, bool CallCanBeVirtual,
6348                             bool WarnOnNonAbstractTypes,
6349                             SourceLocation DtorLoc);
6350 
6351   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6352                                Expr *Operand, SourceLocation RParen);
6353   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6354                                   SourceLocation RParen);
6355 
6356   /// Parsed one of the type trait support pseudo-functions.
6357   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6358                             ArrayRef<ParsedType> Args,
6359                             SourceLocation RParenLoc);
6360   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6361                             ArrayRef<TypeSourceInfo *> Args,
6362                             SourceLocation RParenLoc);
6363 
6364   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6365   /// pseudo-functions.
6366   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6367                                  SourceLocation KWLoc,
6368                                  ParsedType LhsTy,
6369                                  Expr *DimExpr,
6370                                  SourceLocation RParen);
6371 
6372   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6373                                  SourceLocation KWLoc,
6374                                  TypeSourceInfo *TSInfo,
6375                                  Expr *DimExpr,
6376                                  SourceLocation RParen);
6377 
6378   /// ActOnExpressionTrait - Parsed one of the unary type trait support
6379   /// pseudo-functions.
6380   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6381                                   SourceLocation KWLoc,
6382                                   Expr *Queried,
6383                                   SourceLocation RParen);
6384 
6385   ExprResult BuildExpressionTrait(ExpressionTrait OET,
6386                                   SourceLocation KWLoc,
6387                                   Expr *Queried,
6388                                   SourceLocation RParen);
6389 
6390   ExprResult ActOnStartCXXMemberReference(Scope *S,
6391                                           Expr *Base,
6392                                           SourceLocation OpLoc,
6393                                           tok::TokenKind OpKind,
6394                                           ParsedType &ObjectType,
6395                                           bool &MayBePseudoDestructor);
6396 
6397   ExprResult BuildPseudoDestructorExpr(Expr *Base,
6398                                        SourceLocation OpLoc,
6399                                        tok::TokenKind OpKind,
6400                                        const CXXScopeSpec &SS,
6401                                        TypeSourceInfo *ScopeType,
6402                                        SourceLocation CCLoc,
6403                                        SourceLocation TildeLoc,
6404                                      PseudoDestructorTypeStorage DestroyedType);
6405 
6406   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6407                                        SourceLocation OpLoc,
6408                                        tok::TokenKind OpKind,
6409                                        CXXScopeSpec &SS,
6410                                        UnqualifiedId &FirstTypeName,
6411                                        SourceLocation CCLoc,
6412                                        SourceLocation TildeLoc,
6413                                        UnqualifiedId &SecondTypeName);
6414 
6415   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6416                                        SourceLocation OpLoc,
6417                                        tok::TokenKind OpKind,
6418                                        SourceLocation TildeLoc,
6419                                        const DeclSpec& DS);
6420 
6421   /// MaybeCreateExprWithCleanups - If the current full-expression
6422   /// requires any cleanups, surround it with a ExprWithCleanups node.
6423   /// Otherwise, just returns the passed-in expression.
6424   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6425   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6426   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6427 
6428   MaterializeTemporaryExpr *
6429   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6430                                  bool BoundToLvalueReference);
6431 
ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)6432   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6433     return ActOnFinishFullExpr(
6434         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6435   }
6436   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6437                                  bool DiscardedValue, bool IsConstexpr = false);
6438   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6439 
6440   // Marks SS invalid if it represents an incomplete type.
6441   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6442   // Complete an enum decl, maybe without a scope spec.
6443   bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6444                                CXXScopeSpec *SS = nullptr);
6445 
6446   DeclContext *computeDeclContext(QualType T);
6447   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6448                                   bool EnteringContext = false);
6449   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6450   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6451 
6452   /// The parser has parsed a global nested-name-specifier '::'.
6453   ///
6454   /// \param CCLoc The location of the '::'.
6455   ///
6456   /// \param SS The nested-name-specifier, which will be updated in-place
6457   /// to reflect the parsed nested-name-specifier.
6458   ///
6459   /// \returns true if an error occurred, false otherwise.
6460   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6461 
6462   /// The parser has parsed a '__super' nested-name-specifier.
6463   ///
6464   /// \param SuperLoc The location of the '__super' keyword.
6465   ///
6466   /// \param ColonColonLoc The location of the '::'.
6467   ///
6468   /// \param SS The nested-name-specifier, which will be updated in-place
6469   /// to reflect the parsed nested-name-specifier.
6470   ///
6471   /// \returns true if an error occurred, false otherwise.
6472   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6473                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6474 
6475   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6476                                        bool *CanCorrect = nullptr);
6477   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6478 
6479   /// Keeps information about an identifier in a nested-name-spec.
6480   ///
6481   struct NestedNameSpecInfo {
6482     /// The type of the object, if we're parsing nested-name-specifier in
6483     /// a member access expression.
6484     ParsedType ObjectType;
6485 
6486     /// The identifier preceding the '::'.
6487     IdentifierInfo *Identifier;
6488 
6489     /// The location of the identifier.
6490     SourceLocation IdentifierLoc;
6491 
6492     /// The location of the '::'.
6493     SourceLocation CCLoc;
6494 
6495     /// Creates info object for the most typical case.
6496     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6497              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
ObjectTypeNestedNameSpecInfo6498       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6499         CCLoc(ColonColonLoc) {
6500     }
6501 
NestedNameSpecInfoNestedNameSpecInfo6502     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6503                        SourceLocation ColonColonLoc, QualType ObjectType)
6504       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6505         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6506     }
6507   };
6508 
6509   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6510                                     NestedNameSpecInfo &IdInfo);
6511 
6512   bool BuildCXXNestedNameSpecifier(Scope *S,
6513                                    NestedNameSpecInfo &IdInfo,
6514                                    bool EnteringContext,
6515                                    CXXScopeSpec &SS,
6516                                    NamedDecl *ScopeLookupResult,
6517                                    bool ErrorRecoveryLookup,
6518                                    bool *IsCorrectedToColon = nullptr,
6519                                    bool OnlyNamespace = false);
6520 
6521   /// The parser has parsed a nested-name-specifier 'identifier::'.
6522   ///
6523   /// \param S The scope in which this nested-name-specifier occurs.
6524   ///
6525   /// \param IdInfo Parser information about an identifier in the
6526   /// nested-name-spec.
6527   ///
6528   /// \param EnteringContext Whether we're entering the context nominated by
6529   /// this nested-name-specifier.
6530   ///
6531   /// \param SS The nested-name-specifier, which is both an input
6532   /// parameter (the nested-name-specifier before this type) and an
6533   /// output parameter (containing the full nested-name-specifier,
6534   /// including this new type).
6535   ///
6536   /// \param ErrorRecoveryLookup If true, then this method is called to improve
6537   /// error recovery. In this case do not emit error message.
6538   ///
6539   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6540   /// are allowed.  The bool value pointed by this parameter is set to 'true'
6541   /// if the identifier is treated as if it was followed by ':', not '::'.
6542   ///
6543   /// \param OnlyNamespace If true, only considers namespaces in lookup.
6544   ///
6545   /// \returns true if an error occurred, false otherwise.
6546   bool ActOnCXXNestedNameSpecifier(Scope *S,
6547                                    NestedNameSpecInfo &IdInfo,
6548                                    bool EnteringContext,
6549                                    CXXScopeSpec &SS,
6550                                    bool ErrorRecoveryLookup = false,
6551                                    bool *IsCorrectedToColon = nullptr,
6552                                    bool OnlyNamespace = false);
6553 
6554   ExprResult ActOnDecltypeExpression(Expr *E);
6555 
6556   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6557                                            const DeclSpec &DS,
6558                                            SourceLocation ColonColonLoc);
6559 
6560   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6561                                  NestedNameSpecInfo &IdInfo,
6562                                  bool EnteringContext);
6563 
6564   /// The parser has parsed a nested-name-specifier
6565   /// 'template[opt] template-name < template-args >::'.
6566   ///
6567   /// \param S The scope in which this nested-name-specifier occurs.
6568   ///
6569   /// \param SS The nested-name-specifier, which is both an input
6570   /// parameter (the nested-name-specifier before this type) and an
6571   /// output parameter (containing the full nested-name-specifier,
6572   /// including this new type).
6573   ///
6574   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6575   /// \param TemplateName the template name.
6576   /// \param TemplateNameLoc The location of the template name.
6577   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6578   /// \param TemplateArgs The template arguments.
6579   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6580   /// \param CCLoc The location of the '::'.
6581   ///
6582   /// \param EnteringContext Whether we're entering the context of the
6583   /// nested-name-specifier.
6584   ///
6585   ///
6586   /// \returns true if an error occurred, false otherwise.
6587   bool ActOnCXXNestedNameSpecifier(Scope *S,
6588                                    CXXScopeSpec &SS,
6589                                    SourceLocation TemplateKWLoc,
6590                                    TemplateTy TemplateName,
6591                                    SourceLocation TemplateNameLoc,
6592                                    SourceLocation LAngleLoc,
6593                                    ASTTemplateArgsPtr TemplateArgs,
6594                                    SourceLocation RAngleLoc,
6595                                    SourceLocation CCLoc,
6596                                    bool EnteringContext);
6597 
6598   /// Given a C++ nested-name-specifier, produce an annotation value
6599   /// that the parser can use later to reconstruct the given
6600   /// nested-name-specifier.
6601   ///
6602   /// \param SS A nested-name-specifier.
6603   ///
6604   /// \returns A pointer containing all of the information in the
6605   /// nested-name-specifier \p SS.
6606   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6607 
6608   /// Given an annotation pointer for a nested-name-specifier, restore
6609   /// the nested-name-specifier structure.
6610   ///
6611   /// \param Annotation The annotation pointer, produced by
6612   /// \c SaveNestedNameSpecifierAnnotation().
6613   ///
6614   /// \param AnnotationRange The source range corresponding to the annotation.
6615   ///
6616   /// \param SS The nested-name-specifier that will be updated with the contents
6617   /// of the annotation pointer.
6618   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6619                                             SourceRange AnnotationRange,
6620                                             CXXScopeSpec &SS);
6621 
6622   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6623 
6624   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6625   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6626   /// After this method is called, according to [C++ 3.4.3p3], names should be
6627   /// looked up in the declarator-id's scope, until the declarator is parsed and
6628   /// ActOnCXXExitDeclaratorScope is called.
6629   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6630   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6631 
6632   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6633   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6634   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6635   /// Used to indicate that names should revert to being looked up in the
6636   /// defining scope.
6637   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6638 
6639   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6640   /// initializer for the declaration 'Dcl'.
6641   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6642   /// static data member of class X, names should be looked up in the scope of
6643   /// class X.
6644   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6645 
6646   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6647   /// initializer for the declaration 'Dcl'.
6648   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6649 
6650   /// Create a new lambda closure type.
6651   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6652                                          TypeSourceInfo *Info,
6653                                          bool KnownDependent,
6654                                          LambdaCaptureDefault CaptureDefault);
6655 
6656   /// Start the definition of a lambda expression.
6657   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6658                                        SourceRange IntroducerRange,
6659                                        TypeSourceInfo *MethodType,
6660                                        SourceLocation EndLoc,
6661                                        ArrayRef<ParmVarDecl *> Params,
6662                                        ConstexprSpecKind ConstexprKind,
6663                                        Expr *TrailingRequiresClause);
6664 
6665   /// Number lambda for linkage purposes if necessary.
6666   void handleLambdaNumbering(
6667       CXXRecordDecl *Class, CXXMethodDecl *Method,
6668       Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
6669 
6670   /// Endow the lambda scope info with the relevant properties.
6671   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6672                         CXXMethodDecl *CallOperator,
6673                         SourceRange IntroducerRange,
6674                         LambdaCaptureDefault CaptureDefault,
6675                         SourceLocation CaptureDefaultLoc,
6676                         bool ExplicitParams,
6677                         bool ExplicitResultType,
6678                         bool Mutable);
6679 
6680   /// Perform initialization analysis of the init-capture and perform
6681   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6682   /// not being used to initialize a reference.
actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)6683   ParsedType actOnLambdaInitCaptureInitialization(
6684       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6685       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6686     return ParsedType::make(buildLambdaInitCaptureInitialization(
6687         Loc, ByRef, EllipsisLoc, None, Id,
6688         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6689   }
6690   QualType buildLambdaInitCaptureInitialization(
6691       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6692       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6693       Expr *&Init);
6694 
6695   /// Create a dummy variable within the declcontext of the lambda's
6696   ///  call operator, for name lookup purposes for a lambda init capture.
6697   ///
6698   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6699   ///  variables appropriately.
6700   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6701                                           QualType InitCaptureType,
6702                                           SourceLocation EllipsisLoc,
6703                                           IdentifierInfo *Id,
6704                                           unsigned InitStyle, Expr *Init);
6705 
6706   /// Add an init-capture to a lambda scope.
6707   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6708 
6709   /// Note that we have finished the explicit captures for the
6710   /// given lambda.
6711   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6712 
6713   /// \brief This is called after parsing the explicit template parameter list
6714   /// on a lambda (if it exists) in C++2a.
6715   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6716                                                 ArrayRef<NamedDecl *> TParams,
6717                                                 SourceLocation RAngleLoc,
6718                                                 ExprResult RequiresClause);
6719 
6720   /// Introduce the lambda parameters into scope.
6721   void addLambdaParameters(
6722       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6723       CXXMethodDecl *CallOperator, Scope *CurScope);
6724 
6725   /// Deduce a block or lambda's return type based on the return
6726   /// statements present in the body.
6727   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6728 
6729   /// ActOnStartOfLambdaDefinition - This is called just before we start
6730   /// parsing the body of a lambda; it analyzes the explicit captures and
6731   /// arguments, and sets up various data-structures for the body of the
6732   /// lambda.
6733   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6734                                     Declarator &ParamInfo, Scope *CurScope);
6735 
6736   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6737   /// is invoked to pop the information about the lambda.
6738   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6739                         bool IsInstantiation = false);
6740 
6741   /// ActOnLambdaExpr - This is called when the body of a lambda expression
6742   /// was successfully completed.
6743   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6744                              Scope *CurScope);
6745 
6746   /// Does copying/destroying the captured variable have side effects?
6747   bool CaptureHasSideEffects(const sema::Capture &From);
6748 
6749   /// Diagnose if an explicit lambda capture is unused. Returns true if a
6750   /// diagnostic is emitted.
6751   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6752                                    const sema::Capture &From);
6753 
6754   /// Build a FieldDecl suitable to hold the given capture.
6755   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6756 
6757   /// Initialize the given capture with a suitable expression.
6758   ExprResult BuildCaptureInit(const sema::Capture &Capture,
6759                               SourceLocation ImplicitCaptureLoc,
6760                               bool IsOpenMPMapping = false);
6761 
6762   /// Complete a lambda-expression having processed and attached the
6763   /// lambda body.
6764   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6765                              sema::LambdaScopeInfo *LSI);
6766 
6767   /// Get the return type to use for a lambda's conversion function(s) to
6768   /// function pointer type, given the type of the call operator.
6769   QualType
6770   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
6771                                         CallingConv CC);
6772 
6773   /// Define the "body" of the conversion from a lambda object to a
6774   /// function pointer.
6775   ///
6776   /// This routine doesn't actually define a sensible body; rather, it fills
6777   /// in the initialization expression needed to copy the lambda object into
6778   /// the block, and IR generation actually generates the real body of the
6779   /// block pointer conversion.
6780   void DefineImplicitLambdaToFunctionPointerConversion(
6781          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6782 
6783   /// Define the "body" of the conversion from a lambda object to a
6784   /// block pointer.
6785   ///
6786   /// This routine doesn't actually define a sensible body; rather, it fills
6787   /// in the initialization expression needed to copy the lambda object into
6788   /// the block, and IR generation actually generates the real body of the
6789   /// block pointer conversion.
6790   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6791                                                     CXXConversionDecl *Conv);
6792 
6793   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6794                                            SourceLocation ConvLocation,
6795                                            CXXConversionDecl *Conv,
6796                                            Expr *Src);
6797 
6798   /// Check whether the given expression is a valid constraint expression.
6799   /// A diagnostic is emitted if it is not, false is returned, and
6800   /// PossibleNonPrimary will be set to true if the failure might be due to a
6801   /// non-primary expression being used as an atomic constraint.
6802   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6803                                  bool *PossibleNonPrimary = nullptr,
6804                                  bool IsTrailingRequiresClause = false);
6805 
6806 private:
6807   /// Caches pairs of template-like decls whose associated constraints were
6808   /// checked for subsumption and whether or not the first's constraints did in
6809   /// fact subsume the second's.
6810   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6811   /// Caches the normalized associated constraints of declarations (concepts or
6812   /// constrained declarations). If an error occurred while normalizing the
6813   /// associated constraints of the template or concept, nullptr will be cached
6814   /// here.
6815   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6816       NormalizationCache;
6817 
6818   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6819       SatisfactionCache;
6820 
6821 public:
6822   const NormalizedConstraint *
6823   getNormalizedAssociatedConstraints(
6824       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6825 
6826   /// \brief Check whether the given declaration's associated constraints are
6827   /// at least as constrained than another declaration's according to the
6828   /// partial ordering of constraints.
6829   ///
6830   /// \param Result If no error occurred, receives the result of true if D1 is
6831   /// at least constrained than D2, and false otherwise.
6832   ///
6833   /// \returns true if an error occurred, false otherwise.
6834   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6835                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
6836                               bool &Result);
6837 
6838   /// If D1 was not at least as constrained as D2, but would've been if a pair
6839   /// of atomic constraints involved had been declared in a concept and not
6840   /// repeated in two separate places in code.
6841   /// \returns true if such a diagnostic was emitted, false otherwise.
6842   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6843       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6844 
6845   /// \brief Check whether the given list of constraint expressions are
6846   /// satisfied (as if in a 'conjunction') given template arguments.
6847   /// \param Template the template-like entity that triggered the constraints
6848   /// check (either a concept or a constrained entity).
6849   /// \param ConstraintExprs a list of constraint expressions, treated as if
6850   /// they were 'AND'ed together.
6851   /// \param TemplateArgs the list of template arguments to substitute into the
6852   /// constraint expression.
6853   /// \param TemplateIDRange The source range of the template id that
6854   /// caused the constraints check.
6855   /// \param Satisfaction if true is returned, will contain details of the
6856   /// satisfaction, with enough information to diagnose an unsatisfied
6857   /// expression.
6858   /// \returns true if an error occurred and satisfaction could not be checked,
6859   /// false otherwise.
6860   bool CheckConstraintSatisfaction(
6861       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6862       ArrayRef<TemplateArgument> TemplateArgs,
6863       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6864 
6865   /// \brief Check whether the given non-dependent constraint expression is
6866   /// satisfied. Returns false and updates Satisfaction with the satisfaction
6867   /// verdict if successful, emits a diagnostic and returns true if an error
6868   /// occured and satisfaction could not be determined.
6869   ///
6870   /// \returns true if an error occurred, false otherwise.
6871   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6872                                    ConstraintSatisfaction &Satisfaction);
6873 
6874   /// Check whether the given function decl's trailing requires clause is
6875   /// satisfied, if any. Returns false and updates Satisfaction with the
6876   /// satisfaction verdict if successful, emits a diagnostic and returns true if
6877   /// an error occured and satisfaction could not be determined.
6878   ///
6879   /// \returns true if an error occurred, false otherwise.
6880   bool CheckFunctionConstraints(const FunctionDecl *FD,
6881                                 ConstraintSatisfaction &Satisfaction,
6882                                 SourceLocation UsageLoc = SourceLocation());
6883 
6884 
6885   /// \brief Ensure that the given template arguments satisfy the constraints
6886   /// associated with the given template, emitting a diagnostic if they do not.
6887   ///
6888   /// \param Template The template to which the template arguments are being
6889   /// provided.
6890   ///
6891   /// \param TemplateArgs The converted, canonicalized template arguments.
6892   ///
6893   /// \param TemplateIDRange The source range of the template id that
6894   /// caused the constraints check.
6895   ///
6896   /// \returns true if the constrains are not satisfied or could not be checked
6897   /// for satisfaction, false if the constraints are satisfied.
6898   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6899                                        ArrayRef<TemplateArgument> TemplateArgs,
6900                                              SourceRange TemplateIDRange);
6901 
6902   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6903   /// unsatisfied.
6904   /// \param First whether this is the first time an unsatisfied constraint is
6905   /// diagnosed for this error.
6906   void
6907   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6908                                 bool First = true);
6909 
6910   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6911   /// unsatisfied.
6912   void
6913   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6914                                 bool First = true);
6915 
6916   // ParseObjCStringLiteral - Parse Objective-C string literals.
6917   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6918                                     ArrayRef<Expr *> Strings);
6919 
6920   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6921 
6922   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6923   /// numeric literal expression. Type of the expression will be "NSNumber *"
6924   /// or "id" if NSNumber is unavailable.
6925   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6926   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6927                                   bool Value);
6928   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6929 
6930   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6931   /// '@' prefixed parenthesized expression. The type of the expression will
6932   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6933   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6934   /// "const char *" or C structure with attribute 'objc_boxable'.
6935   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6936 
6937   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6938                                           Expr *IndexExpr,
6939                                           ObjCMethodDecl *getterMethod,
6940                                           ObjCMethodDecl *setterMethod);
6941 
6942   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6943                                MutableArrayRef<ObjCDictionaryElement> Elements);
6944 
6945   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6946                                   TypeSourceInfo *EncodedTypeInfo,
6947                                   SourceLocation RParenLoc);
6948   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6949                                     CXXConversionDecl *Method,
6950                                     bool HadMultipleCandidates);
6951 
6952   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6953                                        SourceLocation EncodeLoc,
6954                                        SourceLocation LParenLoc,
6955                                        ParsedType Ty,
6956                                        SourceLocation RParenLoc);
6957 
6958   /// ParseObjCSelectorExpression - Build selector expression for \@selector
6959   ExprResult ParseObjCSelectorExpression(Selector Sel,
6960                                          SourceLocation AtLoc,
6961                                          SourceLocation SelLoc,
6962                                          SourceLocation LParenLoc,
6963                                          SourceLocation RParenLoc,
6964                                          bool WarnMultipleSelectors);
6965 
6966   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6967   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6968                                          SourceLocation AtLoc,
6969                                          SourceLocation ProtoLoc,
6970                                          SourceLocation LParenLoc,
6971                                          SourceLocation ProtoIdLoc,
6972                                          SourceLocation RParenLoc);
6973 
6974   //===--------------------------------------------------------------------===//
6975   // C++ Declarations
6976   //
6977   Decl *ActOnStartLinkageSpecification(Scope *S,
6978                                        SourceLocation ExternLoc,
6979                                        Expr *LangStr,
6980                                        SourceLocation LBraceLoc);
6981   Decl *ActOnFinishLinkageSpecification(Scope *S,
6982                                         Decl *LinkageSpec,
6983                                         SourceLocation RBraceLoc);
6984 
6985 
6986   //===--------------------------------------------------------------------===//
6987   // C++ Classes
6988   //
6989   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6990   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6991                           const CXXScopeSpec *SS = nullptr);
6992   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6993 
6994   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6995                             SourceLocation ColonLoc,
6996                             const ParsedAttributesView &Attrs);
6997 
6998   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6999                                  Declarator &D,
7000                                  MultiTemplateParamsArg TemplateParameterLists,
7001                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
7002                                  InClassInitStyle InitStyle);
7003 
7004   void ActOnStartCXXInClassMemberInitializer();
7005   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7006                                               SourceLocation EqualLoc,
7007                                               Expr *Init);
7008 
7009   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7010                                     Scope *S,
7011                                     CXXScopeSpec &SS,
7012                                     IdentifierInfo *MemberOrBase,
7013                                     ParsedType TemplateTypeTy,
7014                                     const DeclSpec &DS,
7015                                     SourceLocation IdLoc,
7016                                     SourceLocation LParenLoc,
7017                                     ArrayRef<Expr *> Args,
7018                                     SourceLocation RParenLoc,
7019                                     SourceLocation EllipsisLoc);
7020 
7021   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7022                                     Scope *S,
7023                                     CXXScopeSpec &SS,
7024                                     IdentifierInfo *MemberOrBase,
7025                                     ParsedType TemplateTypeTy,
7026                                     const DeclSpec &DS,
7027                                     SourceLocation IdLoc,
7028                                     Expr *InitList,
7029                                     SourceLocation EllipsisLoc);
7030 
7031   MemInitResult BuildMemInitializer(Decl *ConstructorD,
7032                                     Scope *S,
7033                                     CXXScopeSpec &SS,
7034                                     IdentifierInfo *MemberOrBase,
7035                                     ParsedType TemplateTypeTy,
7036                                     const DeclSpec &DS,
7037                                     SourceLocation IdLoc,
7038                                     Expr *Init,
7039                                     SourceLocation EllipsisLoc);
7040 
7041   MemInitResult BuildMemberInitializer(ValueDecl *Member,
7042                                        Expr *Init,
7043                                        SourceLocation IdLoc);
7044 
7045   MemInitResult BuildBaseInitializer(QualType BaseType,
7046                                      TypeSourceInfo *BaseTInfo,
7047                                      Expr *Init,
7048                                      CXXRecordDecl *ClassDecl,
7049                                      SourceLocation EllipsisLoc);
7050 
7051   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7052                                            Expr *Init,
7053                                            CXXRecordDecl *ClassDecl);
7054 
7055   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7056                                 CXXCtorInitializer *Initializer);
7057 
7058   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
7059                            ArrayRef<CXXCtorInitializer *> Initializers = None);
7060 
7061   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7062 
7063 
7064   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7065   /// mark all the non-trivial destructors of its members and bases as
7066   /// referenced.
7067   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7068                                               CXXRecordDecl *Record);
7069 
7070   /// Mark destructors of virtual bases of this class referenced. In the Itanium
7071   /// C++ ABI, this is done when emitting a destructor for any non-abstract
7072   /// class. In the Microsoft C++ ABI, this is done any time a class's
7073   /// destructor is referenced.
7074   void MarkVirtualBaseDestructorsReferenced(
7075       SourceLocation Location, CXXRecordDecl *ClassDecl,
7076       llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7077 
7078   /// Do semantic checks to allow the complete destructor variant to be emitted
7079   /// when the destructor is defined in another translation unit. In the Itanium
7080   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7081   /// can be emitted in separate TUs. To emit the complete variant, run a subset
7082   /// of the checks performed when emitting a regular destructor.
7083   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7084                                       CXXDestructorDecl *Dtor);
7085 
7086   /// The list of classes whose vtables have been used within
7087   /// this translation unit, and the source locations at which the
7088   /// first use occurred.
7089   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7090 
7091   /// The list of vtables that are required but have not yet been
7092   /// materialized.
7093   SmallVector<VTableUse, 16> VTableUses;
7094 
7095   /// The set of classes whose vtables have been used within
7096   /// this translation unit, and a bit that will be true if the vtable is
7097   /// required to be emitted (otherwise, it should be emitted only if needed
7098   /// by code generation).
7099   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7100 
7101   /// Load any externally-stored vtable uses.
7102   void LoadExternalVTableUses();
7103 
7104   /// Note that the vtable for the given class was used at the
7105   /// given location.
7106   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7107                       bool DefinitionRequired = false);
7108 
7109   /// Mark the exception specifications of all virtual member functions
7110   /// in the given class as needed.
7111   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7112                                              const CXXRecordDecl *RD);
7113 
7114   /// MarkVirtualMembersReferenced - Will mark all members of the given
7115   /// CXXRecordDecl referenced.
7116   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7117                                     bool ConstexprOnly = false);
7118 
7119   /// Define all of the vtables that have been used in this
7120   /// translation unit and reference any virtual members used by those
7121   /// vtables.
7122   ///
7123   /// \returns true if any work was done, false otherwise.
7124   bool DefineUsedVTables();
7125 
7126   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7127 
7128   void ActOnMemInitializers(Decl *ConstructorDecl,
7129                             SourceLocation ColonLoc,
7130                             ArrayRef<CXXCtorInitializer*> MemInits,
7131                             bool AnyErrors);
7132 
7133   /// Check class-level dllimport/dllexport attribute. The caller must
7134   /// ensure that referenceDLLExportedClassMethods is called some point later
7135   /// when all outer classes of Class are complete.
7136   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7137   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7138 
7139   void referenceDLLExportedClassMethods();
7140 
7141   void propagateDLLAttrToBaseClassTemplate(
7142       CXXRecordDecl *Class, Attr *ClassAttr,
7143       ClassTemplateSpecializationDecl *BaseTemplateSpec,
7144       SourceLocation BaseLoc);
7145 
7146   /// Add gsl::Pointer attribute to std::container::iterator
7147   /// \param ND The declaration that introduces the name
7148   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7149   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7150 
7151   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7152   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7153 
7154   /// Add [[gsl::Pointer]] attributes for std:: types.
7155   void inferGslPointerAttribute(TypedefNameDecl *TD);
7156 
7157   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7158 
7159   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7160   /// conditions that are needed for the attribute to have an effect.
7161   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7162 
7163   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7164                                          Decl *TagDecl, SourceLocation LBrac,
7165                                          SourceLocation RBrac,
7166                                          const ParsedAttributesView &AttrList);
7167   void ActOnFinishCXXMemberDecls();
7168   void ActOnFinishCXXNonNestedClass();
7169 
7170   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7171   unsigned ActOnReenterTemplateScope(Decl *Template,
7172                                      llvm::function_ref<Scope *()> EnterScope);
7173   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7174   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7175   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7176   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7177   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7178   void ActOnFinishDelayedMemberInitializers(Decl *Record);
7179   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7180                                 CachedTokens &Toks);
7181   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7182   bool IsInsideALocalClassWithinATemplateFunction();
7183 
7184   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7185                                      Expr *AssertExpr,
7186                                      Expr *AssertMessageExpr,
7187                                      SourceLocation RParenLoc);
7188   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7189                                      Expr *AssertExpr,
7190                                      StringLiteral *AssertMessageExpr,
7191                                      SourceLocation RParenLoc,
7192                                      bool Failed);
7193 
7194   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7195                                   SourceLocation FriendLoc,
7196                                   TypeSourceInfo *TSInfo);
7197   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7198                             MultiTemplateParamsArg TemplateParams);
7199   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7200                                      MultiTemplateParamsArg TemplateParams);
7201 
7202   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7203                                       StorageClass& SC);
7204   void CheckConstructor(CXXConstructorDecl *Constructor);
7205   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7206                                      StorageClass& SC);
7207   bool CheckDestructor(CXXDestructorDecl *Destructor);
7208   void CheckConversionDeclarator(Declarator &D, QualType &R,
7209                                  StorageClass& SC);
7210   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7211   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7212                                      StorageClass &SC);
7213   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7214 
7215   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7216 
7217   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7218                                              CXXSpecialMember CSM);
7219   void CheckDelayedMemberExceptionSpecs();
7220 
7221   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7222                                           DefaultedComparisonKind DCK);
7223   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7224                                          FunctionDecl *Spaceship);
7225   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7226                                  DefaultedComparisonKind DCK);
7227 
7228   //===--------------------------------------------------------------------===//
7229   // C++ Derived Classes
7230   //
7231 
7232   /// ActOnBaseSpecifier - Parsed a base specifier
7233   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7234                                        SourceRange SpecifierRange,
7235                                        bool Virtual, AccessSpecifier Access,
7236                                        TypeSourceInfo *TInfo,
7237                                        SourceLocation EllipsisLoc);
7238 
7239   BaseResult ActOnBaseSpecifier(Decl *classdecl,
7240                                 SourceRange SpecifierRange,
7241                                 ParsedAttributes &Attrs,
7242                                 bool Virtual, AccessSpecifier Access,
7243                                 ParsedType basetype,
7244                                 SourceLocation BaseLoc,
7245                                 SourceLocation EllipsisLoc);
7246 
7247   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7248                             MutableArrayRef<CXXBaseSpecifier *> Bases);
7249   void ActOnBaseSpecifiers(Decl *ClassDecl,
7250                            MutableArrayRef<CXXBaseSpecifier *> Bases);
7251 
7252   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7253   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7254                      CXXBasePaths &Paths);
7255 
7256   // FIXME: I don't like this name.
7257   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7258 
7259   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7260                                     SourceLocation Loc, SourceRange Range,
7261                                     CXXCastPath *BasePath = nullptr,
7262                                     bool IgnoreAccess = false);
7263   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7264                                     unsigned InaccessibleBaseID,
7265                                     unsigned AmbiguousBaseConvID,
7266                                     SourceLocation Loc, SourceRange Range,
7267                                     DeclarationName Name,
7268                                     CXXCastPath *BasePath,
7269                                     bool IgnoreAccess = false);
7270 
7271   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7272 
7273   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7274                                          const CXXMethodDecl *Old);
7275 
7276   /// CheckOverridingFunctionReturnType - Checks whether the return types are
7277   /// covariant, according to C++ [class.virtual]p5.
7278   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7279                                          const CXXMethodDecl *Old);
7280 
7281   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7282   /// spec is a subset of base spec.
7283   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7284                                             const CXXMethodDecl *Old);
7285 
7286   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7287 
7288   /// CheckOverrideControl - Check C++11 override control semantics.
7289   void CheckOverrideControl(NamedDecl *D);
7290 
7291   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7292   /// not used in the declaration of an overriding method.
7293   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7294 
7295   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7296   /// overrides a virtual member function marked 'final', according to
7297   /// C++11 [class.virtual]p4.
7298   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7299                                               const CXXMethodDecl *Old);
7300 
7301 
7302   //===--------------------------------------------------------------------===//
7303   // C++ Access Control
7304   //
7305 
7306   enum AccessResult {
7307     AR_accessible,
7308     AR_inaccessible,
7309     AR_dependent,
7310     AR_delayed
7311   };
7312 
7313   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7314                                 NamedDecl *PrevMemberDecl,
7315                                 AccessSpecifier LexicalAS);
7316 
7317   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7318                                            DeclAccessPair FoundDecl);
7319   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7320                                            DeclAccessPair FoundDecl);
7321   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7322                                      SourceRange PlacementRange,
7323                                      CXXRecordDecl *NamingClass,
7324                                      DeclAccessPair FoundDecl,
7325                                      bool Diagnose = true);
7326   AccessResult CheckConstructorAccess(SourceLocation Loc,
7327                                       CXXConstructorDecl *D,
7328                                       DeclAccessPair FoundDecl,
7329                                       const InitializedEntity &Entity,
7330                                       bool IsCopyBindingRefToTemp = false);
7331   AccessResult CheckConstructorAccess(SourceLocation Loc,
7332                                       CXXConstructorDecl *D,
7333                                       DeclAccessPair FoundDecl,
7334                                       const InitializedEntity &Entity,
7335                                       const PartialDiagnostic &PDiag);
7336   AccessResult CheckDestructorAccess(SourceLocation Loc,
7337                                      CXXDestructorDecl *Dtor,
7338                                      const PartialDiagnostic &PDiag,
7339                                      QualType objectType = QualType());
7340   AccessResult CheckFriendAccess(NamedDecl *D);
7341   AccessResult CheckMemberAccess(SourceLocation UseLoc,
7342                                  CXXRecordDecl *NamingClass,
7343                                  DeclAccessPair Found);
7344   AccessResult
7345   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7346                                      CXXRecordDecl *DecomposedClass,
7347                                      DeclAccessPair Field);
7348   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7349                                          Expr *ObjectExpr,
7350                                          Expr *ArgExpr,
7351                                          DeclAccessPair FoundDecl);
7352   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7353                                           DeclAccessPair FoundDecl);
7354   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7355                                     QualType Base, QualType Derived,
7356                                     const CXXBasePath &Path,
7357                                     unsigned DiagID,
7358                                     bool ForceCheck = false,
7359                                     bool ForceUnprivileged = false);
7360   void CheckLookupAccess(const LookupResult &R);
7361   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7362                           QualType BaseType);
7363   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7364                                      DeclAccessPair Found, QualType ObjectType,
7365                                      SourceLocation Loc,
7366                                      const PartialDiagnostic &Diag);
isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)7367   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7368                                      DeclAccessPair Found,
7369                                      QualType ObjectType) {
7370     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7371                                          SourceLocation(), PDiag());
7372   }
7373 
7374   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7375                          const MultiLevelTemplateArgumentList &TemplateArgs);
7376   void PerformDependentDiagnostics(const DeclContext *Pattern,
7377                         const MultiLevelTemplateArgumentList &TemplateArgs);
7378 
7379   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7380 
7381   /// When true, access checking violations are treated as SFINAE
7382   /// failures rather than hard errors.
7383   bool AccessCheckingSFINAE;
7384 
7385   enum AbstractDiagSelID {
7386     AbstractNone = -1,
7387     AbstractReturnType,
7388     AbstractParamType,
7389     AbstractVariableType,
7390     AbstractFieldType,
7391     AbstractIvarType,
7392     AbstractSynthesizedIvarType,
7393     AbstractArrayType
7394   };
7395 
7396   bool isAbstractType(SourceLocation Loc, QualType T);
7397   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7398                               TypeDiagnoser &Diagnoser);
7399   template <typename... Ts>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)7400   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7401                               const Ts &...Args) {
7402     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7403     return RequireNonAbstractType(Loc, T, Diagnoser);
7404   }
7405 
7406   void DiagnoseAbstractType(const CXXRecordDecl *RD);
7407 
7408   //===--------------------------------------------------------------------===//
7409   // C++ Overloaded Operators [C++ 13.5]
7410   //
7411 
7412   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7413 
7414   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7415 
7416   //===--------------------------------------------------------------------===//
7417   // C++ Templates [C++ 14]
7418   //
7419   void FilterAcceptableTemplateNames(LookupResult &R,
7420                                      bool AllowFunctionTemplates = true,
7421                                      bool AllowDependent = true);
7422   bool hasAnyAcceptableTemplateNames(LookupResult &R,
7423                                      bool AllowFunctionTemplates = true,
7424                                      bool AllowDependent = true,
7425                                      bool AllowNonTemplateFunctions = false);
7426   /// Try to interpret the lookup result D as a template-name.
7427   ///
7428   /// \param D A declaration found by name lookup.
7429   /// \param AllowFunctionTemplates Whether function templates should be
7430   ///        considered valid results.
7431   /// \param AllowDependent Whether unresolved using declarations (that might
7432   ///        name templates) should be considered valid results.
7433   static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7434                                           bool AllowFunctionTemplates = true,
7435                                           bool AllowDependent = true);
7436 
7437   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7438   /// Whether and why a template name is required in this lookup.
7439   class RequiredTemplateKind {
7440   public:
7441     /// Template name is required if TemplateKWLoc is valid.
7442     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
TemplateKW(TemplateKWLoc)7443         : TemplateKW(TemplateKWLoc) {}
7444     /// Template name is unconditionally required.
RequiredTemplateKind(TemplateNameIsRequiredTag)7445     RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {}
7446 
getTemplateKeywordLoc()7447     SourceLocation getTemplateKeywordLoc() const {
7448       return TemplateKW.getValueOr(SourceLocation());
7449     }
hasTemplateKeyword()7450     bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
isRequired()7451     bool isRequired() const { return TemplateKW != SourceLocation(); }
7452     explicit operator bool() const { return isRequired(); }
7453 
7454   private:
7455     llvm::Optional<SourceLocation> TemplateKW;
7456   };
7457 
7458   enum class AssumedTemplateKind {
7459     /// This is not assumed to be a template name.
7460     None,
7461     /// This is assumed to be a template name because lookup found nothing.
7462     FoundNothing,
7463     /// This is assumed to be a template name because lookup found one or more
7464     /// functions (but no function templates).
7465     FoundFunctions,
7466   };
7467   bool LookupTemplateName(
7468       LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7469       bool EnteringContext, bool &MemberOfUnknownSpecialization,
7470       RequiredTemplateKind RequiredTemplate = SourceLocation(),
7471       AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7472 
7473   TemplateNameKind isTemplateName(Scope *S,
7474                                   CXXScopeSpec &SS,
7475                                   bool hasTemplateKeyword,
7476                                   const UnqualifiedId &Name,
7477                                   ParsedType ObjectType,
7478                                   bool EnteringContext,
7479                                   TemplateTy &Template,
7480                                   bool &MemberOfUnknownSpecialization,
7481                                   bool Disambiguation = false);
7482 
7483   /// Try to resolve an undeclared template name as a type template.
7484   ///
7485   /// Sets II to the identifier corresponding to the template name, and updates
7486   /// Name to a corresponding (typo-corrected) type template name and TNK to
7487   /// the corresponding kind, if possible.
7488   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7489                                        TemplateNameKind &TNK,
7490                                        SourceLocation NameLoc,
7491                                        IdentifierInfo *&II);
7492 
7493   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7494                                         SourceLocation NameLoc,
7495                                         bool Diagnose = true);
7496 
7497   /// Determine whether a particular identifier might be the name in a C++1z
7498   /// deduction-guide declaration.
7499   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7500                             SourceLocation NameLoc,
7501                             ParsedTemplateTy *Template = nullptr);
7502 
7503   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7504                                    SourceLocation IILoc,
7505                                    Scope *S,
7506                                    const CXXScopeSpec *SS,
7507                                    TemplateTy &SuggestedTemplate,
7508                                    TemplateNameKind &SuggestedKind);
7509 
7510   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7511                                       NamedDecl *Instantiation,
7512                                       bool InstantiatedFromMember,
7513                                       const NamedDecl *Pattern,
7514                                       const NamedDecl *PatternDef,
7515                                       TemplateSpecializationKind TSK,
7516                                       bool Complain = true);
7517 
7518   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7519   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7520 
7521   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7522                                 SourceLocation EllipsisLoc,
7523                                 SourceLocation KeyLoc,
7524                                 IdentifierInfo *ParamName,
7525                                 SourceLocation ParamNameLoc,
7526                                 unsigned Depth, unsigned Position,
7527                                 SourceLocation EqualLoc,
7528                                 ParsedType DefaultArg, bool HasTypeConstraint);
7529 
7530   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7531                            TemplateIdAnnotation *TypeConstraint,
7532                            TemplateTypeParmDecl *ConstrainedParameter,
7533                            SourceLocation EllipsisLoc);
7534   bool BuildTypeConstraint(const CXXScopeSpec &SS,
7535                            TemplateIdAnnotation *TypeConstraint,
7536                            TemplateTypeParmDecl *ConstrainedParameter,
7537                            SourceLocation EllipsisLoc,
7538                            bool AllowUnexpandedPack);
7539 
7540   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7541                             DeclarationNameInfo NameInfo,
7542                             ConceptDecl *NamedConcept,
7543                             const TemplateArgumentListInfo *TemplateArgs,
7544                             TemplateTypeParmDecl *ConstrainedParameter,
7545                             SourceLocation EllipsisLoc);
7546 
7547   bool AttachTypeConstraint(AutoTypeLoc TL,
7548                             NonTypeTemplateParmDecl *ConstrainedParameter,
7549                             SourceLocation EllipsisLoc);
7550 
7551   bool RequireStructuralType(QualType T, SourceLocation Loc);
7552 
7553   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7554                                              SourceLocation Loc);
7555   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7556 
7557   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7558                                       unsigned Depth,
7559                                       unsigned Position,
7560                                       SourceLocation EqualLoc,
7561                                       Expr *DefaultArg);
7562   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7563                                        SourceLocation TmpLoc,
7564                                        TemplateParameterList *Params,
7565                                        SourceLocation EllipsisLoc,
7566                                        IdentifierInfo *ParamName,
7567                                        SourceLocation ParamNameLoc,
7568                                        unsigned Depth,
7569                                        unsigned Position,
7570                                        SourceLocation EqualLoc,
7571                                        ParsedTemplateArgument DefaultArg);
7572 
7573   TemplateParameterList *
7574   ActOnTemplateParameterList(unsigned Depth,
7575                              SourceLocation ExportLoc,
7576                              SourceLocation TemplateLoc,
7577                              SourceLocation LAngleLoc,
7578                              ArrayRef<NamedDecl *> Params,
7579                              SourceLocation RAngleLoc,
7580                              Expr *RequiresClause);
7581 
7582   /// The context in which we are checking a template parameter list.
7583   enum TemplateParamListContext {
7584     TPC_ClassTemplate,
7585     TPC_VarTemplate,
7586     TPC_FunctionTemplate,
7587     TPC_ClassTemplateMember,
7588     TPC_FriendClassTemplate,
7589     TPC_FriendFunctionTemplate,
7590     TPC_FriendFunctionTemplateDefinition,
7591     TPC_TypeAliasTemplate
7592   };
7593 
7594   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7595                                   TemplateParameterList *OldParams,
7596                                   TemplateParamListContext TPC,
7597                                   SkipBodyInfo *SkipBody = nullptr);
7598   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7599       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7600       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7601       ArrayRef<TemplateParameterList *> ParamLists,
7602       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7603       bool SuppressDiagnostic = false);
7604 
7605   DeclResult CheckClassTemplate(
7606       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7607       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7608       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7609       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7610       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7611       TemplateParameterList **OuterTemplateParamLists,
7612       SkipBodyInfo *SkipBody = nullptr);
7613 
7614   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7615                                                     QualType NTTPType,
7616                                                     SourceLocation Loc);
7617 
7618   /// Get a template argument mapping the given template parameter to itself,
7619   /// e.g. for X in \c template<int X>, this would return an expression template
7620   /// argument referencing X.
7621   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7622                                                      SourceLocation Location);
7623 
7624   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7625                                   TemplateArgumentListInfo &Out);
7626 
7627   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7628 
7629   void NoteAllFoundTemplates(TemplateName Name);
7630 
7631   QualType CheckTemplateIdType(TemplateName Template,
7632                                SourceLocation TemplateLoc,
7633                               TemplateArgumentListInfo &TemplateArgs);
7634 
7635   TypeResult
7636   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7637                       TemplateTy Template, IdentifierInfo *TemplateII,
7638                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7639                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7640                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7641 
7642   /// Parsed an elaborated-type-specifier that refers to a template-id,
7643   /// such as \c class T::template apply<U>.
7644   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7645                                     TypeSpecifierType TagSpec,
7646                                     SourceLocation TagLoc,
7647                                     CXXScopeSpec &SS,
7648                                     SourceLocation TemplateKWLoc,
7649                                     TemplateTy TemplateD,
7650                                     SourceLocation TemplateLoc,
7651                                     SourceLocation LAngleLoc,
7652                                     ASTTemplateArgsPtr TemplateArgsIn,
7653                                     SourceLocation RAngleLoc);
7654 
7655   DeclResult ActOnVarTemplateSpecialization(
7656       Scope *S, Declarator &D, TypeSourceInfo *DI,
7657       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7658       StorageClass SC, bool IsPartialSpecialization);
7659 
7660   /// Get the specialization of the given variable template corresponding to
7661   /// the specified argument list, or a null-but-valid result if the arguments
7662   /// are dependent.
7663   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7664                                 SourceLocation TemplateLoc,
7665                                 SourceLocation TemplateNameLoc,
7666                                 const TemplateArgumentListInfo &TemplateArgs);
7667 
7668   /// Form a reference to the specialization of the given variable template
7669   /// corresponding to the specified argument list, or a null-but-valid result
7670   /// if the arguments are dependent.
7671   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7672                                 const DeclarationNameInfo &NameInfo,
7673                                 VarTemplateDecl *Template,
7674                                 SourceLocation TemplateLoc,
7675                                 const TemplateArgumentListInfo *TemplateArgs);
7676 
7677   ExprResult
7678   CheckConceptTemplateId(const CXXScopeSpec &SS,
7679                          SourceLocation TemplateKWLoc,
7680                          const DeclarationNameInfo &ConceptNameInfo,
7681                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7682                          const TemplateArgumentListInfo *TemplateArgs);
7683 
7684   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7685 
7686   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7687                                  SourceLocation TemplateKWLoc,
7688                                  LookupResult &R,
7689                                  bool RequiresADL,
7690                                const TemplateArgumentListInfo *TemplateArgs);
7691 
7692   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7693                                           SourceLocation TemplateKWLoc,
7694                                const DeclarationNameInfo &NameInfo,
7695                                const TemplateArgumentListInfo *TemplateArgs);
7696 
7697   TemplateNameKind ActOnTemplateName(
7698       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7699       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7700       TemplateTy &Template, bool AllowInjectedClassName = false);
7701 
7702   DeclResult ActOnClassTemplateSpecialization(
7703       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7704       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7705       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7706       MultiTemplateParamsArg TemplateParameterLists,
7707       SkipBodyInfo *SkipBody = nullptr);
7708 
7709   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7710                                               TemplateDecl *PrimaryTemplate,
7711                                               unsigned NumExplicitArgs,
7712                                               ArrayRef<TemplateArgument> Args);
7713   void CheckTemplatePartialSpecialization(
7714       ClassTemplatePartialSpecializationDecl *Partial);
7715   void CheckTemplatePartialSpecialization(
7716       VarTemplatePartialSpecializationDecl *Partial);
7717 
7718   Decl *ActOnTemplateDeclarator(Scope *S,
7719                                 MultiTemplateParamsArg TemplateParameterLists,
7720                                 Declarator &D);
7721 
7722   bool
7723   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7724                                          TemplateSpecializationKind NewTSK,
7725                                          NamedDecl *PrevDecl,
7726                                          TemplateSpecializationKind PrevTSK,
7727                                          SourceLocation PrevPtOfInstantiation,
7728                                          bool &SuppressNew);
7729 
7730   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7731                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
7732                                                     LookupResult &Previous);
7733 
7734   bool CheckFunctionTemplateSpecialization(
7735       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7736       LookupResult &Previous, bool QualifiedFriend = false);
7737   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7738   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7739 
7740   DeclResult ActOnExplicitInstantiation(
7741       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7742       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7743       TemplateTy Template, SourceLocation TemplateNameLoc,
7744       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7745       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7746 
7747   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7748                                         SourceLocation TemplateLoc,
7749                                         unsigned TagSpec, SourceLocation KWLoc,
7750                                         CXXScopeSpec &SS, IdentifierInfo *Name,
7751                                         SourceLocation NameLoc,
7752                                         const ParsedAttributesView &Attr);
7753 
7754   DeclResult ActOnExplicitInstantiation(Scope *S,
7755                                         SourceLocation ExternLoc,
7756                                         SourceLocation TemplateLoc,
7757                                         Declarator &D);
7758 
7759   TemplateArgumentLoc
7760   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7761                                           SourceLocation TemplateLoc,
7762                                           SourceLocation RAngleLoc,
7763                                           Decl *Param,
7764                                           SmallVectorImpl<TemplateArgument>
7765                                             &Converted,
7766                                           bool &HasDefaultArg);
7767 
7768   /// Specifies the context in which a particular template
7769   /// argument is being checked.
7770   enum CheckTemplateArgumentKind {
7771     /// The template argument was specified in the code or was
7772     /// instantiated with some deduced template arguments.
7773     CTAK_Specified,
7774 
7775     /// The template argument was deduced via template argument
7776     /// deduction.
7777     CTAK_Deduced,
7778 
7779     /// The template argument was deduced from an array bound
7780     /// via template argument deduction.
7781     CTAK_DeducedFromArrayBound
7782   };
7783 
7784   bool CheckTemplateArgument(NamedDecl *Param,
7785                              TemplateArgumentLoc &Arg,
7786                              NamedDecl *Template,
7787                              SourceLocation TemplateLoc,
7788                              SourceLocation RAngleLoc,
7789                              unsigned ArgumentPackIndex,
7790                            SmallVectorImpl<TemplateArgument> &Converted,
7791                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
7792 
7793   /// Check that the given template arguments can be be provided to
7794   /// the given template, converting the arguments along the way.
7795   ///
7796   /// \param Template The template to which the template arguments are being
7797   /// provided.
7798   ///
7799   /// \param TemplateLoc The location of the template name in the source.
7800   ///
7801   /// \param TemplateArgs The list of template arguments. If the template is
7802   /// a template template parameter, this function may extend the set of
7803   /// template arguments to also include substituted, defaulted template
7804   /// arguments.
7805   ///
7806   /// \param PartialTemplateArgs True if the list of template arguments is
7807   /// intentionally partial, e.g., because we're checking just the initial
7808   /// set of template arguments.
7809   ///
7810   /// \param Converted Will receive the converted, canonicalized template
7811   /// arguments.
7812   ///
7813   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7814   /// contain the converted forms of the template arguments as written.
7815   /// Otherwise, \p TemplateArgs will not be modified.
7816   ///
7817   /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7818   /// receive true if the cause for the error is the associated constraints of
7819   /// the template not being satisfied by the template arguments.
7820   ///
7821   /// \returns true if an error occurred, false otherwise.
7822   bool CheckTemplateArgumentList(TemplateDecl *Template,
7823                                  SourceLocation TemplateLoc,
7824                                  TemplateArgumentListInfo &TemplateArgs,
7825                                  bool PartialTemplateArgs,
7826                                  SmallVectorImpl<TemplateArgument> &Converted,
7827                                  bool UpdateArgsWithConversions = true,
7828                                  bool *ConstraintsNotSatisfied = nullptr);
7829 
7830   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7831                                  TemplateArgumentLoc &Arg,
7832                            SmallVectorImpl<TemplateArgument> &Converted);
7833 
7834   bool CheckTemplateArgument(TypeSourceInfo *Arg);
7835   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7836                                    QualType InstantiatedParamType, Expr *Arg,
7837                                    TemplateArgument &Converted,
7838                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
7839   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7840                                      TemplateParameterList *Params,
7841                                      TemplateArgumentLoc &Arg);
7842 
7843   ExprResult
7844   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7845                                           QualType ParamType,
7846                                           SourceLocation Loc);
7847   ExprResult
7848   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7849                                               SourceLocation Loc);
7850 
7851   /// Enumeration describing how template parameter lists are compared
7852   /// for equality.
7853   enum TemplateParameterListEqualKind {
7854     /// We are matching the template parameter lists of two templates
7855     /// that might be redeclarations.
7856     ///
7857     /// \code
7858     /// template<typename T> struct X;
7859     /// template<typename T> struct X;
7860     /// \endcode
7861     TPL_TemplateMatch,
7862 
7863     /// We are matching the template parameter lists of two template
7864     /// template parameters as part of matching the template parameter lists
7865     /// of two templates that might be redeclarations.
7866     ///
7867     /// \code
7868     /// template<template<int I> class TT> struct X;
7869     /// template<template<int Value> class Other> struct X;
7870     /// \endcode
7871     TPL_TemplateTemplateParmMatch,
7872 
7873     /// We are matching the template parameter lists of a template
7874     /// template argument against the template parameter lists of a template
7875     /// template parameter.
7876     ///
7877     /// \code
7878     /// template<template<int Value> class Metafun> struct X;
7879     /// template<int Value> struct integer_c;
7880     /// X<integer_c> xic;
7881     /// \endcode
7882     TPL_TemplateTemplateArgumentMatch
7883   };
7884 
7885   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7886                                       TemplateParameterList *Old,
7887                                       bool Complain,
7888                                       TemplateParameterListEqualKind Kind,
7889                                       SourceLocation TemplateArgLoc
7890                                         = SourceLocation());
7891 
7892   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7893 
7894   /// Called when the parser has parsed a C++ typename
7895   /// specifier, e.g., "typename T::type".
7896   ///
7897   /// \param S The scope in which this typename type occurs.
7898   /// \param TypenameLoc the location of the 'typename' keyword
7899   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7900   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7901   /// \param IdLoc the location of the identifier.
7902   TypeResult
7903   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7904                     const CXXScopeSpec &SS, const IdentifierInfo &II,
7905                     SourceLocation IdLoc);
7906 
7907   /// Called when the parser has parsed a C++ typename
7908   /// specifier that ends in a template-id, e.g.,
7909   /// "typename MetaFun::template apply<T1, T2>".
7910   ///
7911   /// \param S The scope in which this typename type occurs.
7912   /// \param TypenameLoc the location of the 'typename' keyword
7913   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7914   /// \param TemplateLoc the location of the 'template' keyword, if any.
7915   /// \param TemplateName The template name.
7916   /// \param TemplateII The identifier used to name the template.
7917   /// \param TemplateIILoc The location of the template name.
7918   /// \param LAngleLoc The location of the opening angle bracket  ('<').
7919   /// \param TemplateArgs The template arguments.
7920   /// \param RAngleLoc The location of the closing angle bracket  ('>').
7921   TypeResult
7922   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7923                     const CXXScopeSpec &SS,
7924                     SourceLocation TemplateLoc,
7925                     TemplateTy TemplateName,
7926                     IdentifierInfo *TemplateII,
7927                     SourceLocation TemplateIILoc,
7928                     SourceLocation LAngleLoc,
7929                     ASTTemplateArgsPtr TemplateArgs,
7930                     SourceLocation RAngleLoc);
7931 
7932   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7933                              SourceLocation KeywordLoc,
7934                              NestedNameSpecifierLoc QualifierLoc,
7935                              const IdentifierInfo &II,
7936                              SourceLocation IILoc,
7937                              TypeSourceInfo **TSI,
7938                              bool DeducedTSTContext);
7939 
7940   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7941                              SourceLocation KeywordLoc,
7942                              NestedNameSpecifierLoc QualifierLoc,
7943                              const IdentifierInfo &II,
7944                              SourceLocation IILoc,
7945                              bool DeducedTSTContext = true);
7946 
7947 
7948   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7949                                                     SourceLocation Loc,
7950                                                     DeclarationName Name);
7951   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7952 
7953   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7954   bool RebuildTemplateParamsInCurrentInstantiation(
7955                                                 TemplateParameterList *Params);
7956 
7957   std::string
7958   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7959                                   const TemplateArgumentList &Args);
7960 
7961   std::string
7962   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7963                                   const TemplateArgument *Args,
7964                                   unsigned NumArgs);
7965 
7966   //===--------------------------------------------------------------------===//
7967   // C++ Concepts
7968   //===--------------------------------------------------------------------===//
7969   Decl *ActOnConceptDefinition(
7970       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7971       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7972 
7973   RequiresExprBodyDecl *
7974   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
7975                          ArrayRef<ParmVarDecl *> LocalParameters,
7976                          Scope *BodyScope);
7977   void ActOnFinishRequiresExpr();
7978   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
7979   concepts::Requirement *ActOnTypeRequirement(
7980       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7981       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
7982   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
7983                                                   SourceLocation NoexceptLoc);
7984   concepts::Requirement *
7985   ActOnCompoundRequirement(
7986       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7987       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
7988   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
7989   concepts::ExprRequirement *
7990   BuildExprRequirement(
7991       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
7992       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7993   concepts::ExprRequirement *
7994   BuildExprRequirement(
7995       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
7996       bool IsSatisfied, SourceLocation NoexceptLoc,
7997       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7998   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
7999   concepts::TypeRequirement *
8000   BuildTypeRequirement(
8001       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8002   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8003   concepts::NestedRequirement *
8004   BuildNestedRequirement(
8005       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8006   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8007                                RequiresExprBodyDecl *Body,
8008                                ArrayRef<ParmVarDecl *> LocalParameters,
8009                                ArrayRef<concepts::Requirement *> Requirements,
8010                                SourceLocation ClosingBraceLoc);
8011 
8012   //===--------------------------------------------------------------------===//
8013   // C++ Variadic Templates (C++0x [temp.variadic])
8014   //===--------------------------------------------------------------------===//
8015 
8016   /// Determine whether an unexpanded parameter pack might be permitted in this
8017   /// location. Useful for error recovery.
8018   bool isUnexpandedParameterPackPermitted();
8019 
8020   /// The context in which an unexpanded parameter pack is
8021   /// being diagnosed.
8022   ///
8023   /// Note that the values of this enumeration line up with the first
8024   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8025   enum UnexpandedParameterPackContext {
8026     /// An arbitrary expression.
8027     UPPC_Expression = 0,
8028 
8029     /// The base type of a class type.
8030     UPPC_BaseType,
8031 
8032     /// The type of an arbitrary declaration.
8033     UPPC_DeclarationType,
8034 
8035     /// The type of a data member.
8036     UPPC_DataMemberType,
8037 
8038     /// The size of a bit-field.
8039     UPPC_BitFieldWidth,
8040 
8041     /// The expression in a static assertion.
8042     UPPC_StaticAssertExpression,
8043 
8044     /// The fixed underlying type of an enumeration.
8045     UPPC_FixedUnderlyingType,
8046 
8047     /// The enumerator value.
8048     UPPC_EnumeratorValue,
8049 
8050     /// A using declaration.
8051     UPPC_UsingDeclaration,
8052 
8053     /// A friend declaration.
8054     UPPC_FriendDeclaration,
8055 
8056     /// A declaration qualifier.
8057     UPPC_DeclarationQualifier,
8058 
8059     /// An initializer.
8060     UPPC_Initializer,
8061 
8062     /// A default argument.
8063     UPPC_DefaultArgument,
8064 
8065     /// The type of a non-type template parameter.
8066     UPPC_NonTypeTemplateParameterType,
8067 
8068     /// The type of an exception.
8069     UPPC_ExceptionType,
8070 
8071     /// Partial specialization.
8072     UPPC_PartialSpecialization,
8073 
8074     /// Microsoft __if_exists.
8075     UPPC_IfExists,
8076 
8077     /// Microsoft __if_not_exists.
8078     UPPC_IfNotExists,
8079 
8080     /// Lambda expression.
8081     UPPC_Lambda,
8082 
8083     /// Block expression.
8084     UPPC_Block,
8085 
8086     /// A type constraint.
8087     UPPC_TypeConstraint,
8088 
8089     // A requirement in a requires-expression.
8090     UPPC_Requirement,
8091 
8092     // A requires-clause.
8093     UPPC_RequiresClause,
8094   };
8095 
8096   /// Diagnose unexpanded parameter packs.
8097   ///
8098   /// \param Loc The location at which we should emit the diagnostic.
8099   ///
8100   /// \param UPPC The context in which we are diagnosing unexpanded
8101   /// parameter packs.
8102   ///
8103   /// \param Unexpanded the set of unexpanded parameter packs.
8104   ///
8105   /// \returns true if an error occurred, false otherwise.
8106   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8107                                         UnexpandedParameterPackContext UPPC,
8108                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
8109 
8110   /// If the given type contains an unexpanded parameter pack,
8111   /// diagnose the error.
8112   ///
8113   /// \param Loc The source location where a diagnostc should be emitted.
8114   ///
8115   /// \param T The type that is being checked for unexpanded parameter
8116   /// packs.
8117   ///
8118   /// \returns true if an error occurred, false otherwise.
8119   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8120                                        UnexpandedParameterPackContext UPPC);
8121 
8122   /// If the given expression contains an unexpanded parameter
8123   /// pack, diagnose the error.
8124   ///
8125   /// \param E The expression that is being checked for unexpanded
8126   /// parameter packs.
8127   ///
8128   /// \returns true if an error occurred, false otherwise.
8129   bool DiagnoseUnexpandedParameterPack(Expr *E,
8130                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
8131 
8132   /// If the given requirees-expression contains an unexpanded reference to one
8133   /// of its own parameter packs, diagnose the error.
8134   ///
8135   /// \param RE The requiress-expression that is being checked for unexpanded
8136   /// parameter packs.
8137   ///
8138   /// \returns true if an error occurred, false otherwise.
8139   bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8140 
8141   /// If the given nested-name-specifier contains an unexpanded
8142   /// parameter pack, diagnose the error.
8143   ///
8144   /// \param SS The nested-name-specifier that is being checked for
8145   /// unexpanded parameter packs.
8146   ///
8147   /// \returns true if an error occurred, false otherwise.
8148   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8149                                        UnexpandedParameterPackContext UPPC);
8150 
8151   /// If the given name contains an unexpanded parameter pack,
8152   /// diagnose the error.
8153   ///
8154   /// \param NameInfo The name (with source location information) that
8155   /// is being checked for unexpanded parameter packs.
8156   ///
8157   /// \returns true if an error occurred, false otherwise.
8158   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8159                                        UnexpandedParameterPackContext UPPC);
8160 
8161   /// If the given template name contains an unexpanded parameter pack,
8162   /// diagnose the error.
8163   ///
8164   /// \param Loc The location of the template name.
8165   ///
8166   /// \param Template The template name that is being checked for unexpanded
8167   /// parameter packs.
8168   ///
8169   /// \returns true if an error occurred, false otherwise.
8170   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8171                                        TemplateName Template,
8172                                        UnexpandedParameterPackContext UPPC);
8173 
8174   /// If the given template argument contains an unexpanded parameter
8175   /// pack, diagnose the error.
8176   ///
8177   /// \param Arg The template argument that is being checked for unexpanded
8178   /// parameter packs.
8179   ///
8180   /// \returns true if an error occurred, false otherwise.
8181   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8182                                        UnexpandedParameterPackContext UPPC);
8183 
8184   /// Collect the set of unexpanded parameter packs within the given
8185   /// template argument.
8186   ///
8187   /// \param Arg The template argument that will be traversed to find
8188   /// unexpanded parameter packs.
8189   void collectUnexpandedParameterPacks(TemplateArgument Arg,
8190                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8191 
8192   /// Collect the set of unexpanded parameter packs within the given
8193   /// template argument.
8194   ///
8195   /// \param Arg The template argument that will be traversed to find
8196   /// unexpanded parameter packs.
8197   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8198                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8199 
8200   /// Collect the set of unexpanded parameter packs within the given
8201   /// type.
8202   ///
8203   /// \param T The type that will be traversed to find
8204   /// unexpanded parameter packs.
8205   void collectUnexpandedParameterPacks(QualType T,
8206                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8207 
8208   /// Collect the set of unexpanded parameter packs within the given
8209   /// type.
8210   ///
8211   /// \param TL The type that will be traversed to find
8212   /// unexpanded parameter packs.
8213   void collectUnexpandedParameterPacks(TypeLoc TL,
8214                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8215 
8216   /// Collect the set of unexpanded parameter packs within the given
8217   /// nested-name-specifier.
8218   ///
8219   /// \param NNS The nested-name-specifier that will be traversed to find
8220   /// unexpanded parameter packs.
8221   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8222                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8223 
8224   /// Collect the set of unexpanded parameter packs within the given
8225   /// name.
8226   ///
8227   /// \param NameInfo The name that will be traversed to find
8228   /// unexpanded parameter packs.
8229   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8230                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8231 
8232   /// Invoked when parsing a template argument followed by an
8233   /// ellipsis, which creates a pack expansion.
8234   ///
8235   /// \param Arg The template argument preceding the ellipsis, which
8236   /// may already be invalid.
8237   ///
8238   /// \param EllipsisLoc The location of the ellipsis.
8239   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8240                                             SourceLocation EllipsisLoc);
8241 
8242   /// Invoked when parsing a type followed by an ellipsis, which
8243   /// creates a pack expansion.
8244   ///
8245   /// \param Type The type preceding the ellipsis, which will become
8246   /// the pattern of the pack expansion.
8247   ///
8248   /// \param EllipsisLoc The location of the ellipsis.
8249   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8250 
8251   /// Construct a pack expansion type from the pattern of the pack
8252   /// expansion.
8253   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8254                                      SourceLocation EllipsisLoc,
8255                                      Optional<unsigned> NumExpansions);
8256 
8257   /// Construct a pack expansion type from the pattern of the pack
8258   /// expansion.
8259   QualType CheckPackExpansion(QualType Pattern,
8260                               SourceRange PatternRange,
8261                               SourceLocation EllipsisLoc,
8262                               Optional<unsigned> NumExpansions);
8263 
8264   /// Invoked when parsing an expression followed by an ellipsis, which
8265   /// creates a pack expansion.
8266   ///
8267   /// \param Pattern The expression preceding the ellipsis, which will become
8268   /// the pattern of the pack expansion.
8269   ///
8270   /// \param EllipsisLoc The location of the ellipsis.
8271   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8272 
8273   /// Invoked when parsing an expression followed by an ellipsis, which
8274   /// creates a pack expansion.
8275   ///
8276   /// \param Pattern The expression preceding the ellipsis, which will become
8277   /// the pattern of the pack expansion.
8278   ///
8279   /// \param EllipsisLoc The location of the ellipsis.
8280   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8281                                 Optional<unsigned> NumExpansions);
8282 
8283   /// Determine whether we could expand a pack expansion with the
8284   /// given set of parameter packs into separate arguments by repeatedly
8285   /// transforming the pattern.
8286   ///
8287   /// \param EllipsisLoc The location of the ellipsis that identifies the
8288   /// pack expansion.
8289   ///
8290   /// \param PatternRange The source range that covers the entire pattern of
8291   /// the pack expansion.
8292   ///
8293   /// \param Unexpanded The set of unexpanded parameter packs within the
8294   /// pattern.
8295   ///
8296   /// \param ShouldExpand Will be set to \c true if the transformer should
8297   /// expand the corresponding pack expansions into separate arguments. When
8298   /// set, \c NumExpansions must also be set.
8299   ///
8300   /// \param RetainExpansion Whether the caller should add an unexpanded
8301   /// pack expansion after all of the expanded arguments. This is used
8302   /// when extending explicitly-specified template argument packs per
8303   /// C++0x [temp.arg.explicit]p9.
8304   ///
8305   /// \param NumExpansions The number of separate arguments that will be in
8306   /// the expanded form of the corresponding pack expansion. This is both an
8307   /// input and an output parameter, which can be set by the caller if the
8308   /// number of expansions is known a priori (e.g., due to a prior substitution)
8309   /// and will be set by the callee when the number of expansions is known.
8310   /// The callee must set this value when \c ShouldExpand is \c true; it may
8311   /// set this value in other cases.
8312   ///
8313   /// \returns true if an error occurred (e.g., because the parameter packs
8314   /// are to be instantiated with arguments of different lengths), false
8315   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8316   /// must be set.
8317   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8318                                        SourceRange PatternRange,
8319                              ArrayRef<UnexpandedParameterPack> Unexpanded,
8320                              const MultiLevelTemplateArgumentList &TemplateArgs,
8321                                        bool &ShouldExpand,
8322                                        bool &RetainExpansion,
8323                                        Optional<unsigned> &NumExpansions);
8324 
8325   /// Determine the number of arguments in the given pack expansion
8326   /// type.
8327   ///
8328   /// This routine assumes that the number of arguments in the expansion is
8329   /// consistent across all of the unexpanded parameter packs in its pattern.
8330   ///
8331   /// Returns an empty Optional if the type can't be expanded.
8332   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8333       const MultiLevelTemplateArgumentList &TemplateArgs);
8334 
8335   /// Determine whether the given declarator contains any unexpanded
8336   /// parameter packs.
8337   ///
8338   /// This routine is used by the parser to disambiguate function declarators
8339   /// with an ellipsis prior to the ')', e.g.,
8340   ///
8341   /// \code
8342   ///   void f(T...);
8343   /// \endcode
8344   ///
8345   /// To determine whether we have an (unnamed) function parameter pack or
8346   /// a variadic function.
8347   ///
8348   /// \returns true if the declarator contains any unexpanded parameter packs,
8349   /// false otherwise.
8350   bool containsUnexpandedParameterPacks(Declarator &D);
8351 
8352   /// Returns the pattern of the pack expansion for a template argument.
8353   ///
8354   /// \param OrigLoc The template argument to expand.
8355   ///
8356   /// \param Ellipsis Will be set to the location of the ellipsis.
8357   ///
8358   /// \param NumExpansions Will be set to the number of expansions that will
8359   /// be generated from this pack expansion, if known a priori.
8360   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8361       TemplateArgumentLoc OrigLoc,
8362       SourceLocation &Ellipsis,
8363       Optional<unsigned> &NumExpansions) const;
8364 
8365   /// Given a template argument that contains an unexpanded parameter pack, but
8366   /// which has already been substituted, attempt to determine the number of
8367   /// elements that will be produced once this argument is fully-expanded.
8368   ///
8369   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8370   /// avoid actually expanding the pack where possible.
8371   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8372 
8373   //===--------------------------------------------------------------------===//
8374   // C++ Template Argument Deduction (C++ [temp.deduct])
8375   //===--------------------------------------------------------------------===//
8376 
8377   /// Adjust the type \p ArgFunctionType to match the calling convention,
8378   /// noreturn, and optionally the exception specification of \p FunctionType.
8379   /// Deduction often wants to ignore these properties when matching function
8380   /// types.
8381   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8382                                bool AdjustExceptionSpec = false);
8383 
8384   /// Describes the result of template argument deduction.
8385   ///
8386   /// The TemplateDeductionResult enumeration describes the result of
8387   /// template argument deduction, as returned from
8388   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8389   /// structure provides additional information about the results of
8390   /// template argument deduction, e.g., the deduced template argument
8391   /// list (if successful) or the specific template parameters or
8392   /// deduced arguments that were involved in the failure.
8393   enum TemplateDeductionResult {
8394     /// Template argument deduction was successful.
8395     TDK_Success = 0,
8396     /// The declaration was invalid; do nothing.
8397     TDK_Invalid,
8398     /// Template argument deduction exceeded the maximum template
8399     /// instantiation depth (which has already been diagnosed).
8400     TDK_InstantiationDepth,
8401     /// Template argument deduction did not deduce a value
8402     /// for every template parameter.
8403     TDK_Incomplete,
8404     /// Template argument deduction did not deduce a value for every
8405     /// expansion of an expanded template parameter pack.
8406     TDK_IncompletePack,
8407     /// Template argument deduction produced inconsistent
8408     /// deduced values for the given template parameter.
8409     TDK_Inconsistent,
8410     /// Template argument deduction failed due to inconsistent
8411     /// cv-qualifiers on a template parameter type that would
8412     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8413     /// but were given a non-const "X".
8414     TDK_Underqualified,
8415     /// Substitution of the deduced template argument values
8416     /// resulted in an error.
8417     TDK_SubstitutionFailure,
8418     /// After substituting deduced template arguments, a dependent
8419     /// parameter type did not match the corresponding argument.
8420     TDK_DeducedMismatch,
8421     /// After substituting deduced template arguments, an element of
8422     /// a dependent parameter type did not match the corresponding element
8423     /// of the corresponding argument (when deducing from an initializer list).
8424     TDK_DeducedMismatchNested,
8425     /// A non-depnedent component of the parameter did not match the
8426     /// corresponding component of the argument.
8427     TDK_NonDeducedMismatch,
8428     /// When performing template argument deduction for a function
8429     /// template, there were too many call arguments.
8430     TDK_TooManyArguments,
8431     /// When performing template argument deduction for a function
8432     /// template, there were too few call arguments.
8433     TDK_TooFewArguments,
8434     /// The explicitly-specified template arguments were not valid
8435     /// template arguments for the given template.
8436     TDK_InvalidExplicitArguments,
8437     /// Checking non-dependent argument conversions failed.
8438     TDK_NonDependentConversionFailure,
8439     /// The deduced arguments did not satisfy the constraints associated
8440     /// with the template.
8441     TDK_ConstraintsNotSatisfied,
8442     /// Deduction failed; that's all we know.
8443     TDK_MiscellaneousDeductionFailure,
8444     /// CUDA Target attributes do not match.
8445     TDK_CUDATargetMismatch
8446   };
8447 
8448   TemplateDeductionResult
8449   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8450                           const TemplateArgumentList &TemplateArgs,
8451                           sema::TemplateDeductionInfo &Info);
8452 
8453   TemplateDeductionResult
8454   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8455                           const TemplateArgumentList &TemplateArgs,
8456                           sema::TemplateDeductionInfo &Info);
8457 
8458   TemplateDeductionResult SubstituteExplicitTemplateArguments(
8459       FunctionTemplateDecl *FunctionTemplate,
8460       TemplateArgumentListInfo &ExplicitTemplateArgs,
8461       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8462       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8463       sema::TemplateDeductionInfo &Info);
8464 
8465   /// brief A function argument from which we performed template argument
8466   // deduction for a call.
8467   struct OriginalCallArg {
OriginalCallArgOriginalCallArg8468     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8469                     unsigned ArgIdx, QualType OriginalArgType)
8470         : OriginalParamType(OriginalParamType),
8471           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8472           OriginalArgType(OriginalArgType) {}
8473 
8474     QualType OriginalParamType;
8475     bool DecomposedParam;
8476     unsigned ArgIdx;
8477     QualType OriginalArgType;
8478   };
8479 
8480   TemplateDeductionResult FinishTemplateArgumentDeduction(
8481       FunctionTemplateDecl *FunctionTemplate,
8482       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8483       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8484       sema::TemplateDeductionInfo &Info,
8485       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8486       bool PartialOverloading = false,
8487       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8488 
8489   TemplateDeductionResult DeduceTemplateArguments(
8490       FunctionTemplateDecl *FunctionTemplate,
8491       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8492       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8493       bool PartialOverloading,
8494       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8495 
8496   TemplateDeductionResult
8497   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8498                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8499                           QualType ArgFunctionType,
8500                           FunctionDecl *&Specialization,
8501                           sema::TemplateDeductionInfo &Info,
8502                           bool IsAddressOfFunction = false);
8503 
8504   TemplateDeductionResult
8505   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8506                           QualType ToType,
8507                           CXXConversionDecl *&Specialization,
8508                           sema::TemplateDeductionInfo &Info);
8509 
8510   TemplateDeductionResult
8511   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8512                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8513                           FunctionDecl *&Specialization,
8514                           sema::TemplateDeductionInfo &Info,
8515                           bool IsAddressOfFunction = false);
8516 
8517   /// Substitute Replacement for \p auto in \p TypeWithAuto
8518   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8519   /// Substitute Replacement for auto in TypeWithAuto
8520   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8521                                           QualType Replacement);
8522   /// Completely replace the \c auto in \p TypeWithAuto by
8523   /// \p Replacement. This does not retain any \c auto type sugar.
8524   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8525   TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8526                                             QualType Replacement);
8527 
8528   /// Result type of DeduceAutoType.
8529   enum DeduceAutoResult {
8530     DAR_Succeeded,
8531     DAR_Failed,
8532     DAR_FailedAlreadyDiagnosed
8533   };
8534 
8535   DeduceAutoResult
8536   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8537                  Optional<unsigned> DependentDeductionDepth = None,
8538                  bool IgnoreConstraints = false);
8539   DeduceAutoResult
8540   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8541                  Optional<unsigned> DependentDeductionDepth = None,
8542                  bool IgnoreConstraints = false);
8543   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8544   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8545                         bool Diagnose = true);
8546 
8547   /// Declare implicit deduction guides for a class template if we've
8548   /// not already done so.
8549   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8550                                       SourceLocation Loc);
8551 
8552   QualType DeduceTemplateSpecializationFromInitializer(
8553       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8554       const InitializationKind &Kind, MultiExprArg Init);
8555 
8556   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8557                                         QualType Type, TypeSourceInfo *TSI,
8558                                         SourceRange Range, bool DirectInit,
8559                                         Expr *Init);
8560 
8561   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8562 
8563   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8564                                         SourceLocation ReturnLoc,
8565                                         Expr *&RetExpr, AutoType *AT);
8566 
8567   FunctionTemplateDecl *getMoreSpecializedTemplate(
8568       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8569       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8570       unsigned NumCallArguments2, bool Reversed = false);
8571   UnresolvedSetIterator
8572   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8573                      TemplateSpecCandidateSet &FailedCandidates,
8574                      SourceLocation Loc,
8575                      const PartialDiagnostic &NoneDiag,
8576                      const PartialDiagnostic &AmbigDiag,
8577                      const PartialDiagnostic &CandidateDiag,
8578                      bool Complain = true, QualType TargetType = QualType());
8579 
8580   ClassTemplatePartialSpecializationDecl *
8581   getMoreSpecializedPartialSpecialization(
8582                                   ClassTemplatePartialSpecializationDecl *PS1,
8583                                   ClassTemplatePartialSpecializationDecl *PS2,
8584                                   SourceLocation Loc);
8585 
8586   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8587                                     sema::TemplateDeductionInfo &Info);
8588 
8589   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8590       VarTemplatePartialSpecializationDecl *PS1,
8591       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8592 
8593   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8594                                     sema::TemplateDeductionInfo &Info);
8595 
8596   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8597       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8598 
8599   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8600                                   unsigned Depth, llvm::SmallBitVector &Used);
8601 
8602   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8603                                   bool OnlyDeduced,
8604                                   unsigned Depth,
8605                                   llvm::SmallBitVector &Used);
MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)8606   void MarkDeducedTemplateParameters(
8607                                   const FunctionTemplateDecl *FunctionTemplate,
8608                                   llvm::SmallBitVector &Deduced) {
8609     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8610   }
8611   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8612                                   const FunctionTemplateDecl *FunctionTemplate,
8613                                   llvm::SmallBitVector &Deduced);
8614 
8615   //===--------------------------------------------------------------------===//
8616   // C++ Template Instantiation
8617   //
8618 
8619   MultiLevelTemplateArgumentList
8620   getTemplateInstantiationArgs(NamedDecl *D,
8621                                const TemplateArgumentList *Innermost = nullptr,
8622                                bool RelativeToPrimary = false,
8623                                const FunctionDecl *Pattern = nullptr);
8624 
8625   /// A context in which code is being synthesized (where a source location
8626   /// alone is not sufficient to identify the context). This covers template
8627   /// instantiation and various forms of implicitly-generated functions.
8628   struct CodeSynthesisContext {
8629     /// The kind of template instantiation we are performing
8630     enum SynthesisKind {
8631       /// We are instantiating a template declaration. The entity is
8632       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8633       TemplateInstantiation,
8634 
8635       /// We are instantiating a default argument for a template
8636       /// parameter. The Entity is the template parameter whose argument is
8637       /// being instantiated, the Template is the template, and the
8638       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8639       /// specified.
8640       DefaultTemplateArgumentInstantiation,
8641 
8642       /// We are instantiating a default argument for a function.
8643       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8644       /// provides the template arguments as specified.
8645       DefaultFunctionArgumentInstantiation,
8646 
8647       /// We are substituting explicit template arguments provided for
8648       /// a function template. The entity is a FunctionTemplateDecl.
8649       ExplicitTemplateArgumentSubstitution,
8650 
8651       /// We are substituting template argument determined as part of
8652       /// template argument deduction for either a class template
8653       /// partial specialization or a function template. The
8654       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8655       /// a TemplateDecl.
8656       DeducedTemplateArgumentSubstitution,
8657 
8658       /// We are substituting prior template arguments into a new
8659       /// template parameter. The template parameter itself is either a
8660       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8661       PriorTemplateArgumentSubstitution,
8662 
8663       /// We are checking the validity of a default template argument that
8664       /// has been used when naming a template-id.
8665       DefaultTemplateArgumentChecking,
8666 
8667       /// We are computing the exception specification for a defaulted special
8668       /// member function.
8669       ExceptionSpecEvaluation,
8670 
8671       /// We are instantiating the exception specification for a function
8672       /// template which was deferred until it was needed.
8673       ExceptionSpecInstantiation,
8674 
8675       /// We are instantiating a requirement of a requires expression.
8676       RequirementInstantiation,
8677 
8678       /// We are checking the satisfaction of a nested requirement of a requires
8679       /// expression.
8680       NestedRequirementConstraintsCheck,
8681 
8682       /// We are declaring an implicit special member function.
8683       DeclaringSpecialMember,
8684 
8685       /// We are declaring an implicit 'operator==' for a defaulted
8686       /// 'operator<=>'.
8687       DeclaringImplicitEqualityComparison,
8688 
8689       /// We are defining a synthesized function (such as a defaulted special
8690       /// member).
8691       DefiningSynthesizedFunction,
8692 
8693       // We are checking the constraints associated with a constrained entity or
8694       // the constraint expression of a concept. This includes the checks that
8695       // atomic constraints have the type 'bool' and that they can be constant
8696       // evaluated.
8697       ConstraintsCheck,
8698 
8699       // We are substituting template arguments into a constraint expression.
8700       ConstraintSubstitution,
8701 
8702       // We are normalizing a constraint expression.
8703       ConstraintNormalization,
8704 
8705       // We are substituting into the parameter mapping of an atomic constraint
8706       // during normalization.
8707       ParameterMappingSubstitution,
8708 
8709       /// We are rewriting a comparison operator in terms of an operator<=>.
8710       RewritingOperatorAsSpaceship,
8711 
8712       /// We are initializing a structured binding.
8713       InitializingStructuredBinding,
8714 
8715       /// We are marking a class as __dllexport.
8716       MarkingClassDllexported,
8717 
8718       /// Added for Template instantiation observation.
8719       /// Memoization means we are _not_ instantiating a template because
8720       /// it is already instantiated (but we entered a context where we
8721       /// would have had to if it was not already instantiated).
8722       Memoization
8723     } Kind;
8724 
8725     /// Was the enclosing context a non-instantiation SFINAE context?
8726     bool SavedInNonInstantiationSFINAEContext;
8727 
8728     /// The point of instantiation or synthesis within the source code.
8729     SourceLocation PointOfInstantiation;
8730 
8731     /// The entity that is being synthesized.
8732     Decl *Entity;
8733 
8734     /// The template (or partial specialization) in which we are
8735     /// performing the instantiation, for substitutions of prior template
8736     /// arguments.
8737     NamedDecl *Template;
8738 
8739     /// The list of template arguments we are substituting, if they
8740     /// are not part of the entity.
8741     const TemplateArgument *TemplateArgs;
8742 
8743     // FIXME: Wrap this union around more members, or perhaps store the
8744     // kind-specific members in the RAII object owning the context.
8745     union {
8746       /// The number of template arguments in TemplateArgs.
8747       unsigned NumTemplateArgs;
8748 
8749       /// The special member being declared or defined.
8750       CXXSpecialMember SpecialMember;
8751     };
8752 
template_argumentsCodeSynthesisContext8753     ArrayRef<TemplateArgument> template_arguments() const {
8754       assert(Kind != DeclaringSpecialMember);
8755       return {TemplateArgs, NumTemplateArgs};
8756     }
8757 
8758     /// The template deduction info object associated with the
8759     /// substitution or checking of explicit or deduced template arguments.
8760     sema::TemplateDeductionInfo *DeductionInfo;
8761 
8762     /// The source range that covers the construct that cause
8763     /// the instantiation, e.g., the template-id that causes a class
8764     /// template instantiation.
8765     SourceRange InstantiationRange;
8766 
CodeSynthesisContextCodeSynthesisContext8767     CodeSynthesisContext()
8768         : Kind(TemplateInstantiation),
8769           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8770           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8771           DeductionInfo(nullptr) {}
8772 
8773     /// Determines whether this template is an actual instantiation
8774     /// that should be counted toward the maximum instantiation depth.
8775     bool isInstantiationRecord() const;
8776   };
8777 
8778   /// List of active code synthesis contexts.
8779   ///
8780   /// This vector is treated as a stack. As synthesis of one entity requires
8781   /// synthesis of another, additional contexts are pushed onto the stack.
8782   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8783 
8784   /// Specializations whose definitions are currently being instantiated.
8785   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8786 
8787   /// Non-dependent types used in templates that have already been instantiated
8788   /// by some template instantiation.
8789   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8790 
8791   /// Extra modules inspected when performing a lookup during a template
8792   /// instantiation. Computed lazily.
8793   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8794 
8795   /// Cache of additional modules that should be used for name lookup
8796   /// within the current template instantiation. Computed lazily; use
8797   /// getLookupModules() to get a complete set.
8798   llvm::DenseSet<Module*> LookupModulesCache;
8799 
8800   /// Get the set of additional modules that should be checked during
8801   /// name lookup. A module and its imports become visible when instanting a
8802   /// template defined within it.
8803   llvm::DenseSet<Module*> &getLookupModules();
8804 
8805   /// Map from the most recent declaration of a namespace to the most
8806   /// recent visible declaration of that namespace.
8807   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8808 
8809   /// Whether we are in a SFINAE context that is not associated with
8810   /// template instantiation.
8811   ///
8812   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8813   /// of a template instantiation or template argument deduction.
8814   bool InNonInstantiationSFINAEContext;
8815 
8816   /// The number of \p CodeSynthesisContexts that are not template
8817   /// instantiations and, therefore, should not be counted as part of the
8818   /// instantiation depth.
8819   ///
8820   /// When the instantiation depth reaches the user-configurable limit
8821   /// \p LangOptions::InstantiationDepth we will abort instantiation.
8822   // FIXME: Should we have a similar limit for other forms of synthesis?
8823   unsigned NonInstantiationEntries;
8824 
8825   /// The depth of the context stack at the point when the most recent
8826   /// error or warning was produced.
8827   ///
8828   /// This value is used to suppress printing of redundant context stacks
8829   /// when there are multiple errors or warnings in the same instantiation.
8830   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8831   unsigned LastEmittedCodeSynthesisContextDepth = 0;
8832 
8833   /// The template instantiation callbacks to trace or track
8834   /// instantiations (objects can be chained).
8835   ///
8836   /// This callbacks is used to print, trace or track template
8837   /// instantiations as they are being constructed.
8838   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8839       TemplateInstCallbacks;
8840 
8841   /// The current index into pack expansion arguments that will be
8842   /// used for substitution of parameter packs.
8843   ///
8844   /// The pack expansion index will be -1 to indicate that parameter packs
8845   /// should be instantiated as themselves. Otherwise, the index specifies
8846   /// which argument within the parameter pack will be used for substitution.
8847   int ArgumentPackSubstitutionIndex;
8848 
8849   /// RAII object used to change the argument pack substitution index
8850   /// within a \c Sema object.
8851   ///
8852   /// See \c ArgumentPackSubstitutionIndex for more information.
8853   class ArgumentPackSubstitutionIndexRAII {
8854     Sema &Self;
8855     int OldSubstitutionIndex;
8856 
8857   public:
ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)8858     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8859       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8860       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8861     }
8862 
~ArgumentPackSubstitutionIndexRAII()8863     ~ArgumentPackSubstitutionIndexRAII() {
8864       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8865     }
8866   };
8867 
8868   friend class ArgumentPackSubstitutionRAII;
8869 
8870   /// For each declaration that involved template argument deduction, the
8871   /// set of diagnostics that were suppressed during that template argument
8872   /// deduction.
8873   ///
8874   /// FIXME: Serialize this structure to the AST file.
8875   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8876     SuppressedDiagnosticsMap;
8877   SuppressedDiagnosticsMap SuppressedDiagnostics;
8878 
8879   /// A stack object to be created when performing template
8880   /// instantiation.
8881   ///
8882   /// Construction of an object of type \c InstantiatingTemplate
8883   /// pushes the current instantiation onto the stack of active
8884   /// instantiations. If the size of this stack exceeds the maximum
8885   /// number of recursive template instantiations, construction
8886   /// produces an error and evaluates true.
8887   ///
8888   /// Destruction of this object will pop the named instantiation off
8889   /// the stack.
8890   struct InstantiatingTemplate {
8891     /// Note that we are instantiating a class template,
8892     /// function template, variable template, alias template,
8893     /// or a member thereof.
8894     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8895                           Decl *Entity,
8896                           SourceRange InstantiationRange = SourceRange());
8897 
8898     struct ExceptionSpecification {};
8899     /// Note that we are instantiating an exception specification
8900     /// of a function template.
8901     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8902                           FunctionDecl *Entity, ExceptionSpecification,
8903                           SourceRange InstantiationRange = SourceRange());
8904 
8905     /// Note that we are instantiating a default argument in a
8906     /// template-id.
8907     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8908                           TemplateParameter Param, TemplateDecl *Template,
8909                           ArrayRef<TemplateArgument> TemplateArgs,
8910                           SourceRange InstantiationRange = SourceRange());
8911 
8912     /// Note that we are substituting either explicitly-specified or
8913     /// deduced template arguments during function template argument deduction.
8914     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8915                           FunctionTemplateDecl *FunctionTemplate,
8916                           ArrayRef<TemplateArgument> TemplateArgs,
8917                           CodeSynthesisContext::SynthesisKind Kind,
8918                           sema::TemplateDeductionInfo &DeductionInfo,
8919                           SourceRange InstantiationRange = SourceRange());
8920 
8921     /// Note that we are instantiating as part of template
8922     /// argument deduction for a class template declaration.
8923     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8924                           TemplateDecl *Template,
8925                           ArrayRef<TemplateArgument> TemplateArgs,
8926                           sema::TemplateDeductionInfo &DeductionInfo,
8927                           SourceRange InstantiationRange = SourceRange());
8928 
8929     /// Note that we are instantiating as part of template
8930     /// argument deduction for a class template partial
8931     /// specialization.
8932     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8933                           ClassTemplatePartialSpecializationDecl *PartialSpec,
8934                           ArrayRef<TemplateArgument> TemplateArgs,
8935                           sema::TemplateDeductionInfo &DeductionInfo,
8936                           SourceRange InstantiationRange = SourceRange());
8937 
8938     /// Note that we are instantiating as part of template
8939     /// argument deduction for a variable template partial
8940     /// specialization.
8941     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8942                           VarTemplatePartialSpecializationDecl *PartialSpec,
8943                           ArrayRef<TemplateArgument> TemplateArgs,
8944                           sema::TemplateDeductionInfo &DeductionInfo,
8945                           SourceRange InstantiationRange = SourceRange());
8946 
8947     /// Note that we are instantiating a default argument for a function
8948     /// parameter.
8949     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8950                           ParmVarDecl *Param,
8951                           ArrayRef<TemplateArgument> TemplateArgs,
8952                           SourceRange InstantiationRange = SourceRange());
8953 
8954     /// Note that we are substituting prior template arguments into a
8955     /// non-type parameter.
8956     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8957                           NamedDecl *Template,
8958                           NonTypeTemplateParmDecl *Param,
8959                           ArrayRef<TemplateArgument> TemplateArgs,
8960                           SourceRange InstantiationRange);
8961 
8962     /// Note that we are substituting prior template arguments into a
8963     /// template template parameter.
8964     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8965                           NamedDecl *Template,
8966                           TemplateTemplateParmDecl *Param,
8967                           ArrayRef<TemplateArgument> TemplateArgs,
8968                           SourceRange InstantiationRange);
8969 
8970     /// Note that we are checking the default template argument
8971     /// against the template parameter for a given template-id.
8972     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8973                           TemplateDecl *Template,
8974                           NamedDecl *Param,
8975                           ArrayRef<TemplateArgument> TemplateArgs,
8976                           SourceRange InstantiationRange);
8977 
8978     struct ConstraintsCheck {};
8979     /// \brief Note that we are checking the constraints associated with some
8980     /// constrained entity (a concept declaration or a template with associated
8981     /// constraints).
8982     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8983                           ConstraintsCheck, NamedDecl *Template,
8984                           ArrayRef<TemplateArgument> TemplateArgs,
8985                           SourceRange InstantiationRange);
8986 
8987     struct ConstraintSubstitution {};
8988     /// \brief Note that we are checking a constraint expression associated
8989     /// with a template declaration or as part of the satisfaction check of a
8990     /// concept.
8991     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8992                           ConstraintSubstitution, NamedDecl *Template,
8993                           sema::TemplateDeductionInfo &DeductionInfo,
8994                           SourceRange InstantiationRange);
8995 
8996     struct ConstraintNormalization {};
8997     /// \brief Note that we are normalizing a constraint expression.
8998     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8999                           ConstraintNormalization, NamedDecl *Template,
9000                           SourceRange InstantiationRange);
9001 
9002     struct ParameterMappingSubstitution {};
9003     /// \brief Note that we are subtituting into the parameter mapping of an
9004     /// atomic constraint during constraint normalization.
9005     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9006                           ParameterMappingSubstitution, NamedDecl *Template,
9007                           SourceRange InstantiationRange);
9008 
9009     /// \brief Note that we are substituting template arguments into a part of
9010     /// a requirement of a requires expression.
9011     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9012                           concepts::Requirement *Req,
9013                           sema::TemplateDeductionInfo &DeductionInfo,
9014                           SourceRange InstantiationRange = SourceRange());
9015 
9016     /// \brief Note that we are checking the satisfaction of the constraint
9017     /// expression inside of a nested requirement.
9018     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9019                           concepts::NestedRequirement *Req, ConstraintsCheck,
9020                           SourceRange InstantiationRange = SourceRange());
9021 
9022     /// Note that we have finished instantiating this template.
9023     void Clear();
9024 
~InstantiatingTemplateInstantiatingTemplate9025     ~InstantiatingTemplate() { Clear(); }
9026 
9027     /// Determines whether we have exceeded the maximum
9028     /// recursive template instantiations.
isInvalidInstantiatingTemplate9029     bool isInvalid() const { return Invalid; }
9030 
9031     /// Determine whether we are already instantiating this
9032     /// specialization in some surrounding active instantiation.
isAlreadyInstantiatingInstantiatingTemplate9033     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9034 
9035   private:
9036     Sema &SemaRef;
9037     bool Invalid;
9038     bool AlreadyInstantiating;
9039     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9040                                  SourceRange InstantiationRange);
9041 
9042     InstantiatingTemplate(
9043         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9044         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9045         Decl *Entity, NamedDecl *Template = nullptr,
9046         ArrayRef<TemplateArgument> TemplateArgs = None,
9047         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9048 
9049     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9050 
9051     InstantiatingTemplate&
9052     operator=(const InstantiatingTemplate&) = delete;
9053   };
9054 
9055   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9056   void popCodeSynthesisContext();
9057 
9058   /// Determine whether we are currently performing template instantiation.
inTemplateInstantiation()9059   bool inTemplateInstantiation() const {
9060     return CodeSynthesisContexts.size() > NonInstantiationEntries;
9061   }
9062 
PrintContextStack()9063   void PrintContextStack() {
9064     if (!CodeSynthesisContexts.empty() &&
9065         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9066       PrintInstantiationStack();
9067       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9068     }
9069     if (PragmaAttributeCurrentTargetDecl)
9070       PrintPragmaAttributeInstantiationPoint();
9071   }
9072   void PrintInstantiationStack();
9073 
9074   void PrintPragmaAttributeInstantiationPoint();
9075 
9076   /// Determines whether we are currently in a context where
9077   /// template argument substitution failures are not considered
9078   /// errors.
9079   ///
9080   /// \returns An empty \c Optional if we're not in a SFINAE context.
9081   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9082   /// template-deduction context object, which can be used to capture
9083   /// diagnostics that will be suppressed.
9084   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9085 
9086   /// Determines whether we are currently in a context that
9087   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()9088   bool isUnevaluatedContext() const {
9089     assert(!ExprEvalContexts.empty() &&
9090            "Must be in an expression evaluation context");
9091     return ExprEvalContexts.back().isUnevaluated();
9092   }
9093 
9094   /// RAII class used to determine whether SFINAE has
9095   /// trapped any errors that occur during template argument
9096   /// deduction.
9097   class SFINAETrap {
9098     Sema &SemaRef;
9099     unsigned PrevSFINAEErrors;
9100     bool PrevInNonInstantiationSFINAEContext;
9101     bool PrevAccessCheckingSFINAE;
9102     bool PrevLastDiagnosticIgnored;
9103 
9104   public:
9105     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
SemaRef(SemaRef)9106       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9107         PrevInNonInstantiationSFINAEContext(
9108                                       SemaRef.InNonInstantiationSFINAEContext),
9109         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9110         PrevLastDiagnosticIgnored(
9111             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9112     {
9113       if (!SemaRef.isSFINAEContext())
9114         SemaRef.InNonInstantiationSFINAEContext = true;
9115       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9116     }
9117 
~SFINAETrap()9118     ~SFINAETrap() {
9119       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9120       SemaRef.InNonInstantiationSFINAEContext
9121         = PrevInNonInstantiationSFINAEContext;
9122       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9123       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9124           PrevLastDiagnosticIgnored);
9125     }
9126 
9127     /// Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()9128     bool hasErrorOccurred() const {
9129       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9130     }
9131   };
9132 
9133   /// RAII class used to indicate that we are performing provisional
9134   /// semantic analysis to determine the validity of a construct, so
9135   /// typo-correction and diagnostics in the immediate context (not within
9136   /// implicitly-instantiated templates) should be suppressed.
9137   class TentativeAnalysisScope {
9138     Sema &SemaRef;
9139     // FIXME: Using a SFINAETrap for this is a hack.
9140     SFINAETrap Trap;
9141     bool PrevDisableTypoCorrection;
9142   public:
TentativeAnalysisScope(Sema & SemaRef)9143     explicit TentativeAnalysisScope(Sema &SemaRef)
9144         : SemaRef(SemaRef), Trap(SemaRef, true),
9145           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9146       SemaRef.DisableTypoCorrection = true;
9147     }
~TentativeAnalysisScope()9148     ~TentativeAnalysisScope() {
9149       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9150     }
9151   };
9152 
9153   /// The current instantiation scope used to store local
9154   /// variables.
9155   LocalInstantiationScope *CurrentInstantiationScope;
9156 
9157   /// Tracks whether we are in a context where typo correction is
9158   /// disabled.
9159   bool DisableTypoCorrection;
9160 
9161   /// The number of typos corrected by CorrectTypo.
9162   unsigned TyposCorrected;
9163 
9164   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9165   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9166 
9167   /// A cache containing identifiers for which typo correction failed and
9168   /// their locations, so that repeated attempts to correct an identifier in a
9169   /// given location are ignored if typo correction already failed for it.
9170   IdentifierSourceLocations TypoCorrectionFailures;
9171 
9172   /// Worker object for performing CFG-based warnings.
9173   sema::AnalysisBasedWarnings AnalysisWarnings;
9174   threadSafety::BeforeSet *ThreadSafetyDeclCache;
9175 
9176   /// An entity for which implicit template instantiation is required.
9177   ///
9178   /// The source location associated with the declaration is the first place in
9179   /// the source code where the declaration was "used". It is not necessarily
9180   /// the point of instantiation (which will be either before or after the
9181   /// namespace-scope declaration that triggered this implicit instantiation),
9182   /// However, it is the location that diagnostics should generally refer to,
9183   /// because users will need to know what code triggered the instantiation.
9184   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9185 
9186   /// The queue of implicit template instantiations that are required
9187   /// but have not yet been performed.
9188   std::deque<PendingImplicitInstantiation> PendingInstantiations;
9189 
9190   /// Queue of implicit template instantiations that cannot be performed
9191   /// eagerly.
9192   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9193 
9194   class GlobalEagerInstantiationScope {
9195   public:
GlobalEagerInstantiationScope(Sema & S,bool Enabled)9196     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9197         : S(S), Enabled(Enabled) {
9198       if (!Enabled) return;
9199 
9200       SavedPendingInstantiations.swap(S.PendingInstantiations);
9201       SavedVTableUses.swap(S.VTableUses);
9202     }
9203 
perform()9204     void perform() {
9205       if (Enabled) {
9206         S.DefineUsedVTables();
9207         S.PerformPendingInstantiations();
9208       }
9209     }
9210 
~GlobalEagerInstantiationScope()9211     ~GlobalEagerInstantiationScope() {
9212       if (!Enabled) return;
9213 
9214       // Restore the set of pending vtables.
9215       assert(S.VTableUses.empty() &&
9216              "VTableUses should be empty before it is discarded.");
9217       S.VTableUses.swap(SavedVTableUses);
9218 
9219       // Restore the set of pending implicit instantiations.
9220       if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9221         assert(S.PendingInstantiations.empty() &&
9222                "PendingInstantiations should be empty before it is discarded.");
9223         S.PendingInstantiations.swap(SavedPendingInstantiations);
9224       } else {
9225         // Template instantiations in the PCH may be delayed until the TU.
9226         S.PendingInstantiations.swap(SavedPendingInstantiations);
9227         S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9228                                        SavedPendingInstantiations.begin(),
9229                                        SavedPendingInstantiations.end());
9230       }
9231     }
9232 
9233   private:
9234     Sema &S;
9235     SmallVector<VTableUse, 16> SavedVTableUses;
9236     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9237     bool Enabled;
9238   };
9239 
9240   /// The queue of implicit template instantiations that are required
9241   /// and must be performed within the current local scope.
9242   ///
9243   /// This queue is only used for member functions of local classes in
9244   /// templates, which must be instantiated in the same scope as their
9245   /// enclosing function, so that they can reference function-local
9246   /// types, static variables, enumerators, etc.
9247   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9248 
9249   class LocalEagerInstantiationScope {
9250   public:
LocalEagerInstantiationScope(Sema & S)9251     LocalEagerInstantiationScope(Sema &S) : S(S) {
9252       SavedPendingLocalImplicitInstantiations.swap(
9253           S.PendingLocalImplicitInstantiations);
9254     }
9255 
perform()9256     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9257 
~LocalEagerInstantiationScope()9258     ~LocalEagerInstantiationScope() {
9259       assert(S.PendingLocalImplicitInstantiations.empty() &&
9260              "there shouldn't be any pending local implicit instantiations");
9261       SavedPendingLocalImplicitInstantiations.swap(
9262           S.PendingLocalImplicitInstantiations);
9263     }
9264 
9265   private:
9266     Sema &S;
9267     std::deque<PendingImplicitInstantiation>
9268         SavedPendingLocalImplicitInstantiations;
9269   };
9270 
9271   /// A helper class for building up ExtParameterInfos.
9272   class ExtParameterInfoBuilder {
9273     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9274     bool HasInteresting = false;
9275 
9276   public:
9277     /// Set the ExtParameterInfo for the parameter at the given index,
9278     ///
set(unsigned index,FunctionProtoType::ExtParameterInfo info)9279     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9280       assert(Infos.size() <= index);
9281       Infos.resize(index);
9282       Infos.push_back(info);
9283 
9284       if (!HasInteresting)
9285         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9286     }
9287 
9288     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9289     /// ExtParameterInfo array we've built up.
9290     const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams)9291     getPointerOrNull(unsigned numParams) {
9292       if (!HasInteresting) return nullptr;
9293       Infos.resize(numParams);
9294       return Infos.data();
9295     }
9296   };
9297 
9298   void PerformPendingInstantiations(bool LocalOnly = false);
9299 
9300   TypeSourceInfo *SubstType(TypeSourceInfo *T,
9301                             const MultiLevelTemplateArgumentList &TemplateArgs,
9302                             SourceLocation Loc, DeclarationName Entity,
9303                             bool AllowDeducedTST = false);
9304 
9305   QualType SubstType(QualType T,
9306                      const MultiLevelTemplateArgumentList &TemplateArgs,
9307                      SourceLocation Loc, DeclarationName Entity);
9308 
9309   TypeSourceInfo *SubstType(TypeLoc TL,
9310                             const MultiLevelTemplateArgumentList &TemplateArgs,
9311                             SourceLocation Loc, DeclarationName Entity);
9312 
9313   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9314                             const MultiLevelTemplateArgumentList &TemplateArgs,
9315                                         SourceLocation Loc,
9316                                         DeclarationName Entity,
9317                                         CXXRecordDecl *ThisContext,
9318                                         Qualifiers ThisTypeQuals);
9319   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9320                           const MultiLevelTemplateArgumentList &Args);
9321   bool SubstExceptionSpec(SourceLocation Loc,
9322                           FunctionProtoType::ExceptionSpecInfo &ESI,
9323                           SmallVectorImpl<QualType> &ExceptionStorage,
9324                           const MultiLevelTemplateArgumentList &Args);
9325   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9326                             const MultiLevelTemplateArgumentList &TemplateArgs,
9327                                 int indexAdjustment,
9328                                 Optional<unsigned> NumExpansions,
9329                                 bool ExpectParameterPack);
9330   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9331                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9332                       const MultiLevelTemplateArgumentList &TemplateArgs,
9333                       SmallVectorImpl<QualType> &ParamTypes,
9334                       SmallVectorImpl<ParmVarDecl *> *OutParams,
9335                       ExtParameterInfoBuilder &ParamInfos);
9336   ExprResult SubstExpr(Expr *E,
9337                        const MultiLevelTemplateArgumentList &TemplateArgs);
9338 
9339   /// Substitute the given template arguments into a list of
9340   /// expressions, expanding pack expansions if required.
9341   ///
9342   /// \param Exprs The list of expressions to substitute into.
9343   ///
9344   /// \param IsCall Whether this is some form of call, in which case
9345   /// default arguments will be dropped.
9346   ///
9347   /// \param TemplateArgs The set of template arguments to substitute.
9348   ///
9349   /// \param Outputs Will receive all of the substituted arguments.
9350   ///
9351   /// \returns true if an error occurred, false otherwise.
9352   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9353                   const MultiLevelTemplateArgumentList &TemplateArgs,
9354                   SmallVectorImpl<Expr *> &Outputs);
9355 
9356   StmtResult SubstStmt(Stmt *S,
9357                        const MultiLevelTemplateArgumentList &TemplateArgs);
9358 
9359   TemplateParameterList *
9360   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9361                       const MultiLevelTemplateArgumentList &TemplateArgs);
9362 
9363   bool
9364   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9365                          const MultiLevelTemplateArgumentList &TemplateArgs,
9366                          TemplateArgumentListInfo &Outputs);
9367 
9368 
9369   Decl *SubstDecl(Decl *D, DeclContext *Owner,
9370                   const MultiLevelTemplateArgumentList &TemplateArgs);
9371 
9372   /// Substitute the name and return type of a defaulted 'operator<=>' to form
9373   /// an implicit 'operator=='.
9374   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9375                                            FunctionDecl *Spaceship);
9376 
9377   ExprResult SubstInitializer(Expr *E,
9378                        const MultiLevelTemplateArgumentList &TemplateArgs,
9379                        bool CXXDirectInit);
9380 
9381   bool
9382   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9383                       CXXRecordDecl *Pattern,
9384                       const MultiLevelTemplateArgumentList &TemplateArgs);
9385 
9386   bool
9387   InstantiateClass(SourceLocation PointOfInstantiation,
9388                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9389                    const MultiLevelTemplateArgumentList &TemplateArgs,
9390                    TemplateSpecializationKind TSK,
9391                    bool Complain = true);
9392 
9393   bool InstantiateEnum(SourceLocation PointOfInstantiation,
9394                        EnumDecl *Instantiation, EnumDecl *Pattern,
9395                        const MultiLevelTemplateArgumentList &TemplateArgs,
9396                        TemplateSpecializationKind TSK);
9397 
9398   bool InstantiateInClassInitializer(
9399       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9400       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9401 
9402   struct LateInstantiatedAttribute {
9403     const Attr *TmplAttr;
9404     LocalInstantiationScope *Scope;
9405     Decl *NewDecl;
9406 
LateInstantiatedAttributeLateInstantiatedAttribute9407     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9408                               Decl *D)
9409       : TmplAttr(A), Scope(S), NewDecl(D)
9410     { }
9411   };
9412   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9413 
9414   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9415                         const Decl *Pattern, Decl *Inst,
9416                         LateInstantiatedAttrVec *LateAttrs = nullptr,
9417                         LocalInstantiationScope *OuterMostScope = nullptr);
9418 
9419   void
9420   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9421                           const Decl *Pattern, Decl *Inst,
9422                           LateInstantiatedAttrVec *LateAttrs = nullptr,
9423                           LocalInstantiationScope *OuterMostScope = nullptr);
9424 
9425   void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
9426 
9427   bool usesPartialOrExplicitSpecialization(
9428       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9429 
9430   bool
9431   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9432                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9433                            TemplateSpecializationKind TSK,
9434                            bool Complain = true);
9435 
9436   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9437                                CXXRecordDecl *Instantiation,
9438                             const MultiLevelTemplateArgumentList &TemplateArgs,
9439                                TemplateSpecializationKind TSK);
9440 
9441   void InstantiateClassTemplateSpecializationMembers(
9442                                           SourceLocation PointOfInstantiation,
9443                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9444                                                 TemplateSpecializationKind TSK);
9445 
9446   NestedNameSpecifierLoc
9447   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9448                            const MultiLevelTemplateArgumentList &TemplateArgs);
9449 
9450   DeclarationNameInfo
9451   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9452                            const MultiLevelTemplateArgumentList &TemplateArgs);
9453   TemplateName
9454   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9455                     SourceLocation Loc,
9456                     const MultiLevelTemplateArgumentList &TemplateArgs);
9457   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
9458              TemplateArgumentListInfo &Result,
9459              const MultiLevelTemplateArgumentList &TemplateArgs);
9460 
9461   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9462                                   ParmVarDecl *Param);
9463   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9464                                 FunctionDecl *Function);
9465   bool CheckInstantiatedFunctionTemplateConstraints(
9466       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9467       ArrayRef<TemplateArgument> TemplateArgs,
9468       ConstraintSatisfaction &Satisfaction);
9469   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9470                                                const TemplateArgumentList *Args,
9471                                                SourceLocation Loc);
9472   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9473                                      FunctionDecl *Function,
9474                                      bool Recursive = false,
9475                                      bool DefinitionRequired = false,
9476                                      bool AtEndOfTU = false);
9477   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9478       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9479       const TemplateArgumentList &TemplateArgList,
9480       const TemplateArgumentListInfo &TemplateArgsInfo,
9481       SmallVectorImpl<TemplateArgument> &Converted,
9482       SourceLocation PointOfInstantiation,
9483       LateInstantiatedAttrVec *LateAttrs = nullptr,
9484       LocalInstantiationScope *StartingScope = nullptr);
9485   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9486       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9487       const MultiLevelTemplateArgumentList &TemplateArgs);
9488   void
9489   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9490                              const MultiLevelTemplateArgumentList &TemplateArgs,
9491                              LateInstantiatedAttrVec *LateAttrs,
9492                              DeclContext *Owner,
9493                              LocalInstantiationScope *StartingScope,
9494                              bool InstantiatingVarTemplate = false,
9495                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9496 
9497   void InstantiateVariableInitializer(
9498       VarDecl *Var, VarDecl *OldVar,
9499       const MultiLevelTemplateArgumentList &TemplateArgs);
9500   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9501                                      VarDecl *Var, bool Recursive = false,
9502                                      bool DefinitionRequired = false,
9503                                      bool AtEndOfTU = false);
9504 
9505   void InstantiateMemInitializers(CXXConstructorDecl *New,
9506                                   const CXXConstructorDecl *Tmpl,
9507                             const MultiLevelTemplateArgumentList &TemplateArgs);
9508 
9509   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9510                           const MultiLevelTemplateArgumentList &TemplateArgs,
9511                           bool FindingInstantiatedContext = false);
9512   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9513                           const MultiLevelTemplateArgumentList &TemplateArgs);
9514 
9515   // Objective-C declarations.
9516   enum ObjCContainerKind {
9517     OCK_None = -1,
9518     OCK_Interface = 0,
9519     OCK_Protocol,
9520     OCK_Category,
9521     OCK_ClassExtension,
9522     OCK_Implementation,
9523     OCK_CategoryImplementation
9524   };
9525   ObjCContainerKind getObjCContainerKind() const;
9526 
9527   DeclResult actOnObjCTypeParam(Scope *S,
9528                                 ObjCTypeParamVariance variance,
9529                                 SourceLocation varianceLoc,
9530                                 unsigned index,
9531                                 IdentifierInfo *paramName,
9532                                 SourceLocation paramLoc,
9533                                 SourceLocation colonLoc,
9534                                 ParsedType typeBound);
9535 
9536   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9537                                             ArrayRef<Decl *> typeParams,
9538                                             SourceLocation rAngleLoc);
9539   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9540 
9541   Decl *ActOnStartClassInterface(
9542       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9543       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9544       IdentifierInfo *SuperName, SourceLocation SuperLoc,
9545       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9546       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9547       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9548       const ParsedAttributesView &AttrList);
9549 
9550   void ActOnSuperClassOfClassInterface(Scope *S,
9551                                        SourceLocation AtInterfaceLoc,
9552                                        ObjCInterfaceDecl *IDecl,
9553                                        IdentifierInfo *ClassName,
9554                                        SourceLocation ClassLoc,
9555                                        IdentifierInfo *SuperName,
9556                                        SourceLocation SuperLoc,
9557                                        ArrayRef<ParsedType> SuperTypeArgs,
9558                                        SourceRange SuperTypeArgsRange);
9559 
9560   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9561                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
9562                                IdentifierInfo *SuperName,
9563                                SourceLocation SuperLoc);
9564 
9565   Decl *ActOnCompatibilityAlias(
9566                     SourceLocation AtCompatibilityAliasLoc,
9567                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
9568                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
9569 
9570   bool CheckForwardProtocolDeclarationForCircularDependency(
9571     IdentifierInfo *PName,
9572     SourceLocation &PLoc, SourceLocation PrevLoc,
9573     const ObjCList<ObjCProtocolDecl> &PList);
9574 
9575   Decl *ActOnStartProtocolInterface(
9576       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9577       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9578       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9579       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9580 
9581   Decl *ActOnStartCategoryInterface(
9582       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9583       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9584       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9585       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9586       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9587       const ParsedAttributesView &AttrList);
9588 
9589   Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9590                                       IdentifierInfo *ClassName,
9591                                       SourceLocation ClassLoc,
9592                                       IdentifierInfo *SuperClassname,
9593                                       SourceLocation SuperClassLoc,
9594                                       const ParsedAttributesView &AttrList);
9595 
9596   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9597                                          IdentifierInfo *ClassName,
9598                                          SourceLocation ClassLoc,
9599                                          IdentifierInfo *CatName,
9600                                          SourceLocation CatLoc,
9601                                          const ParsedAttributesView &AttrList);
9602 
9603   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9604                                                ArrayRef<Decl *> Decls);
9605 
9606   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9607                    IdentifierInfo **IdentList,
9608                    SourceLocation *IdentLocs,
9609                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
9610                    unsigned NumElts);
9611 
9612   DeclGroupPtrTy
9613   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9614                                   ArrayRef<IdentifierLocPair> IdentList,
9615                                   const ParsedAttributesView &attrList);
9616 
9617   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9618                                ArrayRef<IdentifierLocPair> ProtocolId,
9619                                SmallVectorImpl<Decl *> &Protocols);
9620 
9621   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9622                                     SourceLocation ProtocolLoc,
9623                                     IdentifierInfo *TypeArgId,
9624                                     SourceLocation TypeArgLoc,
9625                                     bool SelectProtocolFirst = false);
9626 
9627   /// Given a list of identifiers (and their locations), resolve the
9628   /// names to either Objective-C protocol qualifiers or type
9629   /// arguments, as appropriate.
9630   void actOnObjCTypeArgsOrProtocolQualifiers(
9631          Scope *S,
9632          ParsedType baseType,
9633          SourceLocation lAngleLoc,
9634          ArrayRef<IdentifierInfo *> identifiers,
9635          ArrayRef<SourceLocation> identifierLocs,
9636          SourceLocation rAngleLoc,
9637          SourceLocation &typeArgsLAngleLoc,
9638          SmallVectorImpl<ParsedType> &typeArgs,
9639          SourceLocation &typeArgsRAngleLoc,
9640          SourceLocation &protocolLAngleLoc,
9641          SmallVectorImpl<Decl *> &protocols,
9642          SourceLocation &protocolRAngleLoc,
9643          bool warnOnIncompleteProtocols);
9644 
9645   /// Build a an Objective-C protocol-qualified 'id' type where no
9646   /// base type was specified.
9647   TypeResult actOnObjCProtocolQualifierType(
9648                SourceLocation lAngleLoc,
9649                ArrayRef<Decl *> protocols,
9650                ArrayRef<SourceLocation> protocolLocs,
9651                SourceLocation rAngleLoc);
9652 
9653   /// Build a specialized and/or protocol-qualified Objective-C type.
9654   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9655                Scope *S,
9656                SourceLocation Loc,
9657                ParsedType BaseType,
9658                SourceLocation TypeArgsLAngleLoc,
9659                ArrayRef<ParsedType> TypeArgs,
9660                SourceLocation TypeArgsRAngleLoc,
9661                SourceLocation ProtocolLAngleLoc,
9662                ArrayRef<Decl *> Protocols,
9663                ArrayRef<SourceLocation> ProtocolLocs,
9664                SourceLocation ProtocolRAngleLoc);
9665 
9666   /// Build an Objective-C type parameter type.
9667   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9668                                   SourceLocation ProtocolLAngleLoc,
9669                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9670                                   ArrayRef<SourceLocation> ProtocolLocs,
9671                                   SourceLocation ProtocolRAngleLoc,
9672                                   bool FailOnError = false);
9673 
9674   /// Build an Objective-C object pointer type.
9675   QualType BuildObjCObjectType(QualType BaseType,
9676                                SourceLocation Loc,
9677                                SourceLocation TypeArgsLAngleLoc,
9678                                ArrayRef<TypeSourceInfo *> TypeArgs,
9679                                SourceLocation TypeArgsRAngleLoc,
9680                                SourceLocation ProtocolLAngleLoc,
9681                                ArrayRef<ObjCProtocolDecl *> Protocols,
9682                                ArrayRef<SourceLocation> ProtocolLocs,
9683                                SourceLocation ProtocolRAngleLoc,
9684                                bool FailOnError = false);
9685 
9686   /// Ensure attributes are consistent with type.
9687   /// \param [in, out] Attributes The attributes to check; they will
9688   /// be modified to be consistent with \p PropertyTy.
9689   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9690                                    SourceLocation Loc,
9691                                    unsigned &Attributes,
9692                                    bool propertyInPrimaryClass);
9693 
9694   /// Process the specified property declaration and create decls for the
9695   /// setters and getters as needed.
9696   /// \param property The property declaration being processed
9697   void ProcessPropertyDecl(ObjCPropertyDecl *property);
9698 
9699 
9700   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9701                                 ObjCPropertyDecl *SuperProperty,
9702                                 const IdentifierInfo *Name,
9703                                 bool OverridingProtocolProperty);
9704 
9705   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9706                                         ObjCInterfaceDecl *ID);
9707 
9708   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9709                    ArrayRef<Decl *> allMethods = None,
9710                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
9711 
9712   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9713                       SourceLocation LParenLoc,
9714                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
9715                       Selector GetterSel, Selector SetterSel,
9716                       tok::ObjCKeywordKind MethodImplKind,
9717                       DeclContext *lexicalDC = nullptr);
9718 
9719   Decl *ActOnPropertyImplDecl(Scope *S,
9720                               SourceLocation AtLoc,
9721                               SourceLocation PropertyLoc,
9722                               bool ImplKind,
9723                               IdentifierInfo *PropertyId,
9724                               IdentifierInfo *PropertyIvar,
9725                               SourceLocation PropertyIvarLoc,
9726                               ObjCPropertyQueryKind QueryKind);
9727 
9728   enum ObjCSpecialMethodKind {
9729     OSMK_None,
9730     OSMK_Alloc,
9731     OSMK_New,
9732     OSMK_Copy,
9733     OSMK_RetainingInit,
9734     OSMK_NonRetainingInit
9735   };
9736 
9737   struct ObjCArgInfo {
9738     IdentifierInfo *Name;
9739     SourceLocation NameLoc;
9740     // The Type is null if no type was specified, and the DeclSpec is invalid
9741     // in this case.
9742     ParsedType Type;
9743     ObjCDeclSpec DeclSpec;
9744 
9745     /// ArgAttrs - Attribute list for this argument.
9746     ParsedAttributesView ArgAttrs;
9747   };
9748 
9749   Decl *ActOnMethodDeclaration(
9750       Scope *S,
9751       SourceLocation BeginLoc, // location of the + or -.
9752       SourceLocation EndLoc,   // location of the ; or {.
9753       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9754       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9755       // optional arguments. The number of types/arguments is obtained
9756       // from the Sel.getNumArgs().
9757       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9758       unsigned CNumArgs, // c-style args
9759       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9760       bool isVariadic, bool MethodDefinition);
9761 
9762   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9763                                               const ObjCObjectPointerType *OPT,
9764                                               bool IsInstance);
9765   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9766                                            bool IsInstance);
9767 
9768   bool CheckARCMethodDecl(ObjCMethodDecl *method);
9769   bool inferObjCARCLifetime(ValueDecl *decl);
9770 
9771   void deduceOpenCLAddressSpace(ValueDecl *decl);
9772 
9773   ExprResult
9774   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9775                             Expr *BaseExpr,
9776                             SourceLocation OpLoc,
9777                             DeclarationName MemberName,
9778                             SourceLocation MemberLoc,
9779                             SourceLocation SuperLoc, QualType SuperType,
9780                             bool Super);
9781 
9782   ExprResult
9783   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9784                             IdentifierInfo &propertyName,
9785                             SourceLocation receiverNameLoc,
9786                             SourceLocation propertyNameLoc);
9787 
9788   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9789 
9790   /// Describes the kind of message expression indicated by a message
9791   /// send that starts with an identifier.
9792   enum ObjCMessageKind {
9793     /// The message is sent to 'super'.
9794     ObjCSuperMessage,
9795     /// The message is an instance message.
9796     ObjCInstanceMessage,
9797     /// The message is a class message, and the identifier is a type
9798     /// name.
9799     ObjCClassMessage
9800   };
9801 
9802   ObjCMessageKind getObjCMessageKind(Scope *S,
9803                                      IdentifierInfo *Name,
9804                                      SourceLocation NameLoc,
9805                                      bool IsSuper,
9806                                      bool HasTrailingDot,
9807                                      ParsedType &ReceiverType);
9808 
9809   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9810                                Selector Sel,
9811                                SourceLocation LBracLoc,
9812                                ArrayRef<SourceLocation> SelectorLocs,
9813                                SourceLocation RBracLoc,
9814                                MultiExprArg Args);
9815 
9816   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9817                                QualType ReceiverType,
9818                                SourceLocation SuperLoc,
9819                                Selector Sel,
9820                                ObjCMethodDecl *Method,
9821                                SourceLocation LBracLoc,
9822                                ArrayRef<SourceLocation> SelectorLocs,
9823                                SourceLocation RBracLoc,
9824                                MultiExprArg Args,
9825                                bool isImplicit = false);
9826 
9827   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9828                                        bool isSuperReceiver,
9829                                        SourceLocation Loc,
9830                                        Selector Sel,
9831                                        ObjCMethodDecl *Method,
9832                                        MultiExprArg Args);
9833 
9834   ExprResult ActOnClassMessage(Scope *S,
9835                                ParsedType Receiver,
9836                                Selector Sel,
9837                                SourceLocation LBracLoc,
9838                                ArrayRef<SourceLocation> SelectorLocs,
9839                                SourceLocation RBracLoc,
9840                                MultiExprArg Args);
9841 
9842   ExprResult BuildInstanceMessage(Expr *Receiver,
9843                                   QualType ReceiverType,
9844                                   SourceLocation SuperLoc,
9845                                   Selector Sel,
9846                                   ObjCMethodDecl *Method,
9847                                   SourceLocation LBracLoc,
9848                                   ArrayRef<SourceLocation> SelectorLocs,
9849                                   SourceLocation RBracLoc,
9850                                   MultiExprArg Args,
9851                                   bool isImplicit = false);
9852 
9853   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9854                                           QualType ReceiverType,
9855                                           SourceLocation Loc,
9856                                           Selector Sel,
9857                                           ObjCMethodDecl *Method,
9858                                           MultiExprArg Args);
9859 
9860   ExprResult ActOnInstanceMessage(Scope *S,
9861                                   Expr *Receiver,
9862                                   Selector Sel,
9863                                   SourceLocation LBracLoc,
9864                                   ArrayRef<SourceLocation> SelectorLocs,
9865                                   SourceLocation RBracLoc,
9866                                   MultiExprArg Args);
9867 
9868   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9869                                   ObjCBridgeCastKind Kind,
9870                                   SourceLocation BridgeKeywordLoc,
9871                                   TypeSourceInfo *TSInfo,
9872                                   Expr *SubExpr);
9873 
9874   ExprResult ActOnObjCBridgedCast(Scope *S,
9875                                   SourceLocation LParenLoc,
9876                                   ObjCBridgeCastKind Kind,
9877                                   SourceLocation BridgeKeywordLoc,
9878                                   ParsedType Type,
9879                                   SourceLocation RParenLoc,
9880                                   Expr *SubExpr);
9881 
9882   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9883 
9884   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9885 
9886   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9887                                      CastKind &Kind);
9888 
9889   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9890                                         QualType DestType, QualType SrcType,
9891                                         ObjCInterfaceDecl *&RelatedClass,
9892                                         ObjCMethodDecl *&ClassMethod,
9893                                         ObjCMethodDecl *&InstanceMethod,
9894                                         TypedefNameDecl *&TDNDecl,
9895                                         bool CfToNs, bool Diagnose = true);
9896 
9897   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9898                                          QualType DestType, QualType SrcType,
9899                                          Expr *&SrcExpr, bool Diagnose = true);
9900 
9901   bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
9902                                     bool Diagnose = true);
9903 
9904   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9905 
9906   /// Check whether the given new method is a valid override of the
9907   /// given overridden method, and set any properties that should be inherited.
9908   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9909                                const ObjCMethodDecl *Overridden);
9910 
9911   /// Describes the compatibility of a result type with its method.
9912   enum ResultTypeCompatibilityKind {
9913     RTC_Compatible,
9914     RTC_Incompatible,
9915     RTC_Unknown
9916   };
9917 
9918   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9919                                       ObjCMethodDecl *overridden);
9920 
9921   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9922                                 ObjCInterfaceDecl *CurrentClass,
9923                                 ResultTypeCompatibilityKind RTC);
9924 
9925   enum PragmaOptionsAlignKind {
9926     POAK_Native,  // #pragma options align=native
9927     POAK_Natural, // #pragma options align=natural
9928     POAK_Packed,  // #pragma options align=packed
9929     POAK_Power,   // #pragma options align=power
9930     POAK_Mac68k,  // #pragma options align=mac68k
9931     POAK_Reset    // #pragma options align=reset
9932   };
9933 
9934   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9935   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9936                                PragmaClangSectionAction Action,
9937                                PragmaClangSectionKind SecKind, StringRef SecName);
9938 
9939   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9940   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9941                                SourceLocation PragmaLoc);
9942 
9943   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9944   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9945                        StringRef SlotLabel, Expr *Alignment);
9946 
9947   enum class PragmaAlignPackDiagnoseKind {
9948     NonDefaultStateAtInclude,
9949     ChangedStateAtExit
9950   };
9951 
9952   void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
9953                                          SourceLocation IncludeLoc);
9954   void DiagnoseUnterminatedPragmaAlignPack();
9955 
9956   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9957   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9958 
9959   /// ActOnPragmaMSComment - Called on well formed
9960   /// \#pragma comment(kind, "arg").
9961   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9962                             StringRef Arg);
9963 
9964   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9965   /// pointers_to_members(representation method[, general purpose
9966   /// representation]).
9967   void ActOnPragmaMSPointersToMembers(
9968       LangOptions::PragmaMSPointersToMembersKind Kind,
9969       SourceLocation PragmaLoc);
9970 
9971   /// Called on well formed \#pragma vtordisp().
9972   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9973                              SourceLocation PragmaLoc,
9974                              MSVtorDispMode Value);
9975 
9976   enum PragmaSectionKind {
9977     PSK_DataSeg,
9978     PSK_BSSSeg,
9979     PSK_ConstSeg,
9980     PSK_CodeSeg,
9981   };
9982 
9983   bool UnifySection(StringRef SectionName, int SectionFlags,
9984                     NamedDecl *TheDecl);
9985   bool UnifySection(StringRef SectionName,
9986                     int SectionFlags,
9987                     SourceLocation PragmaSectionLocation);
9988 
9989   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9990   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9991                         PragmaMsStackAction Action,
9992                         llvm::StringRef StackSlotLabel,
9993                         StringLiteral *SegmentName,
9994                         llvm::StringRef PragmaName);
9995 
9996   /// Called on well formed \#pragma section().
9997   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9998                             int SectionFlags, StringLiteral *SegmentName);
9999 
10000   /// Called on well-formed \#pragma init_seg().
10001   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10002                             StringLiteral *SegmentName);
10003 
10004   /// Called on #pragma clang __debug dump II
10005   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10006 
10007   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10008   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10009                                  StringRef Value);
10010 
10011   /// Are precise floating point semantics currently enabled?
isPreciseFPEnabled()10012   bool isPreciseFPEnabled() {
10013     return !CurFPFeatures.getAllowFPReassociate() &&
10014            !CurFPFeatures.getNoSignedZero() &&
10015            !CurFPFeatures.getAllowReciprocal() &&
10016            !CurFPFeatures.getAllowApproxFunc();
10017   }
10018 
10019   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10020   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10021                                PragmaFloatControlKind Value);
10022 
10023   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10024   void ActOnPragmaUnused(const Token &Identifier,
10025                          Scope *curScope,
10026                          SourceLocation PragmaLoc);
10027 
10028   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10029   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10030                              SourceLocation PragmaLoc);
10031 
10032   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
10033                                  SourceLocation Loc);
10034   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
10035 
10036   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10037   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10038                          SourceLocation PragmaLoc,
10039                          SourceLocation WeakNameLoc);
10040 
10041   /// ActOnPragmaRedefineExtname - Called on well formed
10042   /// \#pragma redefine_extname oldname newname.
10043   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10044                                   IdentifierInfo* AliasName,
10045                                   SourceLocation PragmaLoc,
10046                                   SourceLocation WeakNameLoc,
10047                                   SourceLocation AliasNameLoc);
10048 
10049   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10050   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10051                             IdentifierInfo* AliasName,
10052                             SourceLocation PragmaLoc,
10053                             SourceLocation WeakNameLoc,
10054                             SourceLocation AliasNameLoc);
10055 
10056   /// ActOnPragmaFPContract - Called on well formed
10057   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10058   /// \#pragma clang fp contract
10059   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10060 
10061   /// Called on well formed
10062   /// \#pragma clang fp reassociate
10063   void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10064 
10065   /// ActOnPragmaFenvAccess - Called on well formed
10066   /// \#pragma STDC FENV_ACCESS
10067   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10068 
10069   /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10070   void ActOnPragmaFPExceptions(SourceLocation Loc,
10071                                LangOptions::FPExceptionModeKind);
10072 
10073   /// Called to set constant rounding mode for floating point operations.
10074   void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
10075 
10076   /// Called to set exception behavior for floating point operations.
10077   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10078 
10079   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10080   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10081   void AddAlignmentAttributesForRecord(RecordDecl *RD);
10082 
10083   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10084   void AddMsStructLayoutForRecord(RecordDecl *RD);
10085 
10086   /// PushNamespaceVisibilityAttr - Note that we've entered a
10087   /// namespace with a visibility attribute.
10088   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10089                                    SourceLocation Loc);
10090 
10091   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10092   /// add an appropriate visibility attribute.
10093   void AddPushedVisibilityAttribute(Decl *RD);
10094 
10095   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10096   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10097   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10098 
10099   /// FreeVisContext - Deallocate and null out VisContext.
10100   void FreeVisContext();
10101 
10102   /// AddCFAuditedAttribute - Check whether we're currently within
10103   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10104   /// the appropriate attribute.
10105   void AddCFAuditedAttribute(Decl *D);
10106 
10107   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10108                                      SourceLocation PragmaLoc,
10109                                      attr::ParsedSubjectMatchRuleSet Rules);
10110   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10111                                      const IdentifierInfo *Namespace);
10112 
10113   /// Called on well-formed '\#pragma clang attribute pop'.
10114   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10115                                const IdentifierInfo *Namespace);
10116 
10117   /// Adds the attributes that have been specified using the
10118   /// '\#pragma clang attribute push' directives to the given declaration.
10119   void AddPragmaAttributes(Scope *S, Decl *D);
10120 
10121   void DiagnoseUnterminatedPragmaAttribute();
10122 
10123   /// Called on well formed \#pragma clang optimize.
10124   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10125 
10126   /// Get the location for the currently active "\#pragma clang optimize
10127   /// off". If this location is invalid, then the state of the pragma is "on".
getOptimizeOffPragmaLocation()10128   SourceLocation getOptimizeOffPragmaLocation() const {
10129     return OptimizeOffPragmaLocation;
10130   }
10131 
10132   /// Only called on function definitions; if there is a pragma in scope
10133   /// with the effect of a range-based optnone, consider marking the function
10134   /// with attribute optnone.
10135   void AddRangeBasedOptnone(FunctionDecl *FD);
10136 
10137   /// Adds the 'optnone' attribute to the function declaration if there
10138   /// are no conflicts; Loc represents the location causing the 'optnone'
10139   /// attribute to be added (usually because of a pragma).
10140   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10141 
10142   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10143   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10144                       bool IsPackExpansion);
10145   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10146                       bool IsPackExpansion);
10147 
10148   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10149   /// declaration.
10150   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10151                             Expr *OE);
10152 
10153   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10154   /// declaration.
10155   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10156                          Expr *ParamExpr);
10157 
10158   /// AddAlignValueAttr - Adds an align_value attribute to a particular
10159   /// declaration.
10160   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10161 
10162   /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10163   void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10164                          StringRef Annot, MutableArrayRef<Expr *> Args);
10165 
10166   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10167   /// declaration.
10168   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10169                            Expr *MaxThreads, Expr *MinBlocks);
10170 
10171   /// AddModeAttr - Adds a mode attribute to a particular declaration.
10172   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10173                    bool InInstantiation = false);
10174 
10175   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10176                            ParameterABI ABI);
10177 
10178   enum class RetainOwnershipKind {NS, CF, OS};
10179   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10180                         RetainOwnershipKind K, bool IsTemplateInstantiation);
10181 
10182   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10183   /// attribute to a particular declaration.
10184   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10185                                       Expr *Min, Expr *Max);
10186 
10187   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10188   /// particular declaration.
10189   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10190                                Expr *Min, Expr *Max);
10191 
10192   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10193 
10194   //===--------------------------------------------------------------------===//
10195   // C++ Coroutines TS
10196   //
10197   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10198                                StringRef Keyword);
10199   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10200   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10201   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10202 
10203   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10204                                       bool IsImplicit = false);
10205   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10206                                         UnresolvedLookupExpr* Lookup);
10207   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10208   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10209                                bool IsImplicit = false);
10210   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10211   bool buildCoroutineParameterMoves(SourceLocation Loc);
10212   VarDecl *buildCoroutinePromise(SourceLocation Loc);
10213   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10214   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10215                                            SourceLocation FuncLoc);
10216   /// Check that the expression co_await promise.final_suspend() shall not be
10217   /// potentially-throwing.
10218   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10219 
10220   //===--------------------------------------------------------------------===//
10221   // OpenMP directives and clauses.
10222   //
10223 private:
10224   void *VarDataSharingAttributesStack;
10225 
10226   struct DeclareTargetContextInfo {
10227     struct MapInfo {
10228       OMPDeclareTargetDeclAttr::MapTypeTy MT;
10229       SourceLocation Loc;
10230     };
10231     /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10232     llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10233 
10234     /// The 'device_type' as parsed from the clause.
10235     OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10236 
10237     /// The directive kind, `begin declare target` or `declare target`.
10238     OpenMPDirectiveKind Kind;
10239 
10240     /// The directive location.
10241     SourceLocation Loc;
10242 
DeclareTargetContextInfoDeclareTargetContextInfo10243     DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
10244         : Kind(Kind), Loc(Loc) {}
10245   };
10246 
10247   /// Number of nested '#pragma omp declare target' directives.
10248   SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
10249 
10250   /// Initialization of data-sharing attributes stack.
10251   void InitDataSharingAttributesStack();
10252   void DestroyDataSharingAttributesStack();
10253   ExprResult
10254   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10255                                         bool StrictlyPositive = true,
10256                                         bool SuppressExprDiags = false);
10257   /// Returns OpenMP nesting level for current directive.
10258   unsigned getOpenMPNestingLevel() const;
10259 
10260   /// Adjusts the function scopes index for the target-based regions.
10261   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10262                                     unsigned Level) const;
10263 
10264   /// Returns the number of scopes associated with the construct on the given
10265   /// OpenMP level.
10266   int getNumberOfConstructScopes(unsigned Level) const;
10267 
10268   /// Push new OpenMP function region for non-capturing function.
10269   void pushOpenMPFunctionRegion();
10270 
10271   /// Pop OpenMP function region for non-capturing function.
10272   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10273 
10274   /// Analyzes and checks a loop nest for use by a loop transformation.
10275   ///
10276   /// \param Kind          The loop transformation directive kind.
10277   /// \param NumLoops      How many nested loops the directive is expecting.
10278   /// \param AStmt         Associated statement of the transformation directive.
10279   /// \param LoopHelpers   [out] The loop analysis result.
10280   /// \param Body          [out] The body code nested in \p NumLoops loop.
10281   /// \param OriginalInits [out] Collection of statements and declarations that
10282   ///                      must have been executed/declared before entering the
10283   ///                      loop.
10284   ///
10285   /// \return Whether there was any error.
10286   bool checkTransformableLoopNest(
10287       OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
10288       SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
10289       Stmt *&Body,
10290       SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
10291           &OriginalInits);
10292 
10293   /// Helper to keep information about the current `omp begin/end declare
10294   /// variant` nesting.
10295   struct OMPDeclareVariantScope {
10296     /// The associated OpenMP context selector.
10297     OMPTraitInfo *TI;
10298 
10299     /// The associated OpenMP context selector mangling.
10300     std::string NameSuffix;
10301 
10302     OMPDeclareVariantScope(OMPTraitInfo &TI);
10303   };
10304 
10305   /// Return the OMPTraitInfo for the surrounding scope, if any.
getOMPTraitInfoForSurroundingScope()10306   OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10307     return OMPDeclareVariantScopes.empty() ? nullptr
10308                                            : OMPDeclareVariantScopes.back().TI;
10309   }
10310 
10311   /// The current `omp begin/end declare variant` scopes.
10312   SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10313 
10314   /// The current `omp begin/end assumes` scopes.
10315   SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
10316 
10317   /// All `omp assumes` we encountered so far.
10318   SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
10319 
10320 public:
10321   /// The declarator \p D defines a function in the scope \p S which is nested
10322   /// in an `omp begin/end declare variant` scope. In this method we create a
10323   /// declaration for \p D and rename \p D according to the OpenMP context
10324   /// selector of the surrounding scope. Return all base functions in \p Bases.
10325   void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10326       Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10327       SmallVectorImpl<FunctionDecl *> &Bases);
10328 
10329   /// Register \p D as specialization of all base functions in \p Bases in the
10330   /// current `omp begin/end declare variant` scope.
10331   void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10332       Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10333 
10334   /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
10335   void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
10336 
10337   /// Can we exit an OpenMP declare variant scope at the moment.
isInOpenMPDeclareVariantScope()10338   bool isInOpenMPDeclareVariantScope() const {
10339     return !OMPDeclareVariantScopes.empty();
10340   }
10341 
10342   /// Given the potential call expression \p Call, determine if there is a
10343   /// specialization via the OpenMP declare variant mechanism available. If
10344   /// there is, return the specialized call expression, otherwise return the
10345   /// original \p Call.
10346   ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10347                              SourceLocation LParenLoc, MultiExprArg ArgExprs,
10348                              SourceLocation RParenLoc, Expr *ExecConfig);
10349 
10350   /// Handle a `omp begin declare variant`.
10351   void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10352 
10353   /// Handle a `omp end declare variant`.
10354   void ActOnOpenMPEndDeclareVariant();
10355 
10356   /// Checks if the variant/multiversion functions are compatible.
10357   bool areMultiversionVariantFunctionsCompatible(
10358       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10359       const PartialDiagnostic &NoProtoDiagID,
10360       const PartialDiagnosticAt &NoteCausedDiagIDAt,
10361       const PartialDiagnosticAt &NoSupportDiagIDAt,
10362       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10363       bool ConstexprSupported, bool CLinkageMayDiffer);
10364 
10365   /// Function tries to capture lambda's captured variables in the OpenMP region
10366   /// before the original lambda is captured.
10367   void tryCaptureOpenMPLambdas(ValueDecl *V);
10368 
10369   /// Return true if the provided declaration \a VD should be captured by
10370   /// reference.
10371   /// \param Level Relative level of nested OpenMP construct for that the check
10372   /// is performed.
10373   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10374   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10375                              unsigned OpenMPCaptureLevel) const;
10376 
10377   /// Check if the specified variable is used in one of the private
10378   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10379   /// constructs.
10380   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10381                                 unsigned StopAt = 0);
10382   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10383                                    ExprObjectKind OK, SourceLocation Loc);
10384 
10385   /// If the current region is a loop-based region, mark the start of the loop
10386   /// construct.
10387   void startOpenMPLoop();
10388 
10389   /// If the current region is a range loop-based region, mark the start of the
10390   /// loop construct.
10391   void startOpenMPCXXRangeFor();
10392 
10393   /// Check if the specified variable is used in 'private' clause.
10394   /// \param Level Relative level of nested OpenMP construct for that the check
10395   /// is performed.
10396   OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10397                                        unsigned CapLevel) const;
10398 
10399   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10400   /// for \p FD based on DSA for the provided corresponding captured declaration
10401   /// \p D.
10402   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10403 
10404   /// Check if the specified variable is captured  by 'target' directive.
10405   /// \param Level Relative level of nested OpenMP construct for that the check
10406   /// is performed.
10407   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10408                                   unsigned CaptureLevel) const;
10409 
10410   /// Check if the specified global variable must be captured  by outer capture
10411   /// regions.
10412   /// \param Level Relative level of nested OpenMP construct for that
10413   /// the check is performed.
10414   bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10415                                   unsigned CaptureLevel) const;
10416 
10417   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10418                                                     Expr *Op);
10419   /// Called on start of new data sharing attribute block.
10420   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10421                            const DeclarationNameInfo &DirName, Scope *CurScope,
10422                            SourceLocation Loc);
10423   /// Start analysis of clauses.
10424   void StartOpenMPClause(OpenMPClauseKind K);
10425   /// End analysis of clauses.
10426   void EndOpenMPClause();
10427   /// Called on end of data sharing attribute block.
10428   void EndOpenMPDSABlock(Stmt *CurDirective);
10429 
10430   /// Check if the current region is an OpenMP loop region and if it is,
10431   /// mark loop control variable, used in \p Init for loop initialization, as
10432   /// private by default.
10433   /// \param Init First part of the for loop.
10434   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10435 
10436   // OpenMP directives and clauses.
10437   /// Called on correct id-expression from the '#pragma omp
10438   /// threadprivate'.
10439   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10440                                      const DeclarationNameInfo &Id,
10441                                      OpenMPDirectiveKind Kind);
10442   /// Called on well-formed '#pragma omp threadprivate'.
10443   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10444                                      SourceLocation Loc,
10445                                      ArrayRef<Expr *> VarList);
10446   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10447   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10448                                                   ArrayRef<Expr *> VarList);
10449   /// Called on well-formed '#pragma omp allocate'.
10450   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10451                                               ArrayRef<Expr *> VarList,
10452                                               ArrayRef<OMPClause *> Clauses,
10453                                               DeclContext *Owner = nullptr);
10454 
10455   /// Called on well-formed '#pragma omp [begin] assume[s]'.
10456   void ActOnOpenMPAssumesDirective(SourceLocation Loc,
10457                                    OpenMPDirectiveKind DKind,
10458                                    ArrayRef<StringRef> Assumptions,
10459                                    bool SkippedClauses);
10460 
10461   /// Check if there is an active global `omp begin assumes` directive.
isInOpenMPAssumeScope()10462   bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
10463 
10464   /// Check if there is an active global `omp assumes` directive.
hasGlobalOpenMPAssumes()10465   bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
10466 
10467   /// Called on well-formed '#pragma omp end assumes'.
10468   void ActOnOpenMPEndAssumesDirective();
10469 
10470   /// Called on well-formed '#pragma omp requires'.
10471   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10472                                               ArrayRef<OMPClause *> ClauseList);
10473   /// Check restrictions on Requires directive
10474   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10475                                         ArrayRef<OMPClause *> Clauses);
10476   /// Check if the specified type is allowed to be used in 'omp declare
10477   /// reduction' construct.
10478   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10479                                            TypeResult ParsedType);
10480   /// Called on start of '#pragma omp declare reduction'.
10481   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10482       Scope *S, DeclContext *DC, DeclarationName Name,
10483       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10484       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10485   /// Initialize declare reduction construct initializer.
10486   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10487   /// Finish current declare reduction construct initializer.
10488   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10489   /// Initialize declare reduction construct initializer.
10490   /// \return omp_priv variable.
10491   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10492   /// Finish current declare reduction construct initializer.
10493   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10494                                                  VarDecl *OmpPrivParm);
10495   /// Called at the end of '#pragma omp declare reduction'.
10496   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10497       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10498 
10499   /// Check variable declaration in 'omp declare mapper' construct.
10500   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10501   /// Check if the specified type is allowed to be used in 'omp declare
10502   /// mapper' construct.
10503   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10504                                         TypeResult ParsedType);
10505   /// Called on start of '#pragma omp declare mapper'.
10506   DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10507       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10508       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10509       Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10510       Decl *PrevDeclInScope = nullptr);
10511   /// Build the mapper variable of '#pragma omp declare mapper'.
10512   ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10513                                                       QualType MapperType,
10514                                                       SourceLocation StartLoc,
10515                                                       DeclarationName VN);
10516   bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10517   const ValueDecl *getOpenMPDeclareMapperVarName() const;
10518 
10519   /// Called on the start of target region i.e. '#pragma omp declare target'.
10520   bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10521 
10522   /// Called at the end of target region i.e. '#pragma omp end declare target'.
10523   const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
10524 
10525   /// Called once a target context is completed, that can be when a
10526   /// '#pragma omp end declare target' was encountered or when a
10527   /// '#pragma omp declare target' without declaration-definition-seq was
10528   /// encountered.
10529   void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10530 
10531   /// Searches for the provided declaration name for OpenMP declare target
10532   /// directive.
10533   NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
10534                                            CXXScopeSpec &ScopeSpec,
10535                                            const DeclarationNameInfo &Id);
10536 
10537   /// Called on correct id-expression from the '#pragma omp declare target'.
10538   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10539                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
10540                                     OMPDeclareTargetDeclAttr::DevTypeTy DT);
10541 
10542   /// Check declaration inside target region.
10543   void
10544   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10545                                    SourceLocation IdLoc = SourceLocation());
10546   /// Finishes analysis of the deferred functions calls that may be declared as
10547   /// host/nohost during device/host compilation.
10548   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10549                                      const FunctionDecl *Callee,
10550                                      SourceLocation Loc);
10551   /// Return true inside OpenMP declare target region.
isInOpenMPDeclareTargetContext()10552   bool isInOpenMPDeclareTargetContext() const {
10553     return !DeclareTargetNesting.empty();
10554   }
10555   /// Return true inside OpenMP target region.
10556   bool isInOpenMPTargetExecutionDirective() const;
10557 
10558   /// Return the number of captured regions created for an OpenMP directive.
10559   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10560 
10561   /// Initialization of captured region for OpenMP region.
10562   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10563 
10564   /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
10565   /// an OpenMP loop directive.
10566   StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
10567 
10568   /// End of OpenMP region.
10569   ///
10570   /// \param S Statement associated with the current OpenMP region.
10571   /// \param Clauses List of clauses for the current OpenMP region.
10572   ///
10573   /// \returns Statement for finished OpenMP region.
10574   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10575   StmtResult ActOnOpenMPExecutableDirective(
10576       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10577       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10578       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10579   /// Called on well-formed '\#pragma omp parallel' after parsing
10580   /// of the  associated statement.
10581   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10582                                           Stmt *AStmt,
10583                                           SourceLocation StartLoc,
10584                                           SourceLocation EndLoc);
10585   using VarsWithInheritedDSAType =
10586       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10587   /// Called on well-formed '\#pragma omp simd' after parsing
10588   /// of the associated statement.
10589   StmtResult
10590   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10591                            SourceLocation StartLoc, SourceLocation EndLoc,
10592                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
10593   /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
10594   /// the associated statement.
10595   StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
10596                                       Stmt *AStmt, SourceLocation StartLoc,
10597                                       SourceLocation EndLoc);
10598   /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
10599   /// and the associated statement.
10600   StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
10601                                         Stmt *AStmt, SourceLocation StartLoc,
10602                                         SourceLocation EndLoc);
10603   /// Called on well-formed '\#pragma omp for' after parsing
10604   /// of the associated statement.
10605   StmtResult
10606   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10607                           SourceLocation StartLoc, SourceLocation EndLoc,
10608                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
10609   /// Called on well-formed '\#pragma omp for simd' after parsing
10610   /// of the associated statement.
10611   StmtResult
10612   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10613                               SourceLocation StartLoc, SourceLocation EndLoc,
10614                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
10615   /// Called on well-formed '\#pragma omp sections' after parsing
10616   /// of the associated statement.
10617   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10618                                           Stmt *AStmt, SourceLocation StartLoc,
10619                                           SourceLocation EndLoc);
10620   /// Called on well-formed '\#pragma omp section' after parsing of the
10621   /// associated statement.
10622   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10623                                          SourceLocation EndLoc);
10624   /// Called on well-formed '\#pragma omp single' after parsing of the
10625   /// associated statement.
10626   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10627                                         Stmt *AStmt, SourceLocation StartLoc,
10628                                         SourceLocation EndLoc);
10629   /// Called on well-formed '\#pragma omp master' after parsing of the
10630   /// associated statement.
10631   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10632                                         SourceLocation EndLoc);
10633   /// Called on well-formed '\#pragma omp critical' after parsing of the
10634   /// associated statement.
10635   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10636                                           ArrayRef<OMPClause *> Clauses,
10637                                           Stmt *AStmt, SourceLocation StartLoc,
10638                                           SourceLocation EndLoc);
10639   /// Called on well-formed '\#pragma omp parallel for' after parsing
10640   /// of the  associated statement.
10641   StmtResult ActOnOpenMPParallelForDirective(
10642       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10643       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10644   /// Called on well-formed '\#pragma omp parallel for simd' after
10645   /// parsing of the  associated statement.
10646   StmtResult ActOnOpenMPParallelForSimdDirective(
10647       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10648       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10649   /// Called on well-formed '\#pragma omp parallel master' after
10650   /// parsing of the  associated statement.
10651   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10652                                                 Stmt *AStmt,
10653                                                 SourceLocation StartLoc,
10654                                                 SourceLocation EndLoc);
10655   /// Called on well-formed '\#pragma omp parallel sections' after
10656   /// parsing of the  associated statement.
10657   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10658                                                   Stmt *AStmt,
10659                                                   SourceLocation StartLoc,
10660                                                   SourceLocation EndLoc);
10661   /// Called on well-formed '\#pragma omp task' after parsing of the
10662   /// associated statement.
10663   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10664                                       Stmt *AStmt, SourceLocation StartLoc,
10665                                       SourceLocation EndLoc);
10666   /// Called on well-formed '\#pragma omp taskyield'.
10667   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10668                                            SourceLocation EndLoc);
10669   /// Called on well-formed '\#pragma omp barrier'.
10670   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10671                                          SourceLocation EndLoc);
10672   /// Called on well-formed '\#pragma omp taskwait'.
10673   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10674                                           SourceLocation EndLoc);
10675   /// Called on well-formed '\#pragma omp taskgroup'.
10676   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10677                                            Stmt *AStmt, SourceLocation StartLoc,
10678                                            SourceLocation EndLoc);
10679   /// Called on well-formed '\#pragma omp flush'.
10680   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10681                                        SourceLocation StartLoc,
10682                                        SourceLocation EndLoc);
10683   /// Called on well-formed '\#pragma omp depobj'.
10684   StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10685                                         SourceLocation StartLoc,
10686                                         SourceLocation EndLoc);
10687   /// Called on well-formed '\#pragma omp scan'.
10688   StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10689                                       SourceLocation StartLoc,
10690                                       SourceLocation EndLoc);
10691   /// Called on well-formed '\#pragma omp ordered' after parsing of the
10692   /// associated statement.
10693   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10694                                          Stmt *AStmt, SourceLocation StartLoc,
10695                                          SourceLocation EndLoc);
10696   /// Called on well-formed '\#pragma omp atomic' after parsing of the
10697   /// associated statement.
10698   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10699                                         Stmt *AStmt, SourceLocation StartLoc,
10700                                         SourceLocation EndLoc);
10701   /// Called on well-formed '\#pragma omp target' after parsing of the
10702   /// associated statement.
10703   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10704                                         Stmt *AStmt, SourceLocation StartLoc,
10705                                         SourceLocation EndLoc);
10706   /// Called on well-formed '\#pragma omp target data' after parsing of
10707   /// the associated statement.
10708   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10709                                             Stmt *AStmt, SourceLocation StartLoc,
10710                                             SourceLocation EndLoc);
10711   /// Called on well-formed '\#pragma omp target enter data' after
10712   /// parsing of the associated statement.
10713   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10714                                                  SourceLocation StartLoc,
10715                                                  SourceLocation EndLoc,
10716                                                  Stmt *AStmt);
10717   /// Called on well-formed '\#pragma omp target exit data' after
10718   /// parsing of the associated statement.
10719   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10720                                                 SourceLocation StartLoc,
10721                                                 SourceLocation EndLoc,
10722                                                 Stmt *AStmt);
10723   /// Called on well-formed '\#pragma omp target parallel' after
10724   /// parsing of the associated statement.
10725   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10726                                                 Stmt *AStmt,
10727                                                 SourceLocation StartLoc,
10728                                                 SourceLocation EndLoc);
10729   /// Called on well-formed '\#pragma omp target parallel for' after
10730   /// parsing of the  associated statement.
10731   StmtResult ActOnOpenMPTargetParallelForDirective(
10732       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10733       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10734   /// Called on well-formed '\#pragma omp teams' after parsing of the
10735   /// associated statement.
10736   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10737                                        Stmt *AStmt, SourceLocation StartLoc,
10738                                        SourceLocation EndLoc);
10739   /// Called on well-formed '\#pragma omp cancellation point'.
10740   StmtResult
10741   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10742                                         SourceLocation EndLoc,
10743                                         OpenMPDirectiveKind CancelRegion);
10744   /// Called on well-formed '\#pragma omp cancel'.
10745   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10746                                         SourceLocation StartLoc,
10747                                         SourceLocation EndLoc,
10748                                         OpenMPDirectiveKind CancelRegion);
10749   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10750   /// associated statement.
10751   StmtResult
10752   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10753                                SourceLocation StartLoc, SourceLocation EndLoc,
10754                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
10755   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10756   /// the associated statement.
10757   StmtResult ActOnOpenMPTaskLoopSimdDirective(
10758       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10759       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10760   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10761   /// associated statement.
10762   StmtResult ActOnOpenMPMasterTaskLoopDirective(
10763       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10764       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10765   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10766   /// the associated statement.
10767   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10768       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10769       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10770   /// Called on well-formed '\#pragma omp parallel master taskloop' after
10771   /// parsing of the associated statement.
10772   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10773       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10774       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10775   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10776   /// parsing of the associated statement.
10777   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10778       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10779       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10780   /// Called on well-formed '\#pragma omp distribute' after parsing
10781   /// of the associated statement.
10782   StmtResult
10783   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10784                                  SourceLocation StartLoc, SourceLocation EndLoc,
10785                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10786   /// Called on well-formed '\#pragma omp target update'.
10787   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10788                                               SourceLocation StartLoc,
10789                                               SourceLocation EndLoc,
10790                                               Stmt *AStmt);
10791   /// Called on well-formed '\#pragma omp distribute parallel for' after
10792   /// parsing of the associated statement.
10793   StmtResult ActOnOpenMPDistributeParallelForDirective(
10794       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10795       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10796   /// Called on well-formed '\#pragma omp distribute parallel for simd'
10797   /// after parsing of the associated statement.
10798   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10799       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10800       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10801   /// Called on well-formed '\#pragma omp distribute simd' after
10802   /// parsing of the associated statement.
10803   StmtResult ActOnOpenMPDistributeSimdDirective(
10804       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10805       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10806   /// Called on well-formed '\#pragma omp target parallel for simd' after
10807   /// parsing of the associated statement.
10808   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10809       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10810       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10811   /// Called on well-formed '\#pragma omp target simd' after parsing of
10812   /// the associated statement.
10813   StmtResult
10814   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10815                                  SourceLocation StartLoc, SourceLocation EndLoc,
10816                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10817   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10818   /// the associated statement.
10819   StmtResult ActOnOpenMPTeamsDistributeDirective(
10820       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10821       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10822   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10823   /// of the associated statement.
10824   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10825       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10826       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10827   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10828   /// after parsing of the associated statement.
10829   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10830       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10831       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10832   /// Called on well-formed '\#pragma omp teams distribute parallel for'
10833   /// after parsing of the associated statement.
10834   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10835       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10836       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10837   /// Called on well-formed '\#pragma omp target teams' after parsing of the
10838   /// associated statement.
10839   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10840                                              Stmt *AStmt,
10841                                              SourceLocation StartLoc,
10842                                              SourceLocation EndLoc);
10843   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10844   /// of the associated statement.
10845   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10846       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10847       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10848   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10849   /// after parsing of the associated statement.
10850   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10851       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10852       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10853   /// Called on well-formed '\#pragma omp target teams distribute parallel for
10854   /// simd' after parsing of the associated statement.
10855   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10856       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10857       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10858   /// Called on well-formed '\#pragma omp target teams distribute simd' after
10859   /// parsing of the associated statement.
10860   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10861       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10862       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10863   /// Called on well-formed '\#pragma omp interop'.
10864   StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
10865                                          SourceLocation StartLoc,
10866                                          SourceLocation EndLoc);
10867   /// Called on well-formed '\#pragma omp dispatch' after parsing of the
10868   // /associated statement.
10869   StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
10870                                           Stmt *AStmt, SourceLocation StartLoc,
10871                                           SourceLocation EndLoc);
10872   /// Called on well-formed '\#pragma omp masked' after parsing of the
10873   // /associated statement.
10874   StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
10875                                         Stmt *AStmt, SourceLocation StartLoc,
10876                                         SourceLocation EndLoc);
10877 
10878   /// Checks correctness of linear modifiers.
10879   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10880                                  SourceLocation LinLoc);
10881   /// Checks that the specified declaration matches requirements for the linear
10882   /// decls.
10883   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10884                              OpenMPLinearClauseKind LinKind, QualType Type,
10885                              bool IsDeclareSimd = false);
10886 
10887   /// Called on well-formed '\#pragma omp declare simd' after parsing of
10888   /// the associated method/function.
10889   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10890       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10891       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10892       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10893       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10894 
10895   /// Checks '\#pragma omp declare variant' variant function and original
10896   /// functions after parsing of the associated method/function.
10897   /// \param DG Function declaration to which declare variant directive is
10898   /// applied to.
10899   /// \param VariantRef Expression that references the variant function, which
10900   /// must be used instead of the original one, specified in \p DG.
10901   /// \param TI The trait info object representing the match clause.
10902   /// \returns None, if the function/variant function are not compatible with
10903   /// the pragma, pair of original function/variant ref expression otherwise.
10904   Optional<std::pair<FunctionDecl *, Expr *>>
10905   checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
10906                                     OMPTraitInfo &TI, SourceRange SR);
10907 
10908   /// Called on well-formed '\#pragma omp declare variant' after parsing of
10909   /// the associated method/function.
10910   /// \param FD Function declaration to which declare variant directive is
10911   /// applied to.
10912   /// \param VariantRef Expression that references the variant function, which
10913   /// must be used instead of the original one, specified in \p DG.
10914   /// \param TI The context traits associated with the function variant.
10915   void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10916                                           OMPTraitInfo &TI, SourceRange SR);
10917 
10918   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10919                                          Expr *Expr,
10920                                          SourceLocation StartLoc,
10921                                          SourceLocation LParenLoc,
10922                                          SourceLocation EndLoc);
10923   /// Called on well-formed 'allocator' clause.
10924   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10925                                         SourceLocation StartLoc,
10926                                         SourceLocation LParenLoc,
10927                                         SourceLocation EndLoc);
10928   /// Called on well-formed 'if' clause.
10929   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10930                                  Expr *Condition, SourceLocation StartLoc,
10931                                  SourceLocation LParenLoc,
10932                                  SourceLocation NameModifierLoc,
10933                                  SourceLocation ColonLoc,
10934                                  SourceLocation EndLoc);
10935   /// Called on well-formed 'final' clause.
10936   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10937                                     SourceLocation LParenLoc,
10938                                     SourceLocation EndLoc);
10939   /// Called on well-formed 'num_threads' clause.
10940   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10941                                          SourceLocation StartLoc,
10942                                          SourceLocation LParenLoc,
10943                                          SourceLocation EndLoc);
10944   /// Called on well-formed 'safelen' clause.
10945   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10946                                       SourceLocation StartLoc,
10947                                       SourceLocation LParenLoc,
10948                                       SourceLocation EndLoc);
10949   /// Called on well-formed 'simdlen' clause.
10950   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10951                                       SourceLocation LParenLoc,
10952                                       SourceLocation EndLoc);
10953   /// Called on well-form 'sizes' clause.
10954   OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
10955                                     SourceLocation StartLoc,
10956                                     SourceLocation LParenLoc,
10957                                     SourceLocation EndLoc);
10958   /// Called on well-form 'full' clauses.
10959   OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
10960                                    SourceLocation EndLoc);
10961   /// Called on well-form 'partial' clauses.
10962   OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
10963                                       SourceLocation LParenLoc,
10964                                       SourceLocation EndLoc);
10965   /// Called on well-formed 'collapse' clause.
10966   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10967                                        SourceLocation StartLoc,
10968                                        SourceLocation LParenLoc,
10969                                        SourceLocation EndLoc);
10970   /// Called on well-formed 'ordered' clause.
10971   OMPClause *
10972   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10973                            SourceLocation LParenLoc = SourceLocation(),
10974                            Expr *NumForLoops = nullptr);
10975   /// Called on well-formed 'grainsize' clause.
10976   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10977                                         SourceLocation LParenLoc,
10978                                         SourceLocation EndLoc);
10979   /// Called on well-formed 'num_tasks' clause.
10980   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10981                                        SourceLocation LParenLoc,
10982                                        SourceLocation EndLoc);
10983   /// Called on well-formed 'hint' clause.
10984   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10985                                    SourceLocation LParenLoc,
10986                                    SourceLocation EndLoc);
10987   /// Called on well-formed 'detach' clause.
10988   OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
10989                                      SourceLocation LParenLoc,
10990                                      SourceLocation EndLoc);
10991 
10992   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10993                                      unsigned Argument,
10994                                      SourceLocation ArgumentLoc,
10995                                      SourceLocation StartLoc,
10996                                      SourceLocation LParenLoc,
10997                                      SourceLocation EndLoc);
10998   /// Called on well-formed 'default' clause.
10999   OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11000                                       SourceLocation KindLoc,
11001                                       SourceLocation StartLoc,
11002                                       SourceLocation LParenLoc,
11003                                       SourceLocation EndLoc);
11004   /// Called on well-formed 'proc_bind' clause.
11005   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11006                                        SourceLocation KindLoc,
11007                                        SourceLocation StartLoc,
11008                                        SourceLocation LParenLoc,
11009                                        SourceLocation EndLoc);
11010   /// Called on well-formed 'order' clause.
11011   OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
11012                                     SourceLocation KindLoc,
11013                                     SourceLocation StartLoc,
11014                                     SourceLocation LParenLoc,
11015                                     SourceLocation EndLoc);
11016   /// Called on well-formed 'update' clause.
11017   OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11018                                      SourceLocation KindLoc,
11019                                      SourceLocation StartLoc,
11020                                      SourceLocation LParenLoc,
11021                                      SourceLocation EndLoc);
11022 
11023   OMPClause *ActOnOpenMPSingleExprWithArgClause(
11024       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11025       SourceLocation StartLoc, SourceLocation LParenLoc,
11026       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11027       SourceLocation EndLoc);
11028   /// Called on well-formed 'schedule' clause.
11029   OMPClause *ActOnOpenMPScheduleClause(
11030       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11031       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11032       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11033       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11034 
11035   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11036                                SourceLocation EndLoc);
11037   /// Called on well-formed 'nowait' clause.
11038   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11039                                      SourceLocation EndLoc);
11040   /// Called on well-formed 'untied' clause.
11041   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11042                                      SourceLocation EndLoc);
11043   /// Called on well-formed 'mergeable' clause.
11044   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11045                                         SourceLocation EndLoc);
11046   /// Called on well-formed 'read' clause.
11047   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11048                                    SourceLocation EndLoc);
11049   /// Called on well-formed 'write' clause.
11050   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11051                                     SourceLocation EndLoc);
11052   /// Called on well-formed 'update' clause.
11053   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11054                                      SourceLocation EndLoc);
11055   /// Called on well-formed 'capture' clause.
11056   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11057                                       SourceLocation EndLoc);
11058   /// Called on well-formed 'seq_cst' clause.
11059   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11060                                      SourceLocation EndLoc);
11061   /// Called on well-formed 'acq_rel' clause.
11062   OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
11063                                      SourceLocation EndLoc);
11064   /// Called on well-formed 'acquire' clause.
11065   OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
11066                                       SourceLocation EndLoc);
11067   /// Called on well-formed 'release' clause.
11068   OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
11069                                       SourceLocation EndLoc);
11070   /// Called on well-formed 'relaxed' clause.
11071   OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
11072                                       SourceLocation EndLoc);
11073 
11074   /// Called on well-formed 'init' clause.
11075   OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
11076                                    bool IsTarget, bool IsTargetSync,
11077                                    SourceLocation StartLoc,
11078                                    SourceLocation LParenLoc,
11079                                    SourceLocation VarLoc,
11080                                    SourceLocation EndLoc);
11081 
11082   /// Called on well-formed 'use' clause.
11083   OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
11084                                   SourceLocation LParenLoc,
11085                                   SourceLocation VarLoc, SourceLocation EndLoc);
11086 
11087   /// Called on well-formed 'destroy' clause.
11088   OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
11089                                       SourceLocation LParenLoc,
11090                                       SourceLocation VarLoc,
11091                                       SourceLocation EndLoc);
11092   /// Called on well-formed 'novariants' clause.
11093   OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
11094                                          SourceLocation StartLoc,
11095                                          SourceLocation LParenLoc,
11096                                          SourceLocation EndLoc);
11097   /// Called on well-formed 'nocontext' clause.
11098   OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
11099                                         SourceLocation StartLoc,
11100                                         SourceLocation LParenLoc,
11101                                         SourceLocation EndLoc);
11102   /// Called on well-formed 'filter' clause.
11103   OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
11104                                      SourceLocation LParenLoc,
11105                                      SourceLocation EndLoc);
11106   /// Called on well-formed 'threads' clause.
11107   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11108                                       SourceLocation EndLoc);
11109   /// Called on well-formed 'simd' clause.
11110   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11111                                    SourceLocation EndLoc);
11112   /// Called on well-formed 'nogroup' clause.
11113   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11114                                       SourceLocation EndLoc);
11115   /// Called on well-formed 'unified_address' clause.
11116   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11117                                              SourceLocation EndLoc);
11118 
11119   /// Called on well-formed 'unified_address' clause.
11120   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11121                                                   SourceLocation EndLoc);
11122 
11123   /// Called on well-formed 'reverse_offload' clause.
11124   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11125                                              SourceLocation EndLoc);
11126 
11127   /// Called on well-formed 'dynamic_allocators' clause.
11128   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11129                                                 SourceLocation EndLoc);
11130 
11131   /// Called on well-formed 'atomic_default_mem_order' clause.
11132   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
11133       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
11134       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11135 
11136   OMPClause *ActOnOpenMPVarListClause(
11137       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
11138       const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11139       CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11140       DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
11141       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11142       ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
11143       SourceLocation ExtraModifierLoc,
11144       ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11145       ArrayRef<SourceLocation> MotionModifiersLoc);
11146   /// Called on well-formed 'inclusive' clause.
11147   OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
11148                                         SourceLocation StartLoc,
11149                                         SourceLocation LParenLoc,
11150                                         SourceLocation EndLoc);
11151   /// Called on well-formed 'exclusive' clause.
11152   OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
11153                                         SourceLocation StartLoc,
11154                                         SourceLocation LParenLoc,
11155                                         SourceLocation EndLoc);
11156   /// Called on well-formed 'allocate' clause.
11157   OMPClause *
11158   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
11159                             SourceLocation StartLoc, SourceLocation ColonLoc,
11160                             SourceLocation LParenLoc, SourceLocation EndLoc);
11161   /// Called on well-formed 'private' clause.
11162   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11163                                       SourceLocation StartLoc,
11164                                       SourceLocation LParenLoc,
11165                                       SourceLocation EndLoc);
11166   /// Called on well-formed 'firstprivate' clause.
11167   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11168                                            SourceLocation StartLoc,
11169                                            SourceLocation LParenLoc,
11170                                            SourceLocation EndLoc);
11171   /// Called on well-formed 'lastprivate' clause.
11172   OMPClause *ActOnOpenMPLastprivateClause(
11173       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
11174       SourceLocation LPKindLoc, SourceLocation ColonLoc,
11175       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11176   /// Called on well-formed 'shared' clause.
11177   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11178                                      SourceLocation StartLoc,
11179                                      SourceLocation LParenLoc,
11180                                      SourceLocation EndLoc);
11181   /// Called on well-formed 'reduction' clause.
11182   OMPClause *ActOnOpenMPReductionClause(
11183       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
11184       SourceLocation StartLoc, SourceLocation LParenLoc,
11185       SourceLocation ModifierLoc, SourceLocation ColonLoc,
11186       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
11187       const DeclarationNameInfo &ReductionId,
11188       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11189   /// Called on well-formed 'task_reduction' clause.
11190   OMPClause *ActOnOpenMPTaskReductionClause(
11191       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11192       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11193       CXXScopeSpec &ReductionIdScopeSpec,
11194       const DeclarationNameInfo &ReductionId,
11195       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11196   /// Called on well-formed 'in_reduction' clause.
11197   OMPClause *ActOnOpenMPInReductionClause(
11198       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11199       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11200       CXXScopeSpec &ReductionIdScopeSpec,
11201       const DeclarationNameInfo &ReductionId,
11202       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11203   /// Called on well-formed 'linear' clause.
11204   OMPClause *
11205   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
11206                           SourceLocation StartLoc, SourceLocation LParenLoc,
11207                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
11208                           SourceLocation ColonLoc, SourceLocation EndLoc);
11209   /// Called on well-formed 'aligned' clause.
11210   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
11211                                       Expr *Alignment,
11212                                       SourceLocation StartLoc,
11213                                       SourceLocation LParenLoc,
11214                                       SourceLocation ColonLoc,
11215                                       SourceLocation EndLoc);
11216   /// Called on well-formed 'copyin' clause.
11217   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11218                                      SourceLocation StartLoc,
11219                                      SourceLocation LParenLoc,
11220                                      SourceLocation EndLoc);
11221   /// Called on well-formed 'copyprivate' clause.
11222   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11223                                           SourceLocation StartLoc,
11224                                           SourceLocation LParenLoc,
11225                                           SourceLocation EndLoc);
11226   /// Called on well-formed 'flush' pseudo clause.
11227   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11228                                     SourceLocation StartLoc,
11229                                     SourceLocation LParenLoc,
11230                                     SourceLocation EndLoc);
11231   /// Called on well-formed 'depobj' pseudo clause.
11232   OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11233                                      SourceLocation LParenLoc,
11234                                      SourceLocation EndLoc);
11235   /// Called on well-formed 'depend' clause.
11236   OMPClause *
11237   ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
11238                           SourceLocation DepLoc, SourceLocation ColonLoc,
11239                           ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11240                           SourceLocation LParenLoc, SourceLocation EndLoc);
11241   /// Called on well-formed 'device' clause.
11242   OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11243                                      Expr *Device, SourceLocation StartLoc,
11244                                      SourceLocation LParenLoc,
11245                                      SourceLocation ModifierLoc,
11246                                      SourceLocation EndLoc);
11247   /// Called on well-formed 'map' clause.
11248   OMPClause *
11249   ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11250                        ArrayRef<SourceLocation> MapTypeModifiersLoc,
11251                        CXXScopeSpec &MapperIdScopeSpec,
11252                        DeclarationNameInfo &MapperId,
11253                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11254                        SourceLocation MapLoc, SourceLocation ColonLoc,
11255                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11256                        ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11257   /// Called on well-formed 'num_teams' clause.
11258   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11259                                        SourceLocation LParenLoc,
11260                                        SourceLocation EndLoc);
11261   /// Called on well-formed 'thread_limit' clause.
11262   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11263                                           SourceLocation StartLoc,
11264                                           SourceLocation LParenLoc,
11265                                           SourceLocation EndLoc);
11266   /// Called on well-formed 'priority' clause.
11267   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11268                                        SourceLocation LParenLoc,
11269                                        SourceLocation EndLoc);
11270   /// Called on well-formed 'dist_schedule' clause.
11271   OMPClause *ActOnOpenMPDistScheduleClause(
11272       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11273       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11274       SourceLocation CommaLoc, SourceLocation EndLoc);
11275   /// Called on well-formed 'defaultmap' clause.
11276   OMPClause *ActOnOpenMPDefaultmapClause(
11277       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11278       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11279       SourceLocation KindLoc, SourceLocation EndLoc);
11280   /// Called on well-formed 'to' clause.
11281   OMPClause *
11282   ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11283                       ArrayRef<SourceLocation> MotionModifiersLoc,
11284                       CXXScopeSpec &MapperIdScopeSpec,
11285                       DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11286                       ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11287                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11288   /// Called on well-formed 'from' clause.
11289   OMPClause *
11290   ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11291                         ArrayRef<SourceLocation> MotionModifiersLoc,
11292                         CXXScopeSpec &MapperIdScopeSpec,
11293                         DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11294                         ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11295                         ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11296   /// Called on well-formed 'use_device_ptr' clause.
11297   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11298                                            const OMPVarListLocTy &Locs);
11299   /// Called on well-formed 'use_device_addr' clause.
11300   OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11301                                             const OMPVarListLocTy &Locs);
11302   /// Called on well-formed 'is_device_ptr' clause.
11303   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11304                                           const OMPVarListLocTy &Locs);
11305   /// Called on well-formed 'nontemporal' clause.
11306   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11307                                           SourceLocation StartLoc,
11308                                           SourceLocation LParenLoc,
11309                                           SourceLocation EndLoc);
11310 
11311   /// Data for list of allocators.
11312   struct UsesAllocatorsData {
11313     /// Allocator.
11314     Expr *Allocator = nullptr;
11315     /// Allocator traits.
11316     Expr *AllocatorTraits = nullptr;
11317     /// Locations of '(' and ')' symbols.
11318     SourceLocation LParenLoc, RParenLoc;
11319   };
11320   /// Called on well-formed 'uses_allocators' clause.
11321   OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11322                                             SourceLocation LParenLoc,
11323                                             SourceLocation EndLoc,
11324                                             ArrayRef<UsesAllocatorsData> Data);
11325   /// Called on well-formed 'affinity' clause.
11326   OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11327                                        SourceLocation LParenLoc,
11328                                        SourceLocation ColonLoc,
11329                                        SourceLocation EndLoc, Expr *Modifier,
11330                                        ArrayRef<Expr *> Locators);
11331 
11332   /// The kind of conversion being performed.
11333   enum CheckedConversionKind {
11334     /// An implicit conversion.
11335     CCK_ImplicitConversion,
11336     /// A C-style cast.
11337     CCK_CStyleCast,
11338     /// A functional-style cast.
11339     CCK_FunctionalCast,
11340     /// A cast other than a C-style cast.
11341     CCK_OtherCast,
11342     /// A conversion for an operand of a builtin overloaded operator.
11343     CCK_ForBuiltinOverloadedOp
11344   };
11345 
isCast(CheckedConversionKind CCK)11346   static bool isCast(CheckedConversionKind CCK) {
11347     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11348            CCK == CCK_OtherCast;
11349   }
11350 
11351   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11352   /// cast.  If there is already an implicit cast, merge into the existing one.
11353   /// If isLvalue, the result of the cast is an lvalue.
11354   ExprResult
11355   ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11356                     ExprValueKind VK = VK_PRValue,
11357                     const CXXCastPath *BasePath = nullptr,
11358                     CheckedConversionKind CCK = CCK_ImplicitConversion);
11359 
11360   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11361   /// to the conversion from scalar type ScalarTy to the Boolean type.
11362   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11363 
11364   /// IgnoredValueConversions - Given that an expression's result is
11365   /// syntactically ignored, perform any conversions that are
11366   /// required.
11367   ExprResult IgnoredValueConversions(Expr *E);
11368 
11369   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11370   // functions and arrays to their respective pointers (C99 6.3.2.1).
11371   ExprResult UsualUnaryConversions(Expr *E);
11372 
11373   /// CallExprUnaryConversions - a special case of an unary conversion
11374   /// performed on a function designator of a call expression.
11375   ExprResult CallExprUnaryConversions(Expr *E);
11376 
11377   // DefaultFunctionArrayConversion - converts functions and arrays
11378   // to their respective pointers (C99 6.3.2.1).
11379   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11380 
11381   // DefaultFunctionArrayLvalueConversion - converts functions and
11382   // arrays to their respective pointers and performs the
11383   // lvalue-to-rvalue conversion.
11384   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11385                                                   bool Diagnose = true);
11386 
11387   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11388   // the operand. This function is a no-op if the operand has a function type
11389   // or an array type.
11390   ExprResult DefaultLvalueConversion(Expr *E);
11391 
11392   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11393   // do not have a prototype. Integer promotions are performed on each
11394   // argument, and arguments that have type float are promoted to double.
11395   ExprResult DefaultArgumentPromotion(Expr *E);
11396 
11397   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11398   /// it as an xvalue. In C++98, the result will still be a prvalue, because
11399   /// we don't have xvalues there.
11400   ExprResult TemporaryMaterializationConversion(Expr *E);
11401 
11402   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11403   enum VariadicCallType {
11404     VariadicFunction,
11405     VariadicBlock,
11406     VariadicMethod,
11407     VariadicConstructor,
11408     VariadicDoesNotApply
11409   };
11410 
11411   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11412                                        const FunctionProtoType *Proto,
11413                                        Expr *Fn);
11414 
11415   // Used for determining in which context a type is allowed to be passed to a
11416   // vararg function.
11417   enum VarArgKind {
11418     VAK_Valid,
11419     VAK_ValidInCXX11,
11420     VAK_Undefined,
11421     VAK_MSVCUndefined,
11422     VAK_Invalid
11423   };
11424 
11425   // Determines which VarArgKind fits an expression.
11426   VarArgKind isValidVarArgType(const QualType &Ty);
11427 
11428   /// Check to see if the given expression is a valid argument to a variadic
11429   /// function, issuing a diagnostic if not.
11430   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11431 
11432   /// Check whether the given statement can have musttail applied to it,
11433   /// issuing a diagnostic and returning false if not. In the success case,
11434   /// the statement is rewritten to remove implicit nodes from the return
11435   /// value.
11436   bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11437 
11438 private:
11439   /// Check whether the given statement can have musttail applied to it,
11440   /// issuing a diagnostic and returning false if not.
11441   bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11442 
11443 public:
11444   /// Check to see if a given expression could have '.c_str()' called on it.
11445   bool hasCStrMethod(const Expr *E);
11446 
11447   /// GatherArgumentsForCall - Collector argument expressions for various
11448   /// form of call prototypes.
11449   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11450                               const FunctionProtoType *Proto,
11451                               unsigned FirstParam, ArrayRef<Expr *> Args,
11452                               SmallVectorImpl<Expr *> &AllArgs,
11453                               VariadicCallType CallType = VariadicDoesNotApply,
11454                               bool AllowExplicit = false,
11455                               bool IsListInitialization = false);
11456 
11457   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11458   // will create a runtime trap if the resulting type is not a POD type.
11459   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11460                                               FunctionDecl *FDecl);
11461 
11462   /// Context in which we're performing a usual arithmetic conversion.
11463   enum ArithConvKind {
11464     /// An arithmetic operation.
11465     ACK_Arithmetic,
11466     /// A bitwise operation.
11467     ACK_BitwiseOp,
11468     /// A comparison.
11469     ACK_Comparison,
11470     /// A conditional (?:) operator.
11471     ACK_Conditional,
11472     /// A compound assignment expression.
11473     ACK_CompAssign,
11474   };
11475 
11476   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11477   // operands and then handles various conversions that are common to binary
11478   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11479   // routine returns the first non-arithmetic type found. The client is
11480   // responsible for emitting appropriate error diagnostics.
11481   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11482                                       SourceLocation Loc, ArithConvKind ACK);
11483 
11484   /// AssignConvertType - All of the 'assignment' semantic checks return this
11485   /// enum to indicate whether the assignment was allowed.  These checks are
11486   /// done for simple assignments, as well as initialization, return from
11487   /// function, argument passing, etc.  The query is phrased in terms of a
11488   /// source and destination type.
11489   enum AssignConvertType {
11490     /// Compatible - the types are compatible according to the standard.
11491     Compatible,
11492 
11493     /// PointerToInt - The assignment converts a pointer to an int, which we
11494     /// accept as an extension.
11495     PointerToInt,
11496 
11497     /// IntToPointer - The assignment converts an int to a pointer, which we
11498     /// accept as an extension.
11499     IntToPointer,
11500 
11501     /// FunctionVoidPointer - The assignment is between a function pointer and
11502     /// void*, which the standard doesn't allow, but we accept as an extension.
11503     FunctionVoidPointer,
11504 
11505     /// IncompatiblePointer - The assignment is between two pointers types that
11506     /// are not compatible, but we accept them as an extension.
11507     IncompatiblePointer,
11508 
11509     /// IncompatibleFunctionPointer - The assignment is between two function
11510     /// pointers types that are not compatible, but we accept them as an
11511     /// extension.
11512     IncompatibleFunctionPointer,
11513 
11514     /// IncompatiblePointerSign - The assignment is between two pointers types
11515     /// which point to integers which have a different sign, but are otherwise
11516     /// identical. This is a subset of the above, but broken out because it's by
11517     /// far the most common case of incompatible pointers.
11518     IncompatiblePointerSign,
11519 
11520     /// CompatiblePointerDiscardsQualifiers - The assignment discards
11521     /// c/v/r qualifiers, which we accept as an extension.
11522     CompatiblePointerDiscardsQualifiers,
11523 
11524     /// IncompatiblePointerDiscardsQualifiers - The assignment
11525     /// discards qualifiers that we don't permit to be discarded,
11526     /// like address spaces.
11527     IncompatiblePointerDiscardsQualifiers,
11528 
11529     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11530     /// changes address spaces in nested pointer types which is not allowed.
11531     /// For instance, converting __private int ** to __generic int ** is
11532     /// illegal even though __private could be converted to __generic.
11533     IncompatibleNestedPointerAddressSpaceMismatch,
11534 
11535     /// IncompatibleNestedPointerQualifiers - The assignment is between two
11536     /// nested pointer types, and the qualifiers other than the first two
11537     /// levels differ e.g. char ** -> const char **, but we accept them as an
11538     /// extension.
11539     IncompatibleNestedPointerQualifiers,
11540 
11541     /// IncompatibleVectors - The assignment is between two vector types that
11542     /// have the same size, which we accept as an extension.
11543     IncompatibleVectors,
11544 
11545     /// IntToBlockPointer - The assignment converts an int to a block
11546     /// pointer. We disallow this.
11547     IntToBlockPointer,
11548 
11549     /// IncompatibleBlockPointer - The assignment is between two block
11550     /// pointers types that are not compatible.
11551     IncompatibleBlockPointer,
11552 
11553     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11554     /// id type and something else (that is incompatible with it). For example,
11555     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11556     IncompatibleObjCQualifiedId,
11557 
11558     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11559     /// object with __weak qualifier.
11560     IncompatibleObjCWeakRef,
11561 
11562     /// Incompatible - We reject this conversion outright, it is invalid to
11563     /// represent it in the AST.
11564     Incompatible
11565   };
11566 
11567   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11568   /// assignment conversion type specified by ConvTy.  This returns true if the
11569   /// conversion was invalid or false if the conversion was accepted.
11570   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11571                                 SourceLocation Loc,
11572                                 QualType DstType, QualType SrcType,
11573                                 Expr *SrcExpr, AssignmentAction Action,
11574                                 bool *Complained = nullptr);
11575 
11576   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11577   /// enum. If AllowMask is true, then we also allow the complement of a valid
11578   /// value, to be used as a mask.
11579   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11580                          bool AllowMask) const;
11581 
11582   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11583   /// integer not in the range of enum values.
11584   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11585                               Expr *SrcExpr);
11586 
11587   /// CheckAssignmentConstraints - Perform type checking for assignment,
11588   /// argument passing, variable initialization, and function return values.
11589   /// C99 6.5.16.
11590   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11591                                                QualType LHSType,
11592                                                QualType RHSType);
11593 
11594   /// Check assignment constraints and optionally prepare for a conversion of
11595   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11596   /// is true.
11597   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11598                                                ExprResult &RHS,
11599                                                CastKind &Kind,
11600                                                bool ConvertRHS = true);
11601 
11602   /// Check assignment constraints for an assignment of RHS to LHSType.
11603   ///
11604   /// \param LHSType The destination type for the assignment.
11605   /// \param RHS The source expression for the assignment.
11606   /// \param Diagnose If \c true, diagnostics may be produced when checking
11607   ///        for assignability. If a diagnostic is produced, \p RHS will be
11608   ///        set to ExprError(). Note that this function may still return
11609   ///        without producing a diagnostic, even for an invalid assignment.
11610   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11611   ///        in an audited Core Foundation API and does not need to be checked
11612   ///        for ARC retain issues.
11613   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11614   ///        conversions necessary to perform the assignment. If \c false,
11615   ///        \p Diagnose must also be \c false.
11616   AssignConvertType CheckSingleAssignmentConstraints(
11617       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11618       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11619 
11620   // If the lhs type is a transparent union, check whether we
11621   // can initialize the transparent union with the given expression.
11622   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11623                                                              ExprResult &RHS);
11624 
11625   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11626 
11627   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11628 
11629   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11630                                        AssignmentAction Action,
11631                                        bool AllowExplicit = false);
11632   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11633                                        const ImplicitConversionSequence& ICS,
11634                                        AssignmentAction Action,
11635                                        CheckedConversionKind CCK
11636                                           = CCK_ImplicitConversion);
11637   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11638                                        const StandardConversionSequence& SCS,
11639                                        AssignmentAction Action,
11640                                        CheckedConversionKind CCK);
11641 
11642   ExprResult PerformQualificationConversion(
11643       Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
11644       CheckedConversionKind CCK = CCK_ImplicitConversion);
11645 
11646   /// the following "Check" methods will return a valid/converted QualType
11647   /// or a null QualType (indicating an error diagnostic was issued).
11648 
11649   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11650   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11651                            ExprResult &RHS);
11652   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11653                                  ExprResult &RHS);
11654   QualType CheckPointerToMemberOperands( // C++ 5.5
11655     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11656     SourceLocation OpLoc, bool isIndirect);
11657   QualType CheckMultiplyDivideOperands( // C99 6.5.5
11658     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11659     bool IsDivide);
11660   QualType CheckRemainderOperands( // C99 6.5.5
11661     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11662     bool IsCompAssign = false);
11663   QualType CheckAdditionOperands( // C99 6.5.6
11664     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11665     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11666   QualType CheckSubtractionOperands( // C99 6.5.6
11667     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11668     QualType* CompLHSTy = nullptr);
11669   QualType CheckShiftOperands( // C99 6.5.7
11670     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11671     BinaryOperatorKind Opc, bool IsCompAssign = false);
11672   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11673   QualType CheckCompareOperands( // C99 6.5.8/9
11674       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11675       BinaryOperatorKind Opc);
11676   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11677       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11678       BinaryOperatorKind Opc);
11679   QualType CheckLogicalOperands( // C99 6.5.[13,14]
11680     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11681     BinaryOperatorKind Opc);
11682   // CheckAssignmentOperands is used for both simple and compound assignment.
11683   // For simple assignment, pass both expressions and a null converted type.
11684   // For compound assignment, pass both expressions and the converted type.
11685   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11686     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11687 
11688   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11689                                      UnaryOperatorKind Opcode, Expr *Op);
11690   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11691                                          BinaryOperatorKind Opcode,
11692                                          Expr *LHS, Expr *RHS);
11693   ExprResult checkPseudoObjectRValue(Expr *E);
11694   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11695 
11696   QualType CheckConditionalOperands( // C99 6.5.15
11697     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11698     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11699   QualType CXXCheckConditionalOperands( // C++ 5.16
11700     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11701     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11702   QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11703                                        ExprResult &RHS,
11704                                        SourceLocation QuestionLoc);
11705   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11706                                     bool ConvertArgs = true);
11707   QualType FindCompositePointerType(SourceLocation Loc,
11708                                     ExprResult &E1, ExprResult &E2,
11709                                     bool ConvertArgs = true) {
11710     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
11711     QualType Composite =
11712         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
11713     E1 = E1Tmp;
11714     E2 = E2Tmp;
11715     return Composite;
11716   }
11717 
11718   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
11719                                         SourceLocation QuestionLoc);
11720 
11721   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
11722                                   SourceLocation QuestionLoc);
11723 
11724   void DiagnoseAlwaysNonNullPointer(Expr *E,
11725                                     Expr::NullPointerConstantKind NullType,
11726                                     bool IsEqual, SourceRange Range);
11727 
11728   /// type checking for vector binary operators.
11729   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11730                                SourceLocation Loc, bool IsCompAssign,
11731                                bool AllowBothBool, bool AllowBoolConversion);
11732   QualType GetSignedVectorType(QualType V);
11733   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11734                                       SourceLocation Loc,
11735                                       BinaryOperatorKind Opc);
11736   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11737                                       SourceLocation Loc);
11738 
11739   /// Type checking for matrix binary operators.
11740   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
11741                                           SourceLocation Loc,
11742                                           bool IsCompAssign);
11743   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
11744                                        SourceLocation Loc, bool IsCompAssign);
11745 
11746   bool isValidSveBitcast(QualType srcType, QualType destType);
11747 
11748   bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
11749 
11750   bool areVectorTypesSameSize(QualType srcType, QualType destType);
11751   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
11752   bool isLaxVectorConversion(QualType srcType, QualType destType);
11753 
11754   /// type checking declaration initializers (C99 6.7.8)
11755   bool CheckForConstantInitializer(Expr *e, QualType t);
11756 
11757   // type checking C++ declaration initializers (C++ [dcl.init]).
11758 
11759   /// ReferenceCompareResult - Expresses the result of comparing two
11760   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
11761   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
11762   enum ReferenceCompareResult {
11763     /// Ref_Incompatible - The two types are incompatible, so direct
11764     /// reference binding is not possible.
11765     Ref_Incompatible = 0,
11766     /// Ref_Related - The two types are reference-related, which means
11767     /// that their unqualified forms (T1 and T2) are either the same
11768     /// or T1 is a base class of T2.
11769     Ref_Related,
11770     /// Ref_Compatible - The two types are reference-compatible.
11771     Ref_Compatible
11772   };
11773 
11774   // Fake up a scoped enumeration that still contextually converts to bool.
11775   struct ReferenceConversionsScope {
11776     /// The conversions that would be performed on an lvalue of type T2 when
11777     /// binding a reference of type T1 to it, as determined when evaluating
11778     /// whether T1 is reference-compatible with T2.
11779     enum ReferenceConversions {
11780       Qualification = 0x1,
11781       NestedQualification = 0x2,
11782       Function = 0x4,
11783       DerivedToBase = 0x8,
11784       ObjC = 0x10,
11785       ObjCLifetime = 0x20,
11786 
11787       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
11788     };
11789   };
11790   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
11791 
11792   ReferenceCompareResult
11793   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
11794                                ReferenceConversions *Conv = nullptr);
11795 
11796   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11797                                  Expr *CastExpr, CastKind &CastKind,
11798                                  ExprValueKind &VK, CXXCastPath &Path);
11799 
11800   /// Force an expression with unknown-type to an expression of the
11801   /// given type.
11802   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
11803 
11804   /// Type-check an expression that's being passed to an
11805   /// __unknown_anytype parameter.
11806   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
11807                                 Expr *result, QualType &paramType);
11808 
11809   // CheckMatrixCast - Check type constraints for matrix casts.
11810   // We allow casting between matrixes of the same dimensions i.e. when they
11811   // have the same number of rows and column. Returns true if the cast is
11812   // invalid.
11813   bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
11814                        CastKind &Kind);
11815 
11816   // CheckVectorCast - check type constraints for vectors.
11817   // Since vectors are an extension, there are no C standard reference for this.
11818   // We allow casting between vectors and integer datatypes of the same size.
11819   // returns true if the cast is invalid
11820   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
11821                        CastKind &Kind);
11822 
11823   /// Prepare `SplattedExpr` for a vector splat operation, adding
11824   /// implicit casts if necessary.
11825   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
11826 
11827   // CheckExtVectorCast - check type constraints for extended vectors.
11828   // Since vectors are an extension, there are no C standard reference for this.
11829   // We allow casting between vectors and integer datatypes of the same size,
11830   // or vectors and the element type of that vector.
11831   // returns the cast expr
11832   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
11833                                 CastKind &Kind);
11834 
11835   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
11836                                         SourceLocation LParenLoc,
11837                                         Expr *CastExpr,
11838                                         SourceLocation RParenLoc);
11839 
11840   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
11841 
11842   /// Checks for invalid conversions and casts between
11843   /// retainable pointers and other pointer kinds for ARC and Weak.
11844   ARCConversionResult CheckObjCConversion(SourceRange castRange,
11845                                           QualType castType, Expr *&op,
11846                                           CheckedConversionKind CCK,
11847                                           bool Diagnose = true,
11848                                           bool DiagnoseCFAudited = false,
11849                                           BinaryOperatorKind Opc = BO_PtrMemD
11850                                           );
11851 
11852   Expr *stripARCUnbridgedCast(Expr *e);
11853   void diagnoseARCUnbridgedCast(Expr *e);
11854 
11855   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
11856                                              QualType ExprType);
11857 
11858   /// checkRetainCycles - Check whether an Objective-C message send
11859   /// might create an obvious retain cycle.
11860   void checkRetainCycles(ObjCMessageExpr *msg);
11861   void checkRetainCycles(Expr *receiver, Expr *argument);
11862   void checkRetainCycles(VarDecl *Var, Expr *Init);
11863 
11864   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
11865   /// to weak/__unsafe_unretained type.
11866   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
11867 
11868   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
11869   /// to weak/__unsafe_unretained expression.
11870   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
11871 
11872   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
11873   /// \param Method - May be null.
11874   /// \param [out] ReturnType - The return type of the send.
11875   /// \return true iff there were any incompatible types.
11876   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
11877                                  MultiExprArg Args, Selector Sel,
11878                                  ArrayRef<SourceLocation> SelectorLocs,
11879                                  ObjCMethodDecl *Method, bool isClassMessage,
11880                                  bool isSuperMessage, SourceLocation lbrac,
11881                                  SourceLocation rbrac, SourceRange RecRange,
11882                                  QualType &ReturnType, ExprValueKind &VK);
11883 
11884   /// Determine the result of a message send expression based on
11885   /// the type of the receiver, the method expected to receive the message,
11886   /// and the form of the message send.
11887   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11888                                     ObjCMethodDecl *Method, bool isClassMessage,
11889                                     bool isSuperMessage);
11890 
11891   /// If the given expression involves a message send to a method
11892   /// with a related result type, emit a note describing what happened.
11893   void EmitRelatedResultTypeNote(const Expr *E);
11894 
11895   /// Given that we had incompatible pointer types in a return
11896   /// statement, check whether we're in a method with a related result
11897   /// type, and if so, emit a note describing what happened.
11898   void EmitRelatedResultTypeNoteForReturn(QualType destType);
11899 
11900   class ConditionResult {
11901     Decl *ConditionVar;
11902     FullExprArg Condition;
11903     bool Invalid;
11904     bool HasKnownValue;
11905     bool KnownValue;
11906 
11907     friend class Sema;
ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)11908     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11909                     bool IsConstexpr)
11910         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11911           HasKnownValue(IsConstexpr && Condition.get() &&
11912                         !Condition.get()->isValueDependent()),
11913           KnownValue(HasKnownValue &&
11914                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
ConditionResult(bool Invalid)11915     explicit ConditionResult(bool Invalid)
11916         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11917           HasKnownValue(false), KnownValue(false) {}
11918 
11919   public:
ConditionResult()11920     ConditionResult() : ConditionResult(false) {}
isInvalid()11921     bool isInvalid() const { return Invalid; }
get()11922     std::pair<VarDecl *, Expr *> get() const {
11923       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11924                             Condition.get());
11925     }
getKnownValue()11926     llvm::Optional<bool> getKnownValue() const {
11927       if (!HasKnownValue)
11928         return None;
11929       return KnownValue;
11930     }
11931   };
ConditionError()11932   static ConditionResult ConditionError() { return ConditionResult(true); }
11933 
11934   enum class ConditionKind {
11935     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
11936     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
11937     Switch       ///< An integral condition for a 'switch' statement.
11938   };
11939 
11940   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
11941                                  Expr *SubExpr, ConditionKind CK);
11942 
11943   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
11944                                          SourceLocation StmtLoc,
11945                                          ConditionKind CK);
11946 
11947   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
11948 
11949   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
11950                                     SourceLocation StmtLoc,
11951                                     ConditionKind CK);
11952   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11953 
11954   /// CheckBooleanCondition - Diagnose problems involving the use of
11955   /// the given expression as a boolean condition (e.g. in an if
11956   /// statement).  Also performs the standard function and array
11957   /// decays, possibly changing the input variable.
11958   ///
11959   /// \param Loc - A location associated with the condition, e.g. the
11960   /// 'if' keyword.
11961   /// \return true iff there were any errors
11962   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
11963                                    bool IsConstexpr = false);
11964 
11965   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
11966   /// found in an explicit(bool) specifier.
11967   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
11968 
11969   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
11970   /// Returns true if the explicit specifier is now resolved.
11971   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
11972 
11973   /// DiagnoseAssignmentAsCondition - Given that an expression is
11974   /// being used as a boolean condition, warn if it's an assignment.
11975   void DiagnoseAssignmentAsCondition(Expr *E);
11976 
11977   /// Redundant parentheses over an equality comparison can indicate
11978   /// that the user intended an assignment used as condition.
11979   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
11980 
11981   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
11982   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
11983 
11984   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
11985   /// the specified width and sign.  If an overflow occurs, detect it and emit
11986   /// the specified diagnostic.
11987   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
11988                                           unsigned NewWidth, bool NewSign,
11989                                           SourceLocation Loc, unsigned DiagID);
11990 
11991   /// Checks that the Objective-C declaration is declared in the global scope.
11992   /// Emits an error and marks the declaration as invalid if it's not declared
11993   /// in the global scope.
11994   bool CheckObjCDeclScope(Decl *D);
11995 
11996   /// Abstract base class used for diagnosing integer constant
11997   /// expression violations.
11998   class VerifyICEDiagnoser {
11999   public:
12000     bool Suppress;
12001 
Suppress(Suppress)12002     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
12003 
12004     virtual SemaDiagnosticBuilder
12005     diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
12006     virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
12007                                                  SourceLocation Loc) = 0;
12008     virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
~VerifyICEDiagnoser()12009     virtual ~VerifyICEDiagnoser() {}
12010   };
12011 
12012   enum AllowFoldKind {
12013     NoFold,
12014     AllowFold,
12015   };
12016 
12017   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
12018   /// and reports the appropriate diagnostics. Returns false on success.
12019   /// Can optionally return the value of the expression.
12020   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12021                                              VerifyICEDiagnoser &Diagnoser,
12022                                              AllowFoldKind CanFold = NoFold);
12023   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12024                                              unsigned DiagID,
12025                                              AllowFoldKind CanFold = NoFold);
12026   ExprResult VerifyIntegerConstantExpression(Expr *E,
12027                                              llvm::APSInt *Result = nullptr,
12028                                              AllowFoldKind CanFold = NoFold);
12029   ExprResult VerifyIntegerConstantExpression(Expr *E,
12030                                              AllowFoldKind CanFold = NoFold) {
12031     return VerifyIntegerConstantExpression(E, nullptr, CanFold);
12032   }
12033 
12034   /// VerifyBitField - verifies that a bit field expression is an ICE and has
12035   /// the correct width, and that the field type is valid.
12036   /// Returns false on success.
12037   /// Can optionally return whether the bit-field is of width 0
12038   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
12039                             QualType FieldTy, bool IsMsStruct,
12040                             Expr *BitWidth, bool *ZeroWidth = nullptr);
12041 
12042 private:
12043   unsigned ForceCUDAHostDeviceDepth = 0;
12044 
12045 public:
12046   /// Increments our count of the number of times we've seen a pragma forcing
12047   /// functions to be __host__ __device__.  So long as this count is greater
12048   /// than zero, all functions encountered will be __host__ __device__.
12049   void PushForceCUDAHostDevice();
12050 
12051   /// Decrements our count of the number of times we've seen a pragma forcing
12052   /// functions to be __host__ __device__.  Returns false if the count is 0
12053   /// before incrementing, so you can emit an error.
12054   bool PopForceCUDAHostDevice();
12055 
12056   /// Diagnostics that are emitted only if we discover that the given function
12057   /// must be codegen'ed.  Because handling these correctly adds overhead to
12058   /// compilation, this is currently only enabled for CUDA compilations.
12059   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
12060                  std::vector<PartialDiagnosticAt>>
12061       DeviceDeferredDiags;
12062 
12063   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
12064   /// key in a hashtable, both the FD and location are hashed.
12065   struct FunctionDeclAndLoc {
12066     CanonicalDeclPtr<FunctionDecl> FD;
12067     SourceLocation Loc;
12068   };
12069 
12070   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
12071   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
12072   /// same deferred diag twice.
12073   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
12074 
12075   /// An inverse call graph, mapping known-emitted functions to one of their
12076   /// known-emitted callers (plus the location of the call).
12077   ///
12078   /// Functions that we can tell a priori must be emitted aren't added to this
12079   /// map.
12080   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
12081                  /* Caller = */ FunctionDeclAndLoc>
12082       DeviceKnownEmittedFns;
12083 
12084   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12085   /// context is "used as device code".
12086   ///
12087   /// - If CurContext is a __host__ function, does not emit any diagnostics
12088   ///   unless \p EmitOnBothSides is true.
12089   /// - If CurContext is a __device__ or __global__ function, emits the
12090   ///   diagnostics immediately.
12091   /// - If CurContext is a __host__ __device__ function and we are compiling for
12092   ///   the device, creates a diagnostic which is emitted if and when we realize
12093   ///   that the function will be codegen'ed.
12094   ///
12095   /// Example usage:
12096   ///
12097   ///  // Variable-length arrays are not allowed in CUDA device code.
12098   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
12099   ///    return ExprError();
12100   ///  // Otherwise, continue parsing as normal.
12101   SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
12102                                              unsigned DiagID);
12103 
12104   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12105   /// context is "used as host code".
12106   ///
12107   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
12108   SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
12109 
12110   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12111   /// context is "used as device code".
12112   ///
12113   /// - If CurContext is a `declare target` function or it is known that the
12114   /// function is emitted for the device, emits the diagnostics immediately.
12115   /// - If CurContext is a non-`declare target` function and we are compiling
12116   ///   for the device, creates a diagnostic which is emitted if and when we
12117   ///   realize that the function will be codegen'ed.
12118   ///
12119   /// Example usage:
12120   ///
12121   ///  // Variable-length arrays are not allowed in NVPTX device code.
12122   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
12123   ///    return ExprError();
12124   ///  // Otherwise, continue parsing as normal.
12125   SemaDiagnosticBuilder
12126   diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
12127 
12128   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12129   /// context is "used as host code".
12130   ///
12131   /// - If CurContext is a `declare target` function or it is known that the
12132   /// function is emitted for the host, emits the diagnostics immediately.
12133   /// - If CurContext is a non-host function, just ignore it.
12134   ///
12135   /// Example usage:
12136   ///
12137   ///  // Variable-length arrays are not allowed in NVPTX device code.
12138   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
12139   ///    return ExprError();
12140   ///  // Otherwise, continue parsing as normal.
12141   SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
12142                                              unsigned DiagID, FunctionDecl *FD);
12143 
12144   SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
12145                                    FunctionDecl *FD = nullptr);
12146   SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
12147                                    const PartialDiagnostic &PD,
12148                                    FunctionDecl *FD = nullptr) {
12149     return targetDiag(Loc, PD.getDiagID(), FD) << PD;
12150   }
12151 
12152   /// Check if the expression is allowed to be used in expressions for the
12153   /// offloading devices.
12154   void checkDeviceDecl(ValueDecl *D, SourceLocation Loc);
12155 
12156   enum CUDAFunctionTarget {
12157     CFT_Device,
12158     CFT_Global,
12159     CFT_Host,
12160     CFT_HostDevice,
12161     CFT_InvalidTarget
12162   };
12163 
12164   /// Determines whether the given function is a CUDA device/host/kernel/etc.
12165   /// function.
12166   ///
12167   /// Use this rather than examining the function's attributes yourself -- you
12168   /// will get it wrong.  Returns CFT_Host if D is null.
12169   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
12170                                         bool IgnoreImplicitHDAttr = false);
12171   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
12172 
12173   enum CUDAVariableTarget {
12174     CVT_Device,  /// Emitted on device side with a shadow variable on host side
12175     CVT_Host,    /// Emitted on host side only
12176     CVT_Both,    /// Emitted on both sides with different addresses
12177     CVT_Unified, /// Emitted as a unified address, e.g. managed variables
12178   };
12179   /// Determines whether the given variable is emitted on host or device side.
12180   CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
12181 
12182   /// Gets the CUDA target for the current context.
CurrentCUDATarget()12183   CUDAFunctionTarget CurrentCUDATarget() {
12184     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
12185   }
12186 
12187   static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
12188 
12189   // CUDA function call preference. Must be ordered numerically from
12190   // worst to best.
12191   enum CUDAFunctionPreference {
12192     CFP_Never,      // Invalid caller/callee combination.
12193     CFP_WrongSide,  // Calls from host-device to host or device
12194                     // function that do not match current compilation
12195                     // mode.
12196     CFP_HostDevice, // Any calls to host/device functions.
12197     CFP_SameSide,   // Calls from host-device to host or device
12198                     // function matching current compilation mode.
12199     CFP_Native,     // host-to-host or device-to-device calls.
12200   };
12201 
12202   /// Identifies relative preference of a given Caller/Callee
12203   /// combination, based on their host/device attributes.
12204   /// \param Caller function which needs address of \p Callee.
12205   ///               nullptr in case of global context.
12206   /// \param Callee target function
12207   ///
12208   /// \returns preference value for particular Caller/Callee combination.
12209   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
12210                                                 const FunctionDecl *Callee);
12211 
12212   /// Determines whether Caller may invoke Callee, based on their CUDA
12213   /// host/device attributes.  Returns false if the call is not allowed.
12214   ///
12215   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
12216   /// semantically correct CUDA programs, but only if they're never codegen'ed.
IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)12217   bool IsAllowedCUDACall(const FunctionDecl *Caller,
12218                          const FunctionDecl *Callee) {
12219     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
12220   }
12221 
12222   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
12223   /// depending on FD and the current compilation settings.
12224   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
12225                                    const LookupResult &Previous);
12226 
12227   /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
12228   /// and current compilation settings.
12229   void MaybeAddCUDAConstantAttr(VarDecl *VD);
12230 
12231 public:
12232   /// Check whether we're allowed to call Callee from the current context.
12233   ///
12234   /// - If the call is never allowed in a semantically-correct program
12235   ///   (CFP_Never), emits an error and returns false.
12236   ///
12237   /// - If the call is allowed in semantically-correct programs, but only if
12238   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
12239   ///   be emitted if and when the caller is codegen'ed, and returns true.
12240   ///
12241   ///   Will only create deferred diagnostics for a given SourceLocation once,
12242   ///   so you can safely call this multiple times without generating duplicate
12243   ///   deferred errors.
12244   ///
12245   /// - Otherwise, returns true without emitting any diagnostics.
12246   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
12247 
12248   void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
12249 
12250   /// Set __device__ or __host__ __device__ attributes on the given lambda
12251   /// operator() method.
12252   ///
12253   /// CUDA lambdas by default is host device function unless it has explicit
12254   /// host or device attribute.
12255   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
12256 
12257   /// Finds a function in \p Matches with highest calling priority
12258   /// from \p Caller context and erases all functions with lower
12259   /// calling priority.
12260   void EraseUnwantedCUDAMatches(
12261       const FunctionDecl *Caller,
12262       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
12263 
12264   /// Given a implicit special member, infer its CUDA target from the
12265   /// calls it needs to make to underlying base/field special members.
12266   /// \param ClassDecl the class for which the member is being created.
12267   /// \param CSM the kind of special member.
12268   /// \param MemberDecl the special member itself.
12269   /// \param ConstRHS true if this is a copy operation with a const object on
12270   ///        its RHS.
12271   /// \param Diagnose true if this call should emit diagnostics.
12272   /// \return true if there was an error inferring.
12273   /// The result of this call is implicit CUDA target attribute(s) attached to
12274   /// the member declaration.
12275   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12276                                                CXXSpecialMember CSM,
12277                                                CXXMethodDecl *MemberDecl,
12278                                                bool ConstRHS,
12279                                                bool Diagnose);
12280 
12281   /// \return true if \p CD can be considered empty according to CUDA
12282   /// (E.2.3.1 in CUDA 7.5 Programming guide).
12283   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12284   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12285 
12286   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12287   // case of error emits appropriate diagnostic and invalidates \p Var.
12288   //
12289   // \details CUDA allows only empty constructors as initializers for global
12290   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12291   // __shared__ variables whether they are local or not (they all are implicitly
12292   // static in CUDA). One exception is that CUDA allows constant initializers
12293   // for __constant__ and __device__ variables.
12294   void checkAllowedCUDAInitializer(VarDecl *VD);
12295 
12296   /// Check whether NewFD is a valid overload for CUDA. Emits
12297   /// diagnostics and invalidates NewFD if not.
12298   void checkCUDATargetOverload(FunctionDecl *NewFD,
12299                                const LookupResult &Previous);
12300   /// Copies target attributes from the template TD to the function FD.
12301   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12302 
12303   /// Returns the name of the launch configuration function.  This is the name
12304   /// of the function that will be called to configure kernel call, with the
12305   /// parameters specified via <<<>>>.
12306   std::string getCudaConfigureFuncName() const;
12307 
12308   /// \name Code completion
12309   //@{
12310   /// Describes the context in which code completion occurs.
12311   enum ParserCompletionContext {
12312     /// Code completion occurs at top-level or namespace context.
12313     PCC_Namespace,
12314     /// Code completion occurs within a class, struct, or union.
12315     PCC_Class,
12316     /// Code completion occurs within an Objective-C interface, protocol,
12317     /// or category.
12318     PCC_ObjCInterface,
12319     /// Code completion occurs within an Objective-C implementation or
12320     /// category implementation
12321     PCC_ObjCImplementation,
12322     /// Code completion occurs within the list of instance variables
12323     /// in an Objective-C interface, protocol, category, or implementation.
12324     PCC_ObjCInstanceVariableList,
12325     /// Code completion occurs following one or more template
12326     /// headers.
12327     PCC_Template,
12328     /// Code completion occurs following one or more template
12329     /// headers within a class.
12330     PCC_MemberTemplate,
12331     /// Code completion occurs within an expression.
12332     PCC_Expression,
12333     /// Code completion occurs within a statement, which may
12334     /// also be an expression or a declaration.
12335     PCC_Statement,
12336     /// Code completion occurs at the beginning of the
12337     /// initialization statement (or expression) in a for loop.
12338     PCC_ForInit,
12339     /// Code completion occurs within the condition of an if,
12340     /// while, switch, or for statement.
12341     PCC_Condition,
12342     /// Code completion occurs within the body of a function on a
12343     /// recovery path, where we do not have a specific handle on our position
12344     /// in the grammar.
12345     PCC_RecoveryInFunction,
12346     /// Code completion occurs where only a type is permitted.
12347     PCC_Type,
12348     /// Code completion occurs in a parenthesized expression, which
12349     /// might also be a type cast.
12350     PCC_ParenthesizedExpression,
12351     /// Code completion occurs within a sequence of declaration
12352     /// specifiers within a function, method, or block.
12353     PCC_LocalDeclarationSpecifiers
12354   };
12355 
12356   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12357   void CodeCompleteOrdinaryName(Scope *S,
12358                                 ParserCompletionContext CompletionContext);
12359   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12360                             bool AllowNonIdentifiers,
12361                             bool AllowNestedNameSpecifiers);
12362 
12363   struct CodeCompleteExpressionData;
12364   void CodeCompleteExpression(Scope *S,
12365                               const CodeCompleteExpressionData &Data);
12366   void CodeCompleteExpression(Scope *S, QualType PreferredType,
12367                               bool IsParenthesized = false);
12368   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12369                                        SourceLocation OpLoc, bool IsArrow,
12370                                        bool IsBaseExprStatement,
12371                                        QualType PreferredType);
12372   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12373                                      QualType PreferredType);
12374   void CodeCompleteTag(Scope *S, unsigned TagSpec);
12375   void CodeCompleteTypeQualifiers(DeclSpec &DS);
12376   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12377                                       const VirtSpecifiers *VS = nullptr);
12378   void CodeCompleteBracketDeclarator(Scope *S);
12379   void CodeCompleteCase(Scope *S);
12380   /// Determines the preferred type of the current function argument, by
12381   /// examining the signatures of all possible overloads.
12382   /// Returns null if unknown or ambiguous, or if code completion is off.
12383   ///
12384   /// If the code completion point has been reached, also reports the function
12385   /// signatures that were considered.
12386   ///
12387   /// FIXME: rename to GuessCallArgumentType to reduce confusion.
12388   QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
12389                                     SourceLocation OpenParLoc);
12390   QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
12391                                            SourceLocation Loc,
12392                                            ArrayRef<Expr *> Args,
12393                                            SourceLocation OpenParLoc);
12394   QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
12395                                               CXXScopeSpec SS,
12396                                               ParsedType TemplateTypeTy,
12397                                               ArrayRef<Expr *> ArgExprs,
12398                                               IdentifierInfo *II,
12399                                               SourceLocation OpenParLoc);
12400   void CodeCompleteInitializer(Scope *S, Decl *D);
12401   /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12402   /// expressions in the initializer list seen so far and \p D is the current
12403   /// Designation being parsed.
12404   void CodeCompleteDesignator(const QualType BaseType,
12405                               llvm::ArrayRef<Expr *> InitExprs,
12406                               const Designation &D);
12407   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12408 
12409   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12410                                bool IsUsingDeclaration, QualType BaseType,
12411                                QualType PreferredType);
12412   void CodeCompleteUsing(Scope *S);
12413   void CodeCompleteUsingDirective(Scope *S);
12414   void CodeCompleteNamespaceDecl(Scope *S);
12415   void CodeCompleteNamespaceAliasDecl(Scope *S);
12416   void CodeCompleteOperatorName(Scope *S);
12417   void CodeCompleteConstructorInitializer(
12418                                 Decl *Constructor,
12419                                 ArrayRef<CXXCtorInitializer *> Initializers);
12420 
12421   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12422                                     bool AfterAmpersand);
12423   void CodeCompleteAfterFunctionEquals(Declarator &D);
12424 
12425   void CodeCompleteObjCAtDirective(Scope *S);
12426   void CodeCompleteObjCAtVisibility(Scope *S);
12427   void CodeCompleteObjCAtStatement(Scope *S);
12428   void CodeCompleteObjCAtExpression(Scope *S);
12429   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12430   void CodeCompleteObjCPropertyGetter(Scope *S);
12431   void CodeCompleteObjCPropertySetter(Scope *S);
12432   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12433                                    bool IsParameter);
12434   void CodeCompleteObjCMessageReceiver(Scope *S);
12435   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12436                                     ArrayRef<IdentifierInfo *> SelIdents,
12437                                     bool AtArgumentExpression);
12438   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12439                                     ArrayRef<IdentifierInfo *> SelIdents,
12440                                     bool AtArgumentExpression,
12441                                     bool IsSuper = false);
12442   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12443                                        ArrayRef<IdentifierInfo *> SelIdents,
12444                                        bool AtArgumentExpression,
12445                                        ObjCInterfaceDecl *Super = nullptr);
12446   void CodeCompleteObjCForCollection(Scope *S,
12447                                      DeclGroupPtrTy IterationVar);
12448   void CodeCompleteObjCSelector(Scope *S,
12449                                 ArrayRef<IdentifierInfo *> SelIdents);
12450   void CodeCompleteObjCProtocolReferences(
12451                                          ArrayRef<IdentifierLocPair> Protocols);
12452   void CodeCompleteObjCProtocolDecl(Scope *S);
12453   void CodeCompleteObjCInterfaceDecl(Scope *S);
12454   void CodeCompleteObjCSuperclass(Scope *S,
12455                                   IdentifierInfo *ClassName,
12456                                   SourceLocation ClassNameLoc);
12457   void CodeCompleteObjCImplementationDecl(Scope *S);
12458   void CodeCompleteObjCInterfaceCategory(Scope *S,
12459                                          IdentifierInfo *ClassName,
12460                                          SourceLocation ClassNameLoc);
12461   void CodeCompleteObjCImplementationCategory(Scope *S,
12462                                               IdentifierInfo *ClassName,
12463                                               SourceLocation ClassNameLoc);
12464   void CodeCompleteObjCPropertyDefinition(Scope *S);
12465   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12466                                               IdentifierInfo *PropertyName);
12467   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12468                                   ParsedType ReturnType);
12469   void CodeCompleteObjCMethodDeclSelector(Scope *S,
12470                                           bool IsInstanceMethod,
12471                                           bool AtParameterName,
12472                                           ParsedType ReturnType,
12473                                           ArrayRef<IdentifierInfo *> SelIdents);
12474   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12475                                             SourceLocation ClassNameLoc,
12476                                             bool IsBaseExprStatement);
12477   void CodeCompletePreprocessorDirective(bool InConditional);
12478   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12479   void CodeCompletePreprocessorMacroName(bool IsDefinition);
12480   void CodeCompletePreprocessorExpression();
12481   void CodeCompletePreprocessorMacroArgument(Scope *S,
12482                                              IdentifierInfo *Macro,
12483                                              MacroInfo *MacroInfo,
12484                                              unsigned Argument);
12485   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12486   void CodeCompleteNaturalLanguage();
12487   void CodeCompleteAvailabilityPlatformName();
12488   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12489                                    CodeCompletionTUInfo &CCTUInfo,
12490                   SmallVectorImpl<CodeCompletionResult> &Results);
12491   //@}
12492 
12493   //===--------------------------------------------------------------------===//
12494   // Extra semantic analysis beyond the C type system
12495 
12496 public:
12497   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12498                                                 unsigned ByteNo) const;
12499 
12500 private:
12501   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12502                         const ArraySubscriptExpr *ASE=nullptr,
12503                         bool AllowOnePastEnd=true, bool IndexNegated=false);
12504   void CheckArrayAccess(const Expr *E);
12505   // Used to grab the relevant information from a FormatAttr and a
12506   // FunctionDeclaration.
12507   struct FormatStringInfo {
12508     unsigned FormatIdx;
12509     unsigned FirstDataArg;
12510     bool HasVAListArg;
12511   };
12512 
12513   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12514                                   FormatStringInfo *FSI);
12515   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12516                          const FunctionProtoType *Proto);
12517   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12518                            ArrayRef<const Expr *> Args);
12519   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12520                         const FunctionProtoType *Proto);
12521   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12522   void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
12523                             ArrayRef<const Expr *> Args,
12524                             const FunctionProtoType *Proto, SourceLocation Loc);
12525 
12526   void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
12527                          StringRef ParamName, QualType ArgTy, QualType ParamTy);
12528 
12529   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12530                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
12531                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12532                  VariadicCallType CallType);
12533 
12534   bool CheckObjCString(Expr *Arg);
12535   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12536 
12537   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12538                                       unsigned BuiltinID, CallExpr *TheCall);
12539 
12540   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12541                                   CallExpr *TheCall);
12542 
12543   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12544 
12545   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12546                                     unsigned MaxWidth);
12547   bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12548                                     CallExpr *TheCall);
12549   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12550   bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12551   bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12552                                    CallExpr *TheCall);
12553   bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12554                                     bool WantCDE);
12555   bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12556                                    CallExpr *TheCall);
12557 
12558   bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12559                                        CallExpr *TheCall);
12560   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12561   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12562   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12563   bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12564                                     CallExpr *TheCall);
12565   bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12566                            CallExpr *TheCall);
12567   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12568   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12569   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12570   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12571   bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12572   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12573                                          ArrayRef<int> ArgNums);
12574   bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12575   bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12576                                             ArrayRef<int> ArgNums);
12577   bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12578                                    CallExpr *TheCall);
12579   bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12580                                    CallExpr *TheCall);
12581   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12582   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
12583   bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12584                                      CallExpr *TheCall);
12585 
12586   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12587   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12588   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12589   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12590   bool SemaBuiltinComplex(CallExpr *TheCall);
12591   bool SemaBuiltinVSX(CallExpr *TheCall);
12592   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12593   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
12594 
12595 public:
12596   // Used by C++ template instantiation.
12597   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12598   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12599                                    SourceLocation BuiltinLoc,
12600                                    SourceLocation RParenLoc);
12601 
12602 private:
12603   bool SemaBuiltinPrefetch(CallExpr *TheCall);
12604   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12605   bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
12606   bool SemaBuiltinAssume(CallExpr *TheCall);
12607   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12608   bool SemaBuiltinLongjmp(CallExpr *TheCall);
12609   bool SemaBuiltinSetjmp(CallExpr *TheCall);
12610   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12611   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12612   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12613                                      AtomicExpr::AtomicOp Op);
12614   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12615                                                     bool IsDelete);
12616   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12617                               llvm::APSInt &Result);
12618   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12619                                    int High, bool RangeIsError = true);
12620   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12621                                       unsigned Multiple);
12622   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12623   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12624                                          unsigned ArgBits);
12625   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12626                                                unsigned ArgBits);
12627   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12628                                 int ArgNum, unsigned ExpectedFieldNum,
12629                                 bool AllowName);
12630   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12631   bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc);
12632 
12633   bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
12634 
12635   // Matrix builtin handling.
12636   ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12637                                         ExprResult CallResult);
12638   ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12639                                               ExprResult CallResult);
12640   ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12641                                                ExprResult CallResult);
12642 
12643 public:
12644   enum FormatStringType {
12645     FST_Scanf,
12646     FST_Printf,
12647     FST_NSString,
12648     FST_Strftime,
12649     FST_Strfmon,
12650     FST_Kprintf,
12651     FST_FreeBSDKPrintf,
12652     FST_OSTrace,
12653     FST_OSLog,
12654     FST_Unknown
12655   };
12656   static FormatStringType GetFormatStringType(const FormatAttr *Format);
12657 
12658   bool FormatStringHasSArg(const StringLiteral *FExpr);
12659 
12660   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12661 
12662 private:
12663   bool CheckFormatArguments(const FormatAttr *Format,
12664                             ArrayRef<const Expr *> Args,
12665                             bool IsCXXMember,
12666                             VariadicCallType CallType,
12667                             SourceLocation Loc, SourceRange Range,
12668                             llvm::SmallBitVector &CheckedVarArgs);
12669   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12670                             bool HasVAListArg, unsigned format_idx,
12671                             unsigned firstDataArg, FormatStringType Type,
12672                             VariadicCallType CallType,
12673                             SourceLocation Loc, SourceRange range,
12674                             llvm::SmallBitVector &CheckedVarArgs);
12675 
12676   void CheckAbsoluteValueFunction(const CallExpr *Call,
12677                                   const FunctionDecl *FDecl);
12678 
12679   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12680 
12681   void CheckMemaccessArguments(const CallExpr *Call,
12682                                unsigned BId,
12683                                IdentifierInfo *FnName);
12684 
12685   void CheckStrlcpycatArguments(const CallExpr *Call,
12686                                 IdentifierInfo *FnName);
12687 
12688   void CheckStrncatArguments(const CallExpr *Call,
12689                              IdentifierInfo *FnName);
12690 
12691   void CheckFreeArguments(const CallExpr *E);
12692 
12693   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
12694                           SourceLocation ReturnLoc,
12695                           bool isObjCMethod = false,
12696                           const AttrVec *Attrs = nullptr,
12697                           const FunctionDecl *FD = nullptr);
12698 
12699 public:
12700   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
12701 
12702 private:
12703   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
12704   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
12705   void CheckForIntOverflow(Expr *E);
12706   void CheckUnsequencedOperations(const Expr *E);
12707 
12708   /// Perform semantic checks on a completed expression. This will either
12709   /// be a full-expression or a default argument expression.
12710   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
12711                           bool IsConstexpr = false);
12712 
12713   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
12714                                    Expr *Init);
12715 
12716   /// Check if there is a field shadowing.
12717   void CheckShadowInheritedFields(const SourceLocation &Loc,
12718                                   DeclarationName FieldName,
12719                                   const CXXRecordDecl *RD,
12720                                   bool DeclIsField = true);
12721 
12722   /// Check if the given expression contains 'break' or 'continue'
12723   /// statement that produces control flow different from GCC.
12724   void CheckBreakContinueBinding(Expr *E);
12725 
12726   /// Check whether receiver is mutable ObjC container which
12727   /// attempts to add itself into the container
12728   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
12729 
12730   void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee);
12731 
12732   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
12733   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
12734                                  bool DeleteWasArrayForm);
12735 public:
12736   /// Register a magic integral constant to be used as a type tag.
12737   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12738                                   uint64_t MagicValue, QualType Type,
12739                                   bool LayoutCompatible, bool MustBeNull);
12740 
12741   struct TypeTagData {
TypeTagDataTypeTagData12742     TypeTagData() {}
12743 
TypeTagDataTypeTagData12744     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
12745         Type(Type), LayoutCompatible(LayoutCompatible),
12746         MustBeNull(MustBeNull)
12747     {}
12748 
12749     QualType Type;
12750 
12751     /// If true, \c Type should be compared with other expression's types for
12752     /// layout-compatibility.
12753     unsigned LayoutCompatible : 1;
12754     unsigned MustBeNull : 1;
12755   };
12756 
12757   /// A pair of ArgumentKind identifier and magic value.  This uniquely
12758   /// identifies the magic value.
12759   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
12760 
12761 private:
12762   /// A map from magic value to type information.
12763   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
12764       TypeTagForDatatypeMagicValues;
12765 
12766   /// Peform checks on a call of a function with argument_with_type_tag
12767   /// or pointer_with_type_tag attributes.
12768   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12769                                 const ArrayRef<const Expr *> ExprArgs,
12770                                 SourceLocation CallSiteLoc);
12771 
12772   /// Check if we are taking the address of a packed field
12773   /// as this may be a problem if the pointer value is dereferenced.
12774   void CheckAddressOfPackedMember(Expr *rhs);
12775 
12776   /// The parser's current scope.
12777   ///
12778   /// The parser maintains this state here.
12779   Scope *CurScope;
12780 
12781   mutable IdentifierInfo *Ident_super;
12782   mutable IdentifierInfo *Ident___float128;
12783 
12784   /// Nullability type specifiers.
12785   IdentifierInfo *Ident__Nonnull = nullptr;
12786   IdentifierInfo *Ident__Nullable = nullptr;
12787   IdentifierInfo *Ident__Nullable_result = nullptr;
12788   IdentifierInfo *Ident__Null_unspecified = nullptr;
12789 
12790   IdentifierInfo *Ident_NSError = nullptr;
12791 
12792   /// The handler for the FileChanged preprocessor events.
12793   ///
12794   /// Used for diagnostics that implement custom semantic analysis for #include
12795   /// directives, like -Wpragma-pack.
12796   sema::SemaPPCallbacks *SemaPPCallbackHandler;
12797 
12798 protected:
12799   friend class Parser;
12800   friend class InitializationSequence;
12801   friend class ASTReader;
12802   friend class ASTDeclReader;
12803   friend class ASTWriter;
12804 
12805 public:
12806   /// Retrieve the keyword associated
12807   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
12808 
12809   /// The struct behind the CFErrorRef pointer.
12810   RecordDecl *CFError = nullptr;
12811   bool isCFError(RecordDecl *D);
12812 
12813   /// Retrieve the identifier "NSError".
12814   IdentifierInfo *getNSErrorIdent();
12815 
12816   /// Retrieve the parser's current scope.
12817   ///
12818   /// This routine must only be used when it is certain that semantic analysis
12819   /// and the parser are in precisely the same context, which is not the case
12820   /// when, e.g., we are performing any kind of template instantiation.
12821   /// Therefore, the only safe places to use this scope are in the parser
12822   /// itself and in routines directly invoked from the parser and *never* from
12823   /// template substitution or instantiation.
getCurScope()12824   Scope *getCurScope() const { return CurScope; }
12825 
incrementMSManglingNumber()12826   void incrementMSManglingNumber() const {
12827     return CurScope->incrementMSManglingNumber();
12828   }
12829 
12830   IdentifierInfo *getSuperIdentifier() const;
12831   IdentifierInfo *getFloat128Identifier() const;
12832 
12833   Decl *getObjCDeclContext() const;
12834 
getCurLexicalContext()12835   DeclContext *getCurLexicalContext() const {
12836     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
12837   }
12838 
getCurObjCLexicalContext()12839   const DeclContext *getCurObjCLexicalContext() const {
12840     const DeclContext *DC = getCurLexicalContext();
12841     // A category implicitly has the attribute of the interface.
12842     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
12843       DC = CatD->getClassInterface();
12844     return DC;
12845   }
12846 
12847   /// Determine the number of levels of enclosing template parameters. This is
12848   /// only usable while parsing. Note that this does not include dependent
12849   /// contexts in which no template parameters have yet been declared, such as
12850   /// in a terse function template or generic lambda before the first 'auto' is
12851   /// encountered.
12852   unsigned getTemplateDepth(Scope *S) const;
12853 
12854   /// To be used for checking whether the arguments being passed to
12855   /// function exceeds the number of parameters expected for it.
12856   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
12857                                bool PartialOverloading = false) {
12858     // We check whether we're just after a comma in code-completion.
12859     if (NumArgs > 0 && PartialOverloading)
12860       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
12861     return NumArgs > NumParams;
12862   }
12863 
12864   // Emitting members of dllexported classes is delayed until the class
12865   // (including field initializers) is fully parsed.
12866   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
12867   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
12868 
12869 private:
12870   int ParsingClassDepth = 0;
12871 
12872   class SavePendingParsedClassStateRAII {
12873   public:
SavePendingParsedClassStateRAII(Sema & S)12874     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
12875 
~SavePendingParsedClassStateRAII()12876     ~SavePendingParsedClassStateRAII() {
12877       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
12878              "there shouldn't be any pending delayed exception spec checks");
12879       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
12880              "there shouldn't be any pending delayed exception spec checks");
12881       swapSavedState();
12882     }
12883 
12884   private:
12885     Sema &S;
12886     decltype(DelayedOverridingExceptionSpecChecks)
12887         SavedOverridingExceptionSpecChecks;
12888     decltype(DelayedEquivalentExceptionSpecChecks)
12889         SavedEquivalentExceptionSpecChecks;
12890 
swapSavedState()12891     void swapSavedState() {
12892       SavedOverridingExceptionSpecChecks.swap(
12893           S.DelayedOverridingExceptionSpecChecks);
12894       SavedEquivalentExceptionSpecChecks.swap(
12895           S.DelayedEquivalentExceptionSpecChecks);
12896     }
12897   };
12898 
12899   /// Helper class that collects misaligned member designations and
12900   /// their location info for delayed diagnostics.
12901   struct MisalignedMember {
12902     Expr *E;
12903     RecordDecl *RD;
12904     ValueDecl *MD;
12905     CharUnits Alignment;
12906 
MisalignedMemberMisalignedMember12907     MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMemberMisalignedMember12908     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12909                      CharUnits Alignment)
12910         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
MisalignedMemberMisalignedMember12911     explicit MisalignedMember(Expr *E)
12912         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12913 
12914     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12915   };
12916   /// Small set of gathered accesses to potentially misaligned members
12917   /// due to the packed attribute.
12918   SmallVector<MisalignedMember, 4> MisalignedMembers;
12919 
12920   /// Adds an expression to the set of gathered misaligned members.
12921   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12922                                      CharUnits Alignment);
12923 
12924 public:
12925   /// Diagnoses the current set of gathered accesses. This typically
12926   /// happens at full expression level. The set is cleared after emitting the
12927   /// diagnostics.
12928   void DiagnoseMisalignedMembers();
12929 
12930   /// This function checks if the expression is in the sef of potentially
12931   /// misaligned members and it is converted to some pointer type T with lower
12932   /// or equal alignment requirements. If so it removes it. This is used when
12933   /// we do not want to diagnose such misaligned access (e.g. in conversions to
12934   /// void*).
12935   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
12936 
12937   /// This function calls Action when it determines that E designates a
12938   /// misaligned member due to the packed attribute. This is used to emit
12939   /// local diagnostics like in reference binding.
12940   void RefersToMemberWithReducedAlignment(
12941       Expr *E,
12942       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12943           Action);
12944 
12945   /// Describes the reason a calling convention specification was ignored, used
12946   /// for diagnostics.
12947   enum class CallingConventionIgnoredReason {
12948     ForThisTarget = 0,
12949     VariadicFunction,
12950     ConstructorDestructor,
12951     BuiltinFunction
12952   };
12953   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12954   /// context is "used as device code".
12955   ///
12956   /// - If CurLexicalContext is a kernel function or it is known that the
12957   ///   function will be emitted for the device, emits the diagnostics
12958   ///   immediately.
12959   /// - If CurLexicalContext is a function and we are compiling
12960   ///   for the device, but we don't know that this function will be codegen'ed
12961   ///   for devive yet, creates a diagnostic which is emitted if and when we
12962   ///   realize that the function will be codegen'ed.
12963   ///
12964   /// Example usage:
12965   ///
12966   /// Diagnose __float128 type usage only from SYCL device code if the current
12967   /// target doesn't support it
12968   /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
12969   ///     S.getLangOpts().SYCLIsDevice)
12970   ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
12971   SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
12972                                              unsigned DiagID);
12973 
12974   /// Check whether we're allowed to call Callee from the current context.
12975   ///
12976   /// - If the call is never allowed in a semantically-correct program
12977   ///   emits an error and returns false.
12978   ///
12979   /// - If the call is allowed in semantically-correct programs, but only if
12980   ///   it's never codegen'ed, creates a deferred diagnostic to be emitted if
12981   ///   and when the caller is codegen'ed, and returns true.
12982   ///
12983   /// - Otherwise, returns true without emitting any diagnostics.
12984   ///
12985   /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
12986   /// codegen'ed yet.
12987   bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
12988 };
12989 
12990 /// RAII object that enters a new expression evaluation context.
12991 class EnterExpressionEvaluationContext {
12992   Sema &Actions;
12993   bool Entered = true;
12994 
12995 public:
12996   EnterExpressionEvaluationContext(
12997       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12998       Decl *LambdaContextDecl = nullptr,
12999       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13000           Sema::ExpressionEvaluationContextRecord::EK_Other,
13001       bool ShouldEnter = true)
Actions(Actions)13002       : Actions(Actions), Entered(ShouldEnter) {
13003     if (Entered)
13004       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
13005                                               ExprContext);
13006   }
13007   EnterExpressionEvaluationContext(
13008       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13009       Sema::ReuseLambdaContextDecl_t,
13010       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13011           Sema::ExpressionEvaluationContextRecord::EK_Other)
Actions(Actions)13012       : Actions(Actions) {
13013     Actions.PushExpressionEvaluationContext(
13014         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
13015   }
13016 
13017   enum InitListTag { InitList };
13018   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
13019                                    bool ShouldEnter = true)
Actions(Actions)13020       : Actions(Actions), Entered(false) {
13021     // In C++11 onwards, narrowing checks are performed on the contents of
13022     // braced-init-lists, even when they occur within unevaluated operands.
13023     // Therefore we still need to instantiate constexpr functions used in such
13024     // a context.
13025     if (ShouldEnter && Actions.isUnevaluatedContext() &&
13026         Actions.getLangOpts().CPlusPlus11) {
13027       Actions.PushExpressionEvaluationContext(
13028           Sema::ExpressionEvaluationContext::UnevaluatedList);
13029       Entered = true;
13030     }
13031   }
13032 
~EnterExpressionEvaluationContext()13033   ~EnterExpressionEvaluationContext() {
13034     if (Entered)
13035       Actions.PopExpressionEvaluationContext();
13036   }
13037 };
13038 
13039 DeductionFailureInfo
13040 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
13041                          sema::TemplateDeductionInfo &Info);
13042 
13043 /// Contains a late templated function.
13044 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
13045 struct LateParsedTemplate {
13046   CachedTokens Toks;
13047   /// The template function declaration to be late parsed.
13048   Decl *D;
13049 };
13050 
13051 template <>
13052 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
13053                                                  PragmaMsStackAction Action,
13054                                                  llvm::StringRef StackSlotLabel,
13055                                                  AlignPackInfo Value);
13056 
13057 } // end namespace clang
13058 
13059 namespace llvm {
13060 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
13061 // SourceLocation.
13062 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
13063   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
13064   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
13065 
13066   static FunctionDeclAndLoc getEmptyKey() {
13067     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
13068   }
13069 
13070   static FunctionDeclAndLoc getTombstoneKey() {
13071     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
13072   }
13073 
13074   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
13075     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
13076                         FDL.Loc.getHashValue());
13077   }
13078 
13079   static bool isEqual(const FunctionDeclAndLoc &LHS,
13080                       const FunctionDeclAndLoc &RHS) {
13081     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
13082   }
13083 };
13084 } // namespace llvm
13085 
13086 #endif
13087