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/TypeLoc.h"
36 #include "clang/AST/TypeOrdering.h"
37 #include "clang/Basic/BitmaskEnum.h"
38 #include "clang/Basic/ExpressionTraits.h"
39 #include "clang/Basic/Module.h"
40 #include "clang/Basic/OpenCLOptions.h"
41 #include "clang/Basic/OpenMPKinds.h"
42 #include "clang/Basic/PragmaKinds.h"
43 #include "clang/Basic/Specifiers.h"
44 #include "clang/Basic/TemplateKinds.h"
45 #include "clang/Basic/TypeTraits.h"
46 #include "clang/Sema/AnalysisBasedWarnings.h"
47 #include "clang/Sema/CleanupInfo.h"
48 #include "clang/Sema/DeclSpec.h"
49 #include "clang/Sema/ExternalSemaSource.h"
50 #include "clang/Sema/IdentifierResolver.h"
51 #include "clang/Sema/ObjCMethodList.h"
52 #include "clang/Sema/Ownership.h"
53 #include "clang/Sema/Scope.h"
54 #include "clang/Sema/SemaConcept.h"
55 #include "clang/Sema/TypoCorrection.h"
56 #include "clang/Sema/Weak.h"
57 #include "llvm/ADT/ArrayRef.h"
58 #include "llvm/ADT/Optional.h"
59 #include "llvm/ADT/SetVector.h"
60 #include "llvm/ADT/SmallBitVector.h"
61 #include "llvm/ADT/SmallSet.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/TinyPtrVector.h"
65 #include "llvm/Frontend/OpenMP/OMPConstants.h"
66 #include <deque>
67 #include <memory>
68 #include <string>
69 #include <tuple>
70 #include <vector>
71 
72 namespace llvm {
73   class APSInt;
74   template <typename ValueT> struct DenseMapInfo;
75   template <typename ValueT, typename ValueInfoT> class DenseSet;
76   class SmallBitVector;
77   struct InlineAsmIdentifierInfo;
78 }
79 
80 namespace clang {
81   class ADLResult;
82   class ASTConsumer;
83   class ASTContext;
84   class ASTMutationListener;
85   class ASTReader;
86   class ASTWriter;
87   class ArrayType;
88   class ParsedAttr;
89   class BindingDecl;
90   class BlockDecl;
91   class CapturedDecl;
92   class CXXBasePath;
93   class CXXBasePaths;
94   class CXXBindTemporaryExpr;
95   typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
96   class CXXConstructorDecl;
97   class CXXConversionDecl;
98   class CXXDeleteExpr;
99   class CXXDestructorDecl;
100   class CXXFieldCollector;
101   class CXXMemberCallExpr;
102   class CXXMethodDecl;
103   class CXXScopeSpec;
104   class CXXTemporary;
105   class CXXTryStmt;
106   class CallExpr;
107   class ClassTemplateDecl;
108   class ClassTemplatePartialSpecializationDecl;
109   class ClassTemplateSpecializationDecl;
110   class VarTemplatePartialSpecializationDecl;
111   class CodeCompleteConsumer;
112   class CodeCompletionAllocator;
113   class CodeCompletionTUInfo;
114   class CodeCompletionResult;
115   class CoroutineBodyStmt;
116   class Decl;
117   class DeclAccessPair;
118   class DeclContext;
119   class DeclRefExpr;
120   class DeclaratorDecl;
121   class DeducedTemplateArgument;
122   class DependentDiagnostic;
123   class DesignatedInitExpr;
124   class Designation;
125   class EnableIfAttr;
126   class EnumConstantDecl;
127   class Expr;
128   class ExtVectorType;
129   class FormatAttr;
130   class FriendDecl;
131   class FunctionDecl;
132   class FunctionProtoType;
133   class FunctionTemplateDecl;
134   class ImplicitConversionSequence;
135   typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
136   class InitListExpr;
137   class InitializationKind;
138   class InitializationSequence;
139   class InitializedEntity;
140   class IntegerLiteral;
141   class LabelStmt;
142   class LambdaExpr;
143   class LangOptions;
144   class LocalInstantiationScope;
145   class LookupResult;
146   class MacroInfo;
147   typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
148   class ModuleLoader;
149   class MultiLevelTemplateArgumentList;
150   class NamedDecl;
151   class ObjCCategoryDecl;
152   class ObjCCategoryImplDecl;
153   class ObjCCompatibleAliasDecl;
154   class ObjCContainerDecl;
155   class ObjCImplDecl;
156   class ObjCImplementationDecl;
157   class ObjCInterfaceDecl;
158   class ObjCIvarDecl;
159   template <class T> class ObjCList;
160   class ObjCMessageExpr;
161   class ObjCMethodDecl;
162   class ObjCPropertyDecl;
163   class ObjCProtocolDecl;
164   class OMPThreadPrivateDecl;
165   class OMPRequiresDecl;
166   class OMPDeclareReductionDecl;
167   class OMPDeclareSimdDecl;
168   class OMPClause;
169   struct OMPVarListLocTy;
170   struct OverloadCandidate;
171   enum class OverloadCandidateParamOrder : char;
172   enum OverloadCandidateRewriteKind : unsigned;
173   class OverloadCandidateSet;
174   class OverloadExpr;
175   class ParenListExpr;
176   class ParmVarDecl;
177   class Preprocessor;
178   class PseudoDestructorTypeStorage;
179   class PseudoObjectExpr;
180   class QualType;
181   class StandardConversionSequence;
182   class Stmt;
183   class StringLiteral;
184   class SwitchStmt;
185   class TemplateArgument;
186   class TemplateArgumentList;
187   class TemplateArgumentLoc;
188   class TemplateDecl;
189   class TemplateInstantiationCallback;
190   class TemplateParameterList;
191   class TemplatePartialOrderingContext;
192   class TemplateTemplateParmDecl;
193   class Token;
194   class TypeAliasDecl;
195   class TypedefDecl;
196   class TypedefNameDecl;
197   class TypeLoc;
198   class TypoCorrectionConsumer;
199   class UnqualifiedId;
200   class UnresolvedLookupExpr;
201   class UnresolvedMemberExpr;
202   class UnresolvedSetImpl;
203   class UnresolvedSetIterator;
204   class UsingDecl;
205   class UsingShadowDecl;
206   class ValueDecl;
207   class VarDecl;
208   class VarTemplateSpecializationDecl;
209   class VisibilityAttr;
210   class VisibleDeclConsumer;
211   class IndirectFieldDecl;
212   struct DeductionFailureInfo;
213   class TemplateSpecCandidateSet;
214 
215 namespace sema {
216   class AccessedEntity;
217   class BlockScopeInfo;
218   class Capture;
219   class CapturedRegionScopeInfo;
220   class CapturingScopeInfo;
221   class CompoundScopeInfo;
222   class DelayedDiagnostic;
223   class DelayedDiagnosticPool;
224   class FunctionScopeInfo;
225   class LambdaScopeInfo;
226   class PossiblyUnreachableDiag;
227   class SemaPPCallbacks;
228   class TemplateDeductionInfo;
229 }
230 
231 namespace threadSafety {
232   class BeforeSet;
233   void threadSafetyCleanup(BeforeSet* Cache);
234 }
235 
236 // FIXME: No way to easily map from TemplateTypeParmTypes to
237 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
238 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
239                   SourceLocation> UnexpandedParameterPack;
240 
241 /// Describes whether we've seen any nullability information for the given
242 /// file.
243 struct FileNullability {
244   /// The first pointer declarator (of any pointer kind) in the file that does
245   /// not have a corresponding nullability annotation.
246   SourceLocation PointerLoc;
247 
248   /// The end location for the first pointer declarator in the file. Used for
249   /// placing fix-its.
250   SourceLocation PointerEndLoc;
251 
252   /// Which kind of pointer declarator we saw.
253   uint8_t PointerKind;
254 
255   /// Whether we saw any type nullability annotations in the given file.
256   bool SawTypeNullability = false;
257 };
258 
259 /// A mapping from file IDs to a record of whether we've seen nullability
260 /// information in that file.
261 class FileNullabilityMap {
262   /// A mapping from file IDs to the nullability information for each file ID.
263   llvm::DenseMap<FileID, FileNullability> Map;
264 
265   /// A single-element cache based on the file ID.
266   struct {
267     FileID File;
268     FileNullability Nullability;
269   } Cache;
270 
271 public:
272   FileNullability &operator[](FileID file) {
273     // Check the single-element cache.
274     if (file == Cache.File)
275       return Cache.Nullability;
276 
277     // It's not in the single-element cache; flush the cache if we have one.
278     if (!Cache.File.isInvalid()) {
279       Map[Cache.File] = Cache.Nullability;
280     }
281 
282     // Pull this entry into the cache.
283     Cache.File = file;
284     Cache.Nullability = Map[file];
285     return Cache.Nullability;
286   }
287 };
288 
289 /// Keeps track of expected type during expression parsing. The type is tied to
290 /// a particular token, all functions that update or consume the type take a
291 /// start location of the token they are looking at as a parameter. This allows
292 /// to avoid updating the type on hot paths in the parser.
293 class PreferredTypeBuilder {
294 public:
295   PreferredTypeBuilder() = default;
PreferredTypeBuilder(QualType Type)296   explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
297 
298   void enterCondition(Sema &S, SourceLocation Tok);
299   void enterReturn(Sema &S, SourceLocation Tok);
300   void enterVariableInit(SourceLocation Tok, Decl *D);
301   /// Computing a type for the function argument may require running
302   /// overloading, so we postpone its computation until it is actually needed.
303   ///
304   /// Clients should be very careful when using this funciton, as it stores a
305   /// function_ref, clients should make sure all calls to get() with the same
306   /// location happen while function_ref is alive.
307   void enterFunctionArgument(SourceLocation Tok,
308                              llvm::function_ref<QualType()> ComputeType);
309 
310   void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
311   void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
312                   SourceLocation OpLoc);
313   void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
314   void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
315   void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
316   /// Handles all type casts, including C-style cast, C++ casts, etc.
317   void enterTypeCast(SourceLocation Tok, QualType CastType);
318 
get(SourceLocation Tok)319   QualType get(SourceLocation Tok) const {
320     if (Tok != ExpectedLoc)
321       return QualType();
322     if (!Type.isNull())
323       return Type;
324     if (ComputeType)
325       return ComputeType();
326     return QualType();
327   }
328 
329 private:
330   /// Start position of a token for which we store expected type.
331   SourceLocation ExpectedLoc;
332   /// Expected type for a token starting at ExpectedLoc.
333   QualType Type;
334   /// A function to compute expected type at ExpectedLoc. It is only considered
335   /// if Type is null.
336   llvm::function_ref<QualType()> ComputeType;
337 };
338 
339 /// Sema - This implements semantic analysis and AST building for C.
340 class Sema final {
341   Sema(const Sema &) = delete;
342   void operator=(const Sema &) = delete;
343 
344   /// A key method to reduce duplicate debug info from Sema.
345   virtual void anchor();
346 
347   ///Source of additional semantic information.
348   ExternalSemaSource *ExternalSource;
349 
350   ///Whether Sema has generated a multiplexer and has to delete it.
351   bool isMultiplexExternalSource;
352 
353   static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
354 
355   bool isVisibleSlow(const NamedDecl *D);
356 
357   /// Determine whether two declarations should be linked together, given that
358   /// the old declaration might not be visible and the new declaration might
359   /// not have external linkage.
shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)360   bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
361                                     const NamedDecl *New) {
362     if (isVisible(Old))
363      return true;
364     // See comment in below overload for why it's safe to compute the linkage
365     // of the new declaration here.
366     if (New->isExternallyDeclarable()) {
367       assert(Old->isExternallyDeclarable() &&
368              "should not have found a non-externally-declarable previous decl");
369       return true;
370     }
371     return false;
372   }
373   bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
374 
375   void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
376                                       QualType ResultTy,
377                                       ArrayRef<QualType> Args);
378 
379 public:
380   /// The maximum alignment, same as in llvm::Value. We duplicate them here
381   /// because that allows us not to duplicate the constants in clang code,
382   /// which we must to since we can't directly use the llvm constants.
383   /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
384   ///
385   /// This is the greatest alignment value supported by load, store, and alloca
386   /// instructions, and global values.
387   static const unsigned MaxAlignmentExponent = 29;
388   static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
389 
390   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
391   typedef OpaquePtr<TemplateName> TemplateTy;
392   typedef OpaquePtr<QualType> TypeTy;
393 
394   OpenCLOptions OpenCLFeatures;
395   FPOptions CurFPFeatures;
396 
397   const LangOptions &LangOpts;
398   Preprocessor &PP;
399   ASTContext &Context;
400   ASTConsumer &Consumer;
401   DiagnosticsEngine &Diags;
402   SourceManager &SourceMgr;
403 
404   /// Flag indicating whether or not to collect detailed statistics.
405   bool CollectStats;
406 
407   /// Code-completion consumer.
408   CodeCompleteConsumer *CodeCompleter;
409 
410   /// CurContext - This is the current declaration context of parsing.
411   DeclContext *CurContext;
412 
413   /// Generally null except when we temporarily switch decl contexts,
414   /// like in \see ActOnObjCTemporaryExitContainerContext.
415   DeclContext *OriginalLexicalContext;
416 
417   /// VAListTagName - The declaration name corresponding to __va_list_tag.
418   /// This is used as part of a hack to omit that class from ADL results.
419   DeclarationName VAListTagName;
420 
421   bool MSStructPragmaOn; // True when \#pragma ms_struct on
422 
423   /// Controls member pointer representation format under the MS ABI.
424   LangOptions::PragmaMSPointersToMembersKind
425       MSPointerToMemberRepresentationMethod;
426 
427   /// Stack of active SEH __finally scopes.  Can be empty.
428   SmallVector<Scope*, 2> CurrentSEHFinally;
429 
430   /// Source location for newly created implicit MSInheritanceAttrs
431   SourceLocation ImplicitMSInheritanceAttrLoc;
432 
433   /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
434   /// `TransformTypos` in order to keep track of any TypoExprs that are created
435   /// recursively during typo correction and wipe them away if the correction
436   /// fails.
437   llvm::SmallVector<TypoExpr *, 2> TypoExprs;
438 
439   /// pragma clang section kind
440   enum PragmaClangSectionKind {
441     PCSK_Invalid      = 0,
442     PCSK_BSS          = 1,
443     PCSK_Data         = 2,
444     PCSK_Rodata       = 3,
445     PCSK_Text         = 4,
446     PCSK_Relro        = 5
447    };
448 
449   enum PragmaClangSectionAction {
450     PCSA_Set     = 0,
451     PCSA_Clear   = 1
452   };
453 
454   struct PragmaClangSection {
455     std::string SectionName;
456     bool Valid = false;
457     SourceLocation PragmaLocation;
458 
459     void Act(SourceLocation PragmaLocation,
460              PragmaClangSectionAction Action,
461              StringLiteral* Name);
462    };
463 
464    PragmaClangSection PragmaClangBSSSection;
465    PragmaClangSection PragmaClangDataSection;
466    PragmaClangSection PragmaClangRodataSection;
467    PragmaClangSection PragmaClangRelroSection;
468    PragmaClangSection PragmaClangTextSection;
469 
470   enum PragmaMsStackAction {
471     PSK_Reset     = 0x0,                // #pragma ()
472     PSK_Set       = 0x1,                // #pragma (value)
473     PSK_Push      = 0x2,                // #pragma (push[, id])
474     PSK_Pop       = 0x4,                // #pragma (pop[, id])
475     PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
476     PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
477     PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
478   };
479 
480   template<typename ValueType>
481   struct PragmaStack {
482     struct Slot {
483       llvm::StringRef StackSlotLabel;
484       ValueType Value;
485       SourceLocation PragmaLocation;
486       SourceLocation PragmaPushLocation;
SlotPragmaStack::Slot487       Slot(llvm::StringRef StackSlotLabel, ValueType Value,
488            SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
489           : StackSlotLabel(StackSlotLabel), Value(Value),
490             PragmaLocation(PragmaLocation),
491             PragmaPushLocation(PragmaPushLocation) {}
492     };
493 
ActPragmaStack494     void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
495              llvm::StringRef StackSlotLabel, ValueType Value) {
496       if (Action == PSK_Reset) {
497         CurrentValue = DefaultValue;
498         CurrentPragmaLocation = PragmaLocation;
499         return;
500       }
501       if (Action & PSK_Push)
502         Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
503                            PragmaLocation);
504       else if (Action & PSK_Pop) {
505         if (!StackSlotLabel.empty()) {
506           // If we've got a label, try to find it and jump there.
507           auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
508             return x.StackSlotLabel == StackSlotLabel;
509           });
510           // If we found the label so pop from there.
511           if (I != Stack.rend()) {
512             CurrentValue = I->Value;
513             CurrentPragmaLocation = I->PragmaLocation;
514             Stack.erase(std::prev(I.base()), Stack.end());
515           }
516         } else if (!Stack.empty()) {
517           // We do not have a label, just pop the last entry.
518           CurrentValue = Stack.back().Value;
519           CurrentPragmaLocation = Stack.back().PragmaLocation;
520           Stack.pop_back();
521         }
522       }
523       if (Action & PSK_Set) {
524         CurrentValue = Value;
525         CurrentPragmaLocation = PragmaLocation;
526       }
527     }
528 
529     // MSVC seems to add artificial slots to #pragma stacks on entering a C++
530     // method body to restore the stacks on exit, so it works like this:
531     //
532     //   struct S {
533     //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
534     //     void Method {}
535     //     #pragma <name>(pop, InternalPragmaSlot)
536     //   };
537     //
538     // It works even with #pragma vtordisp, although MSVC doesn't support
539     //   #pragma vtordisp(push [, id], n)
540     // syntax.
541     //
542     // Push / pop a named sentinel slot.
SentinelActionPragmaStack543     void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
544       assert((Action == PSK_Push || Action == PSK_Pop) &&
545              "Can only push / pop #pragma stack sentinels!");
546       Act(CurrentPragmaLocation, Action, Label, CurrentValue);
547     }
548 
549     // Constructors.
PragmaStackPragmaStack550     explicit PragmaStack(const ValueType &Default)
551         : DefaultValue(Default), CurrentValue(Default) {}
552 
hasValuePragmaStack553     bool hasValue() const { return CurrentValue != DefaultValue; }
554 
555     SmallVector<Slot, 2> Stack;
556     ValueType DefaultValue; // Value used for PSK_Reset action.
557     ValueType CurrentValue;
558     SourceLocation CurrentPragmaLocation;
559   };
560   // FIXME: We should serialize / deserialize these if they occur in a PCH (but
561   // we shouldn't do so if they're in a module).
562 
563   /// Whether to insert vtordisps prior to virtual bases in the Microsoft
564   /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
565   ///
566   /// 0: Suppress all vtordisps
567   /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
568   ///    structors
569   /// 2: Always insert vtordisps to support RTTI on partially constructed
570   ///    objects
571   PragmaStack<MSVtorDispMode> VtorDispStack;
572   // #pragma pack.
573   // Sentinel to represent when the stack is set to mac68k alignment.
574   static const unsigned kMac68kAlignmentSentinel = ~0U;
575   PragmaStack<unsigned> PackStack;
576   // The current #pragma pack values and locations at each #include.
577   struct PackIncludeState {
578     unsigned CurrentValue;
579     SourceLocation CurrentPragmaLocation;
580     bool HasNonDefaultValue, ShouldWarnOnInclude;
581   };
582   SmallVector<PackIncludeState, 8> PackIncludeStack;
583   // Segment #pragmas.
584   PragmaStack<StringLiteral *> DataSegStack;
585   PragmaStack<StringLiteral *> BSSSegStack;
586   PragmaStack<StringLiteral *> ConstSegStack;
587   PragmaStack<StringLiteral *> CodeSegStack;
588 
589   // This stack tracks the current state of Sema.CurFPFeatures.
590   PragmaStack<FPOptionsOverride> FpPragmaStack;
CurFPFeatureOverrides()591   FPOptionsOverride CurFPFeatureOverrides() {
592     FPOptionsOverride result;
593     if (!FpPragmaStack.hasValue()) {
594       result = FPOptionsOverride();
595     } else {
596       result = FpPragmaStack.CurrentValue;
597     }
598     return result;
599   }
600 
601   // RAII object to push / pop sentinel slots for all MS #pragma stacks.
602   // Actions should be performed only if we enter / exit a C++ method body.
603   class PragmaStackSentinelRAII {
604   public:
605     PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
606     ~PragmaStackSentinelRAII();
607 
608   private:
609     Sema &S;
610     StringRef SlotLabel;
611     bool ShouldAct;
612   };
613 
614   /// A mapping that describes the nullability we've seen in each header file.
615   FileNullabilityMap NullabilityMap;
616 
617   /// Last section used with #pragma init_seg.
618   StringLiteral *CurInitSeg;
619   SourceLocation CurInitSegLoc;
620 
621   /// VisContext - Manages the stack for \#pragma GCC visibility.
622   void *VisContext; // Really a "PragmaVisStack*"
623 
624   /// This an attribute introduced by \#pragma clang attribute.
625   struct PragmaAttributeEntry {
626     SourceLocation Loc;
627     ParsedAttr *Attribute;
628     SmallVector<attr::SubjectMatchRule, 4> MatchRules;
629     bool IsUsed;
630   };
631 
632   /// A push'd group of PragmaAttributeEntries.
633   struct PragmaAttributeGroup {
634     /// The location of the push attribute.
635     SourceLocation Loc;
636     /// The namespace of this push group.
637     const IdentifierInfo *Namespace;
638     SmallVector<PragmaAttributeEntry, 2> Entries;
639   };
640 
641   SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
642 
643   /// The declaration that is currently receiving an attribute from the
644   /// #pragma attribute stack.
645   const Decl *PragmaAttributeCurrentTargetDecl;
646 
647   /// This represents the last location of a "#pragma clang optimize off"
648   /// directive if such a directive has not been closed by an "on" yet. If
649   /// optimizations are currently "on", this is set to an invalid location.
650   SourceLocation OptimizeOffPragmaLocation;
651 
652   /// Flag indicating if Sema is building a recovery call expression.
653   ///
654   /// This flag is used to avoid building recovery call expressions
655   /// if Sema is already doing so, which would cause infinite recursions.
656   bool IsBuildingRecoveryCallExpr;
657 
658   /// Used to control the generation of ExprWithCleanups.
659   CleanupInfo Cleanup;
660 
661   /// ExprCleanupObjects - This is the stack of objects requiring
662   /// cleanup that are created by the current full expression.
663   SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
664 
665   /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
666   /// to a variable (constant) that may or may not be odr-used in this Expr, and
667   /// we won't know until all lvalue-to-rvalue and discarded value conversions
668   /// have been applied to all subexpressions of the enclosing full expression.
669   /// This is cleared at the end of each full expression.
670   using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
671                                              llvm::SmallPtrSet<Expr *, 4>>;
672   MaybeODRUseExprSet MaybeODRUseExprs;
673 
674   std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
675 
676   /// Stack containing information about each of the nested
677   /// function, block, and method scopes that are currently active.
678   SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
679 
680   /// The index of the first FunctionScope that corresponds to the current
681   /// context.
682   unsigned FunctionScopesStart = 0;
683 
getFunctionScopes()684   ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
685     return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
686                               FunctionScopes.end());
687   }
688 
689   /// Stack containing information needed when in C++2a an 'auto' is encountered
690   /// in a function declaration parameter type specifier in order to invent a
691   /// corresponding template parameter in the enclosing abbreviated function
692   /// template. This information is also present in LambdaScopeInfo, stored in
693   /// the FunctionScopes stack.
694   SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
695 
696   /// The index of the first InventedParameterInfo that refers to the current
697   /// context.
698   unsigned InventedParameterInfosStart = 0;
699 
getInventedParameterInfos()700   ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
701     return llvm::makeArrayRef(InventedParameterInfos.begin() +
702                                   InventedParameterInfosStart,
703                               InventedParameterInfos.end());
704   }
705 
706   typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
707                      &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
708     ExtVectorDeclsType;
709 
710   /// ExtVectorDecls - This is a list all the extended vector types. This allows
711   /// us to associate a raw vector type with one of the ext_vector type names.
712   /// This is only necessary for issuing pretty diagnostics.
713   ExtVectorDeclsType ExtVectorDecls;
714 
715   /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
716   std::unique_ptr<CXXFieldCollector> FieldCollector;
717 
718   typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
719 
720   /// Set containing all declared private fields that are not used.
721   NamedDeclSetType UnusedPrivateFields;
722 
723   /// Set containing all typedefs that are likely unused.
724   llvm::SmallSetVector<const TypedefNameDecl *, 4>
725       UnusedLocalTypedefNameCandidates;
726 
727   /// Delete-expressions to be analyzed at the end of translation unit
728   ///
729   /// This list contains class members, and locations of delete-expressions
730   /// that could not be proven as to whether they mismatch with new-expression
731   /// used in initializer of the field.
732   typedef std::pair<SourceLocation, bool> DeleteExprLoc;
733   typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
734   llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
735 
736   typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
737 
738   /// PureVirtualClassDiagSet - a set of class declarations which we have
739   /// emitted a list of pure virtual functions. Used to prevent emitting the
740   /// same list more than once.
741   std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
742 
743   /// ParsingInitForAutoVars - a set of declarations with auto types for which
744   /// we are currently parsing the initializer.
745   llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
746 
747   /// Look for a locally scoped extern "C" declaration by the given name.
748   NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
749 
750   typedef LazyVector<VarDecl *, ExternalSemaSource,
751                      &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
752     TentativeDefinitionsType;
753 
754   /// All the tentative definitions encountered in the TU.
755   TentativeDefinitionsType TentativeDefinitions;
756 
757   /// All the external declarations encoutered and used in the TU.
758   SmallVector<VarDecl *, 4> ExternalDeclarations;
759 
760   typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
761                      &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
762     UnusedFileScopedDeclsType;
763 
764   /// The set of file scoped decls seen so far that have not been used
765   /// and must warn if not used. Only contains the first declaration.
766   UnusedFileScopedDeclsType UnusedFileScopedDecls;
767 
768   typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
769                      &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
770     DelegatingCtorDeclsType;
771 
772   /// All the delegating constructors seen so far in the file, used for
773   /// cycle detection at the end of the TU.
774   DelegatingCtorDeclsType DelegatingCtorDecls;
775 
776   /// All the overriding functions seen during a class definition
777   /// that had their exception spec checks delayed, plus the overridden
778   /// function.
779   SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
780     DelayedOverridingExceptionSpecChecks;
781 
782   /// All the function redeclarations seen during a class definition that had
783   /// their exception spec checks delayed, plus the prior declaration they
784   /// should be checked against. Except during error recovery, the new decl
785   /// should always be a friend declaration, as that's the only valid way to
786   /// redeclare a special member before its class is complete.
787   SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
788     DelayedEquivalentExceptionSpecChecks;
789 
790   typedef llvm::MapVector<const FunctionDecl *,
791                           std::unique_ptr<LateParsedTemplate>>
792       LateParsedTemplateMapT;
793   LateParsedTemplateMapT LateParsedTemplateMap;
794 
795   /// Callback to the parser to parse templated functions when needed.
796   typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
797   typedef void LateTemplateParserCleanupCB(void *P);
798   LateTemplateParserCB *LateTemplateParser;
799   LateTemplateParserCleanupCB *LateTemplateParserCleanup;
800   void *OpaqueParser;
801 
SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)802   void SetLateTemplateParser(LateTemplateParserCB *LTP,
803                              LateTemplateParserCleanupCB *LTPCleanup,
804                              void *P) {
805     LateTemplateParser = LTP;
806     LateTemplateParserCleanup = LTPCleanup;
807     OpaqueParser = P;
808   }
809 
810   class DelayedDiagnostics;
811 
812   class DelayedDiagnosticsState {
813     sema::DelayedDiagnosticPool *SavedPool;
814     friend class Sema::DelayedDiagnostics;
815   };
816   typedef DelayedDiagnosticsState ParsingDeclState;
817   typedef DelayedDiagnosticsState ProcessingContextState;
818 
819   /// A class which encapsulates the logic for delaying diagnostics
820   /// during parsing and other processing.
821   class DelayedDiagnostics {
822     /// The current pool of diagnostics into which delayed
823     /// diagnostics should go.
824     sema::DelayedDiagnosticPool *CurPool;
825 
826   public:
DelayedDiagnostics()827     DelayedDiagnostics() : CurPool(nullptr) {}
828 
829     /// Adds a delayed diagnostic.
830     void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
831 
832     /// Determines whether diagnostics should be delayed.
shouldDelayDiagnostics()833     bool shouldDelayDiagnostics() { return CurPool != nullptr; }
834 
835     /// Returns the current delayed-diagnostics pool.
getCurrentPool()836     sema::DelayedDiagnosticPool *getCurrentPool() const {
837       return CurPool;
838     }
839 
840     /// Enter a new scope.  Access and deprecation diagnostics will be
841     /// collected in this pool.
push(sema::DelayedDiagnosticPool & pool)842     DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
843       DelayedDiagnosticsState state;
844       state.SavedPool = CurPool;
845       CurPool = &pool;
846       return state;
847     }
848 
849     /// Leave a delayed-diagnostic state that was previously pushed.
850     /// Do not emit any of the diagnostics.  This is performed as part
851     /// of the bookkeeping of popping a pool "properly".
popWithoutEmitting(DelayedDiagnosticsState state)852     void popWithoutEmitting(DelayedDiagnosticsState state) {
853       CurPool = state.SavedPool;
854     }
855 
856     /// Enter a new scope where access and deprecation diagnostics are
857     /// not delayed.
pushUndelayed()858     DelayedDiagnosticsState pushUndelayed() {
859       DelayedDiagnosticsState state;
860       state.SavedPool = CurPool;
861       CurPool = nullptr;
862       return state;
863     }
864 
865     /// Undo a previous pushUndelayed().
popUndelayed(DelayedDiagnosticsState state)866     void popUndelayed(DelayedDiagnosticsState state) {
867       assert(CurPool == nullptr);
868       CurPool = state.SavedPool;
869     }
870   } DelayedDiagnostics;
871 
872   /// A RAII object to temporarily push a declaration context.
873   class ContextRAII {
874   private:
875     Sema &S;
876     DeclContext *SavedContext;
877     ProcessingContextState SavedContextState;
878     QualType SavedCXXThisTypeOverride;
879     unsigned SavedFunctionScopesStart;
880     unsigned SavedInventedParameterInfosStart;
881 
882   public:
883     ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
S(S)884       : S(S), SavedContext(S.CurContext),
885         SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
886         SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
887         SavedFunctionScopesStart(S.FunctionScopesStart),
888         SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
889     {
890       assert(ContextToPush && "pushing null context");
891       S.CurContext = ContextToPush;
892       if (NewThisContext)
893         S.CXXThisTypeOverride = QualType();
894       // Any saved FunctionScopes do not refer to this context.
895       S.FunctionScopesStart = S.FunctionScopes.size();
896       S.InventedParameterInfosStart = S.InventedParameterInfos.size();
897     }
898 
pop()899     void pop() {
900       if (!SavedContext) return;
901       S.CurContext = SavedContext;
902       S.DelayedDiagnostics.popUndelayed(SavedContextState);
903       S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
904       S.FunctionScopesStart = SavedFunctionScopesStart;
905       S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
906       SavedContext = nullptr;
907     }
908 
~ContextRAII()909     ~ContextRAII() {
910       pop();
911     }
912   };
913 
914   /// Whether the AST is currently being rebuilt to correct immediate
915   /// invocations. Immediate invocation candidates and references to consteval
916   /// functions aren't tracked when this is set.
917   bool RebuildingImmediateInvocation = false;
918 
919   /// Used to change context to isConstantEvaluated without pushing a heavy
920   /// ExpressionEvaluationContextRecord object.
921   bool isConstantEvaluatedOverride;
922 
isConstantEvaluated()923   bool isConstantEvaluated() {
924     return ExprEvalContexts.back().isConstantEvaluated() ||
925            isConstantEvaluatedOverride;
926   }
927 
928   /// RAII object to handle the state changes required to synthesize
929   /// a function body.
930   class SynthesizedFunctionScope {
931     Sema &S;
932     Sema::ContextRAII SavedContext;
933     bool PushedCodeSynthesisContext = false;
934 
935   public:
SynthesizedFunctionScope(Sema & S,DeclContext * DC)936     SynthesizedFunctionScope(Sema &S, DeclContext *DC)
937         : S(S), SavedContext(S, DC) {
938       S.PushFunctionScope();
939       S.PushExpressionEvaluationContext(
940           Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
941       if (auto *FD = dyn_cast<FunctionDecl>(DC))
942         FD->setWillHaveBody(true);
943       else
944         assert(isa<ObjCMethodDecl>(DC));
945     }
946 
addContextNote(SourceLocation UseLoc)947     void addContextNote(SourceLocation UseLoc) {
948       assert(!PushedCodeSynthesisContext);
949 
950       Sema::CodeSynthesisContext Ctx;
951       Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
952       Ctx.PointOfInstantiation = UseLoc;
953       Ctx.Entity = cast<Decl>(S.CurContext);
954       S.pushCodeSynthesisContext(Ctx);
955 
956       PushedCodeSynthesisContext = true;
957     }
958 
~SynthesizedFunctionScope()959     ~SynthesizedFunctionScope() {
960       if (PushedCodeSynthesisContext)
961         S.popCodeSynthesisContext();
962       if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
963         FD->setWillHaveBody(false);
964       S.PopExpressionEvaluationContext();
965       S.PopFunctionScopeInfo();
966     }
967   };
968 
969   /// WeakUndeclaredIdentifiers - Identifiers contained in
970   /// \#pragma weak before declared. rare. may alias another
971   /// identifier, declared or undeclared
972   llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
973 
974   /// ExtnameUndeclaredIdentifiers - Identifiers contained in
975   /// \#pragma redefine_extname before declared.  Used in Solaris system headers
976   /// to define functions that occur in multiple standards to call the version
977   /// in the currently selected standard.
978   llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
979 
980 
981   /// Load weak undeclared identifiers from the external source.
982   void LoadExternalWeakUndeclaredIdentifiers();
983 
984   /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
985   /// \#pragma weak during processing of other Decls.
986   /// I couldn't figure out a clean way to generate these in-line, so
987   /// we store them here and handle separately -- which is a hack.
988   /// It would be best to refactor this.
989   SmallVector<Decl*,2> WeakTopLevelDecl;
990 
991   IdentifierResolver IdResolver;
992 
993   /// Translation Unit Scope - useful to Objective-C actions that need
994   /// to lookup file scope declarations in the "ordinary" C decl namespace.
995   /// For example, user-defined classes, built-in "id" type, etc.
996   Scope *TUScope;
997 
998   /// The C++ "std" namespace, where the standard library resides.
999   LazyDeclPtr StdNamespace;
1000 
1001   /// The C++ "std::bad_alloc" class, which is defined by the C++
1002   /// standard library.
1003   LazyDeclPtr StdBadAlloc;
1004 
1005   /// The C++ "std::align_val_t" enum class, which is defined by the C++
1006   /// standard library.
1007   LazyDeclPtr StdAlignValT;
1008 
1009   /// The C++ "std::experimental" namespace, where the experimental parts
1010   /// of the standard library resides.
1011   NamespaceDecl *StdExperimentalNamespaceCache;
1012 
1013   /// The C++ "std::initializer_list" template, which is defined in
1014   /// \<initializer_list>.
1015   ClassTemplateDecl *StdInitializerList;
1016 
1017   /// The C++ "std::coroutine_traits" template, which is defined in
1018   /// \<coroutine_traits>
1019   ClassTemplateDecl *StdCoroutineTraitsCache;
1020 
1021   /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1022   RecordDecl *CXXTypeInfoDecl;
1023 
1024   /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1025   RecordDecl *MSVCGuidDecl;
1026 
1027   /// Caches identifiers/selectors for NSFoundation APIs.
1028   std::unique_ptr<NSAPI> NSAPIObj;
1029 
1030   /// The declaration of the Objective-C NSNumber class.
1031   ObjCInterfaceDecl *NSNumberDecl;
1032 
1033   /// The declaration of the Objective-C NSValue class.
1034   ObjCInterfaceDecl *NSValueDecl;
1035 
1036   /// Pointer to NSNumber type (NSNumber *).
1037   QualType NSNumberPointer;
1038 
1039   /// Pointer to NSValue type (NSValue *).
1040   QualType NSValuePointer;
1041 
1042   /// The Objective-C NSNumber methods used to create NSNumber literals.
1043   ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1044 
1045   /// The declaration of the Objective-C NSString class.
1046   ObjCInterfaceDecl *NSStringDecl;
1047 
1048   /// Pointer to NSString type (NSString *).
1049   QualType NSStringPointer;
1050 
1051   /// The declaration of the stringWithUTF8String: method.
1052   ObjCMethodDecl *StringWithUTF8StringMethod;
1053 
1054   /// The declaration of the valueWithBytes:objCType: method.
1055   ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1056 
1057   /// The declaration of the Objective-C NSArray class.
1058   ObjCInterfaceDecl *NSArrayDecl;
1059 
1060   /// The declaration of the arrayWithObjects:count: method.
1061   ObjCMethodDecl *ArrayWithObjectsMethod;
1062 
1063   /// The declaration of the Objective-C NSDictionary class.
1064   ObjCInterfaceDecl *NSDictionaryDecl;
1065 
1066   /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1067   ObjCMethodDecl *DictionaryWithObjectsMethod;
1068 
1069   /// id<NSCopying> type.
1070   QualType QIDNSCopying;
1071 
1072   /// will hold 'respondsToSelector:'
1073   Selector RespondsToSelectorSel;
1074 
1075   /// A flag to remember whether the implicit forms of operator new and delete
1076   /// have been declared.
1077   bool GlobalNewDeleteDeclared;
1078 
1079   /// A flag to indicate that we're in a context that permits abstract
1080   /// references to fields.  This is really a
1081   bool AllowAbstractFieldReference;
1082 
1083   /// Describes how the expressions currently being parsed are
1084   /// evaluated at run-time, if at all.
1085   enum class ExpressionEvaluationContext {
1086     /// The current expression and its subexpressions occur within an
1087     /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1088     /// \c sizeof, where the type of the expression may be significant but
1089     /// no code will be generated to evaluate the value of the expression at
1090     /// run time.
1091     Unevaluated,
1092 
1093     /// The current expression occurs within a braced-init-list within
1094     /// an unevaluated operand. This is mostly like a regular unevaluated
1095     /// context, except that we still instantiate constexpr functions that are
1096     /// referenced here so that we can perform narrowing checks correctly.
1097     UnevaluatedList,
1098 
1099     /// The current expression occurs within a discarded statement.
1100     /// This behaves largely similarly to an unevaluated operand in preventing
1101     /// definitions from being required, but not in other ways.
1102     DiscardedStatement,
1103 
1104     /// The current expression occurs within an unevaluated
1105     /// operand that unconditionally permits abstract references to
1106     /// fields, such as a SIZE operator in MS-style inline assembly.
1107     UnevaluatedAbstract,
1108 
1109     /// The current context is "potentially evaluated" in C++11 terms,
1110     /// but the expression is evaluated at compile-time (like the values of
1111     /// cases in a switch statement).
1112     ConstantEvaluated,
1113 
1114     /// The current expression is potentially evaluated at run time,
1115     /// which means that code may be generated to evaluate the value of the
1116     /// expression at run time.
1117     PotentiallyEvaluated,
1118 
1119     /// The current expression is potentially evaluated, but any
1120     /// declarations referenced inside that expression are only used if
1121     /// in fact the current expression is used.
1122     ///
1123     /// This value is used when parsing default function arguments, for which
1124     /// we would like to provide diagnostics (e.g., passing non-POD arguments
1125     /// through varargs) but do not want to mark declarations as "referenced"
1126     /// until the default argument is used.
1127     PotentiallyEvaluatedIfUsed
1128   };
1129 
1130   using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1131 
1132   /// Data structure used to record current or nested
1133   /// expression evaluation contexts.
1134   struct ExpressionEvaluationContextRecord {
1135     /// The expression evaluation context.
1136     ExpressionEvaluationContext Context;
1137 
1138     /// Whether the enclosing context needed a cleanup.
1139     CleanupInfo ParentCleanup;
1140 
1141     /// Whether we are in a decltype expression.
1142     bool IsDecltype;
1143 
1144     /// The number of active cleanup objects when we entered
1145     /// this expression evaluation context.
1146     unsigned NumCleanupObjects;
1147 
1148     /// The number of typos encountered during this expression evaluation
1149     /// context (i.e. the number of TypoExprs created).
1150     unsigned NumTypos;
1151 
1152     MaybeODRUseExprSet SavedMaybeODRUseExprs;
1153 
1154     /// The lambdas that are present within this context, if it
1155     /// is indeed an unevaluated context.
1156     SmallVector<LambdaExpr *, 2> Lambdas;
1157 
1158     /// The declaration that provides context for lambda expressions
1159     /// and block literals if the normal declaration context does not
1160     /// suffice, e.g., in a default function argument.
1161     Decl *ManglingContextDecl;
1162 
1163     /// If we are processing a decltype type, a set of call expressions
1164     /// for which we have deferred checking the completeness of the return type.
1165     SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1166 
1167     /// If we are processing a decltype type, a set of temporary binding
1168     /// expressions for which we have deferred checking the destructor.
1169     SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1170 
1171     llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1172 
1173     /// Expressions appearing as the LHS of a volatile assignment in this
1174     /// context. We produce a warning for these when popping the context if
1175     /// they are not discarded-value expressions nor unevaluated operands.
1176     SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1177 
1178     /// Set of candidates for starting an immediate invocation.
1179     llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1180 
1181     /// Set of DeclRefExprs referencing a consteval function when used in a
1182     /// context not already known to be immediately invoked.
1183     llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1184 
1185     /// \brief Describes whether we are in an expression constext which we have
1186     /// to handle differently.
1187     enum ExpressionKind {
1188       EK_Decltype, EK_TemplateArgument, EK_Other
1189     } ExprContext;
1190 
ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1191     ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1192                                       unsigned NumCleanupObjects,
1193                                       CleanupInfo ParentCleanup,
1194                                       Decl *ManglingContextDecl,
1195                                       ExpressionKind ExprContext)
1196         : Context(Context), ParentCleanup(ParentCleanup),
1197           NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1198           ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
1199 
isUnevaluatedExpressionEvaluationContextRecord1200     bool isUnevaluated() const {
1201       return Context == ExpressionEvaluationContext::Unevaluated ||
1202              Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1203              Context == ExpressionEvaluationContext::UnevaluatedList;
1204     }
isConstantEvaluatedExpressionEvaluationContextRecord1205     bool isConstantEvaluated() const {
1206       return Context == ExpressionEvaluationContext::ConstantEvaluated;
1207     }
1208   };
1209 
1210   /// A stack of expression evaluation contexts.
1211   SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1212 
1213   /// Emit a warning for all pending noderef expressions that we recorded.
1214   void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1215 
1216   /// Compute the mangling number context for a lambda expression or
1217   /// block literal. Also return the extra mangling decl if any.
1218   ///
1219   /// \param DC - The DeclContext containing the lambda expression or
1220   /// block literal.
1221   std::tuple<MangleNumberingContext *, Decl *>
1222   getCurrentMangleNumberContext(const DeclContext *DC);
1223 
1224 
1225   /// SpecialMemberOverloadResult - The overloading result for a special member
1226   /// function.
1227   ///
1228   /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1229   /// integer are used to determine whether overload resolution succeeded.
1230   class SpecialMemberOverloadResult {
1231   public:
1232     enum Kind {
1233       NoMemberOrDeleted,
1234       Ambiguous,
1235       Success
1236     };
1237 
1238   private:
1239     llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1240 
1241   public:
SpecialMemberOverloadResult()1242     SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl * MD)1243     SpecialMemberOverloadResult(CXXMethodDecl *MD)
1244         : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1245 
getMethod()1246     CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
setMethod(CXXMethodDecl * MD)1247     void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1248 
getKind()1249     Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
setKind(Kind K)1250     void setKind(Kind K) { Pair.setInt(K); }
1251   };
1252 
1253   class SpecialMemberOverloadResultEntry
1254       : public llvm::FastFoldingSetNode,
1255         public SpecialMemberOverloadResult {
1256   public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1257     SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1258       : FastFoldingSetNode(ID)
1259     {}
1260   };
1261 
1262   /// A cache of special member function overload resolution results
1263   /// for C++ records.
1264   llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1265 
1266   /// A cache of the flags available in enumerations with the flag_bits
1267   /// attribute.
1268   mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1269 
1270   /// The kind of translation unit we are processing.
1271   ///
1272   /// When we're processing a complete translation unit, Sema will perform
1273   /// end-of-translation-unit semantic tasks (such as creating
1274   /// initializers for tentative definitions in C) once parsing has
1275   /// completed. Modules and precompiled headers perform different kinds of
1276   /// checks.
1277   TranslationUnitKind TUKind;
1278 
1279   llvm::BumpPtrAllocator BumpAlloc;
1280 
1281   /// The number of SFINAE diagnostics that have been trapped.
1282   unsigned NumSFINAEErrors;
1283 
1284   typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1285     UnparsedDefaultArgInstantiationsMap;
1286 
1287   /// A mapping from parameters with unparsed default arguments to the
1288   /// set of instantiations of each parameter.
1289   ///
1290   /// This mapping is a temporary data structure used when parsing
1291   /// nested class templates or nested classes of class templates,
1292   /// where we might end up instantiating an inner class before the
1293   /// default arguments of its methods have been parsed.
1294   UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1295 
1296   // Contains the locations of the beginning of unparsed default
1297   // argument locations.
1298   llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1299 
1300   /// UndefinedInternals - all the used, undefined objects which require a
1301   /// definition in this translation unit.
1302   llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1303 
1304   /// Determine if VD, which must be a variable or function, is an external
1305   /// symbol that nonetheless can't be referenced from outside this translation
1306   /// unit because its type has no linkage and it's not extern "C".
1307   bool isExternalWithNoLinkageType(ValueDecl *VD);
1308 
1309   /// Obtain a sorted list of functions that are undefined but ODR-used.
1310   void getUndefinedButUsed(
1311       SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1312 
1313   /// Retrieves list of suspicious delete-expressions that will be checked at
1314   /// the end of translation unit.
1315   const llvm::MapVector<FieldDecl *, DeleteLocs> &
1316   getMismatchingDeleteExpressions() const;
1317 
1318   typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1319   typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1320 
1321   /// Method Pool - allows efficient lookup when typechecking messages to "id".
1322   /// We need to maintain a list, since selectors can have differing signatures
1323   /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1324   /// of selectors are "overloaded").
1325   /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1326   /// methods inside categories with a particular selector.
1327   GlobalMethodPool MethodPool;
1328 
1329   /// Method selectors used in a \@selector expression. Used for implementation
1330   /// of -Wselector.
1331   llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1332 
1333   /// List of SourceLocations where 'self' is implicitly retained inside a
1334   /// block.
1335   llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1336       ImplicitlyRetainedSelfLocs;
1337 
1338   /// Kinds of C++ special members.
1339   enum CXXSpecialMember {
1340     CXXDefaultConstructor,
1341     CXXCopyConstructor,
1342     CXXMoveConstructor,
1343     CXXCopyAssignment,
1344     CXXMoveAssignment,
1345     CXXDestructor,
1346     CXXInvalid
1347   };
1348 
1349   typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1350       SpecialMemberDecl;
1351 
1352   /// The C++ special members which we are currently in the process of
1353   /// declaring. If this process recursively triggers the declaration of the
1354   /// same special member, we should act as if it is not yet declared.
1355   llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1356 
1357   /// Kinds of defaulted comparison operator functions.
1358   enum class DefaultedComparisonKind : unsigned char {
1359     /// This is not a defaultable comparison operator.
1360     None,
1361     /// This is an operator== that should be implemented as a series of
1362     /// subobject comparisons.
1363     Equal,
1364     /// This is an operator<=> that should be implemented as a series of
1365     /// subobject comparisons.
1366     ThreeWay,
1367     /// This is an operator!= that should be implemented as a rewrite in terms
1368     /// of a == comparison.
1369     NotEqual,
1370     /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1371     /// terms of a <=> comparison.
1372     Relational,
1373   };
1374 
1375   /// The function definitions which were renamed as part of typo-correction
1376   /// to match their respective declarations. We want to keep track of them
1377   /// to ensure that we don't emit a "redefinition" error if we encounter a
1378   /// correctly named definition after the renamed definition.
1379   llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1380 
1381   /// Stack of types that correspond to the parameter entities that are
1382   /// currently being copy-initialized. Can be empty.
1383   llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1384 
1385   void ReadMethodPool(Selector Sel);
1386   void updateOutOfDateSelector(Selector Sel);
1387 
1388   /// Private Helper predicate to check for 'self'.
1389   bool isSelfExpr(Expr *RExpr);
1390   bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1391 
1392   /// Cause the active diagnostic on the DiagosticsEngine to be
1393   /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1394   /// should not be used elsewhere.
1395   void EmitCurrentDiagnostic(unsigned DiagID);
1396 
1397   /// Records and restores the CurFPFeatures state on entry/exit of compound
1398   /// statements.
1399   class FPFeaturesStateRAII {
1400   public:
FPFeaturesStateRAII(Sema & S)1401     FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) {
1402       OldOverrides = S.FpPragmaStack.CurrentValue;
1403     }
~FPFeaturesStateRAII()1404     ~FPFeaturesStateRAII() {
1405       S.CurFPFeatures = OldFPFeaturesState;
1406       S.FpPragmaStack.CurrentValue = OldOverrides;
1407     }
getOverrides()1408     FPOptionsOverride getOverrides() { return OldOverrides; }
1409 
1410   private:
1411     Sema& S;
1412     FPOptions OldFPFeaturesState;
1413     FPOptionsOverride OldOverrides;
1414   };
1415 
1416   void addImplicitTypedef(StringRef Name, QualType T);
1417 
1418   bool WarnedStackExhausted = false;
1419 
1420 public:
1421   Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1422        TranslationUnitKind TUKind = TU_Complete,
1423        CodeCompleteConsumer *CompletionConsumer = nullptr);
1424   ~Sema();
1425 
1426   /// Perform initialization that occurs after the parser has been
1427   /// initialized but before it parses anything.
1428   void Initialize();
1429 
getLangOpts()1430   const LangOptions &getLangOpts() const { return LangOpts; }
getOpenCLOptions()1431   OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
getCurFPFeatures()1432   FPOptions     &getCurFPFeatures() { return CurFPFeatures; }
1433 
getDiagnostics()1434   DiagnosticsEngine &getDiagnostics() const { return Diags; }
getSourceManager()1435   SourceManager &getSourceManager() const { return SourceMgr; }
getPreprocessor()1436   Preprocessor &getPreprocessor() const { return PP; }
getASTContext()1437   ASTContext &getASTContext() const { return Context; }
getASTConsumer()1438   ASTConsumer &getASTConsumer() const { return Consumer; }
1439   ASTMutationListener *getASTMutationListener() const;
getExternalSource()1440   ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1441 
1442   ///Registers an external source. If an external source already exists,
1443   /// creates a multiplex external source and appends to it.
1444   ///
1445   ///\param[in] E - A non-null external sema source.
1446   ///
1447   void addExternalSource(ExternalSemaSource *E);
1448 
1449   void PrintStats() const;
1450 
1451   /// Warn that the stack is nearly exhausted.
1452   void warnStackExhausted(SourceLocation Loc);
1453 
1454   /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1455   /// guaranteed). Produces a warning if we're low on stack space and allocates
1456   /// more in that case. Use this in code that may recurse deeply (for example,
1457   /// in template instantiation) to avoid stack overflow.
1458   void runWithSufficientStackSpace(SourceLocation Loc,
1459                                    llvm::function_ref<void()> Fn);
1460 
1461   /// Helper class that creates diagnostics with optional
1462   /// template instantiation stacks.
1463   ///
1464   /// This class provides a wrapper around the basic DiagnosticBuilder
1465   /// class that emits diagnostics. ImmediateDiagBuilder is
1466   /// responsible for emitting the diagnostic (as DiagnosticBuilder
1467   /// does) and, if the diagnostic comes from inside a template
1468   /// instantiation, printing the template instantiation stack as
1469   /// well.
1470   class ImmediateDiagBuilder : public DiagnosticBuilder {
1471     Sema &SemaRef;
1472     unsigned DiagID;
1473 
1474   public:
ImmediateDiagBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1475     ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1476         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
ImmediateDiagBuilder(DiagnosticBuilder && DB,Sema & SemaRef,unsigned DiagID)1477     ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1478         : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1479 
1480     // This is a cunning lie. DiagnosticBuilder actually performs move
1481     // construction in its copy constructor (but due to varied uses, it's not
1482     // possible to conveniently express this as actual move construction). So
1483     // the default copy ctor here is fine, because the base class disables the
1484     // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1485     // in that case anwyay.
1486     ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1487 
~ImmediateDiagBuilder()1488     ~ImmediateDiagBuilder() {
1489       // If we aren't active, there is nothing to do.
1490       if (!isActive()) return;
1491 
1492       // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1493       // builder itself so it won't emit the diagnostic in its own destructor.
1494       //
1495       // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1496       // do its own needless checks to see if the diagnostic needs to be
1497       // emitted. However, because we take care to ensure that the builder
1498       // objects never escape, a sufficiently smart compiler will be able to
1499       // eliminate that code.
1500       Clear();
1501 
1502       // Dispatch to Sema to emit the diagnostic.
1503       SemaRef.EmitCurrentDiagnostic(DiagID);
1504     }
1505 
1506     /// Teach operator<< to produce an object of the correct type.
1507     template <typename T>
1508     friend const ImmediateDiagBuilder &
1509     operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1510       const DiagnosticBuilder &BaseDiag = Diag;
1511       BaseDiag << Value;
1512       return Diag;
1513     }
1514 
1515     // It is necessary to limit this to rvalue reference to avoid calling this
1516     // function with a bitfield lvalue argument since non-const reference to
1517     // bitfield is not allowed.
1518     template <typename T, typename = typename std::enable_if<
1519                               !std::is_lvalue_reference<T>::value>::type>
1520     const ImmediateDiagBuilder &operator<<(T &&V) const {
1521       const DiagnosticBuilder &BaseDiag = *this;
1522       BaseDiag << std::move(V);
1523       return *this;
1524     }
1525   };
1526 
1527   /// A generic diagnostic builder for errors which may or may not be deferred.
1528   ///
1529   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1530   /// which are not allowed to appear inside __device__ functions and are
1531   /// allowed to appear in __host__ __device__ functions only if the host+device
1532   /// function is never codegen'ed.
1533   ///
1534   /// To handle this, we use the notion of "deferred diagnostics", where we
1535   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1536   ///
1537   /// This class lets you emit either a regular diagnostic, a deferred
1538   /// diagnostic, or no diagnostic at all, according to an argument you pass to
1539   /// its constructor, thus simplifying the process of creating these "maybe
1540   /// deferred" diagnostics.
1541   class SemaDiagnosticBuilder {
1542   public:
1543     enum Kind {
1544       /// Emit no diagnostics.
1545       K_Nop,
1546       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1547       K_Immediate,
1548       /// Emit the diagnostic immediately, and, if it's a warning or error, also
1549       /// emit a call stack showing how this function can be reached by an a
1550       /// priori known-emitted function.
1551       K_ImmediateWithCallStack,
1552       /// Create a deferred diagnostic, which is emitted only if the function
1553       /// it's attached to is codegen'ed.  Also emit a call stack as with
1554       /// K_ImmediateWithCallStack.
1555       K_Deferred
1556     };
1557 
1558     SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1559                           FunctionDecl *Fn, Sema &S);
1560     SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1561     SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1562     ~SemaDiagnosticBuilder();
1563 
isImmediate()1564     bool isImmediate() const { return ImmediateDiag.hasValue(); }
1565 
1566     /// Convertible to bool: True if we immediately emitted an error, false if
1567     /// we didn't emit an error or we created a deferred error.
1568     ///
1569     /// Example usage:
1570     ///
1571     ///   if (SemaDiagnosticBuilder(...) << foo << bar)
1572     ///     return ExprError();
1573     ///
1574     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1575     /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1576     operator bool() const { return isImmediate(); }
1577 
1578     template <typename T>
1579     friend const SemaDiagnosticBuilder &
1580     operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1581       if (Diag.ImmediateDiag.hasValue())
1582         *Diag.ImmediateDiag << Value;
1583       else if (Diag.PartialDiagId.hasValue())
1584         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1585             << Value;
1586       return Diag;
1587     }
1588 
1589     // It is necessary to limit this to rvalue reference to avoid calling this
1590     // function with a bitfield lvalue argument since non-const reference to
1591     // bitfield is not allowed.
1592     template <typename T, typename = typename std::enable_if<
1593                               !std::is_lvalue_reference<T>::value>::type>
1594     const SemaDiagnosticBuilder &operator<<(T &&V) const {
1595       if (ImmediateDiag.hasValue())
1596         *ImmediateDiag << std::move(V);
1597       else if (PartialDiagId.hasValue())
1598         S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1599       return *this;
1600     }
1601 
1602     friend const SemaDiagnosticBuilder &
1603     operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1604       if (Diag.ImmediateDiag.hasValue())
1605         PD.Emit(*Diag.ImmediateDiag);
1606       else if (Diag.PartialDiagId.hasValue())
1607         Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1608       return Diag;
1609     }
1610 
AddFixItHint(const FixItHint & Hint)1611     void AddFixItHint(const FixItHint &Hint) const {
1612       if (ImmediateDiag.hasValue())
1613         ImmediateDiag->AddFixItHint(Hint);
1614       else if (PartialDiagId.hasValue())
1615         S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1616     }
1617 
ExprError(const SemaDiagnosticBuilder &)1618     friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1619       return ExprError();
1620     }
StmtError(const SemaDiagnosticBuilder &)1621     friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1622       return StmtError();
1623     }
ExprResult()1624     operator ExprResult() const { return ExprError(); }
StmtResult()1625     operator StmtResult() const { return StmtError(); }
TypeResult()1626     operator TypeResult() const { return TypeError(); }
DeclResult()1627     operator DeclResult() const { return DeclResult(true); }
MemInitResult()1628     operator MemInitResult() const { return MemInitResult(true); }
1629 
1630   private:
1631     Sema &S;
1632     SourceLocation Loc;
1633     unsigned DiagID;
1634     FunctionDecl *Fn;
1635     bool ShowCallStack;
1636 
1637     // Invariant: At most one of these Optionals has a value.
1638     // FIXME: Switch these to a Variant once that exists.
1639     llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1640     llvm::Optional<unsigned> PartialDiagId;
1641   };
1642   using DiagBuilderT = SemaDiagnosticBuilder;
1643 
1644   /// Is the last error level diagnostic immediate. This is used to determined
1645   /// whether the next info diagnostic should be immediate.
1646   bool IsLastErrorImmediate = true;
1647 
1648   /// Emit a diagnostic.
1649   SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1650                              bool DeferHint = false);
1651 
1652   /// Emit a partial diagnostic.
1653   SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1654                              bool DeferHint = false);
1655 
1656   /// Build a partial diagnostic.
1657   PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1658 
1659   /// Whether uncompilable error has occurred. This includes error happens
1660   /// in deferred diagnostics.
1661   bool hasUncompilableErrorOccurred() const;
1662 
1663   bool findMacroSpelling(SourceLocation &loc, StringRef name);
1664 
1665   /// Get a string to suggest for zero-initialization of a type.
1666   std::string
1667   getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1668   std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1669 
1670   /// Calls \c Lexer::getLocForEndOfToken()
1671   SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1672 
1673   /// Retrieve the module loader associated with the preprocessor.
1674   ModuleLoader &getModuleLoader() const;
1675 
1676   /// Invent a new identifier for parameters of abbreviated templates.
1677   IdentifierInfo *
1678   InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1679                                              unsigned Index);
1680 
1681   void emitAndClearUnusedLocalTypedefWarnings();
1682 
1683   private:
1684     /// Function or variable declarations to be checked for whether the deferred
1685     /// diagnostics should be emitted.
1686     SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1687 
1688   public:
1689   // Emit all deferred diagnostics.
1690   void emitDeferredDiags();
1691 
1692   enum TUFragmentKind {
1693     /// The global module fragment, between 'module;' and a module-declaration.
1694     Global,
1695     /// A normal translation unit fragment. For a non-module unit, this is the
1696     /// entire translation unit. Otherwise, it runs from the module-declaration
1697     /// to the private-module-fragment (if any) or the end of the TU (if not).
1698     Normal,
1699     /// The private module fragment, between 'module :private;' and the end of
1700     /// the translation unit.
1701     Private
1702   };
1703 
1704   void ActOnStartOfTranslationUnit();
1705   void ActOnEndOfTranslationUnit();
1706   void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1707 
1708   void CheckDelegatingCtorCycles();
1709 
1710   Scope *getScopeForContext(DeclContext *Ctx);
1711 
1712   void PushFunctionScope();
1713   void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1714   sema::LambdaScopeInfo *PushLambdaScope();
1715 
1716   /// This is used to inform Sema what the current TemplateParameterDepth
1717   /// is during Parsing.  Currently it is used to pass on the depth
1718   /// when parsing generic lambda 'auto' parameters.
1719   void RecordParsingTemplateParameterDepth(unsigned Depth);
1720 
1721   void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1722                                RecordDecl *RD, CapturedRegionKind K,
1723                                unsigned OpenMPCaptureLevel = 0);
1724 
1725   /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1726   /// time after they've been popped.
1727   class PoppedFunctionScopeDeleter {
1728     Sema *Self;
1729 
1730   public:
PoppedFunctionScopeDeleter(Sema * Self)1731     explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1732     void operator()(sema::FunctionScopeInfo *Scope) const;
1733   };
1734 
1735   using PoppedFunctionScopePtr =
1736       std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1737 
1738   PoppedFunctionScopePtr
1739   PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1740                        const Decl *D = nullptr,
1741                        QualType BlockType = QualType());
1742 
getCurFunction()1743   sema::FunctionScopeInfo *getCurFunction() const {
1744     return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1745   }
1746 
1747   sema::FunctionScopeInfo *getEnclosingFunction() const;
1748 
1749   void setFunctionHasBranchIntoScope();
1750   void setFunctionHasBranchProtectedScope();
1751   void setFunctionHasIndirectGoto();
1752 
1753   void PushCompoundScope(bool IsStmtExpr);
1754   void PopCompoundScope();
1755 
1756   sema::CompoundScopeInfo &getCurCompoundScope() const;
1757 
1758   bool hasAnyUnrecoverableErrorsInThisFunction() const;
1759 
1760   /// Retrieve the current block, if any.
1761   sema::BlockScopeInfo *getCurBlock();
1762 
1763   /// Get the innermost lambda enclosing the current location, if any. This
1764   /// looks through intervening non-lambda scopes such as local functions and
1765   /// blocks.
1766   sema::LambdaScopeInfo *getEnclosingLambda() const;
1767 
1768   /// Retrieve the current lambda scope info, if any.
1769   /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1770   /// lambda scope info ignoring all inner capturing scopes that are not
1771   /// lambda scopes.
1772   sema::LambdaScopeInfo *
1773   getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1774 
1775   /// Retrieve the current generic lambda info, if any.
1776   sema::LambdaScopeInfo *getCurGenericLambda();
1777 
1778   /// Retrieve the current captured region, if any.
1779   sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1780 
1781   /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
WeakTopLevelDecls()1782   SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1783 
1784   /// Called before parsing a function declarator belonging to a function
1785   /// declaration.
1786   void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1787                                                unsigned TemplateParameterDepth);
1788 
1789   /// Called after parsing a function declarator belonging to a function
1790   /// declaration.
1791   void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
1792 
1793   void ActOnComment(SourceRange Comment);
1794 
1795   //===--------------------------------------------------------------------===//
1796   // Type Analysis / Processing: SemaType.cpp.
1797   //
1798 
1799   QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1800                               const DeclSpec *DS = nullptr);
1801   QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1802                               const DeclSpec *DS = nullptr);
1803   QualType BuildPointerType(QualType T,
1804                             SourceLocation Loc, DeclarationName Entity);
1805   QualType BuildReferenceType(QualType T, bool LValueRef,
1806                               SourceLocation Loc, DeclarationName Entity);
1807   QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1808                           Expr *ArraySize, unsigned Quals,
1809                           SourceRange Brackets, DeclarationName Entity);
1810   QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
1811   QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1812                               SourceLocation AttrLoc);
1813   QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
1814                            SourceLocation AttrLoc);
1815 
1816   QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
1817                                  SourceLocation AttrLoc);
1818 
1819   /// Same as above, but constructs the AddressSpace index if not provided.
1820   QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1821                                  SourceLocation AttrLoc);
1822 
1823   bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
1824 
1825   bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1826 
1827   /// Build a function type.
1828   ///
1829   /// This routine checks the function type according to C++ rules and
1830   /// under the assumption that the result type and parameter types have
1831   /// just been instantiated from a template. It therefore duplicates
1832   /// some of the behavior of GetTypeForDeclarator, but in a much
1833   /// simpler form that is only suitable for this narrow use case.
1834   ///
1835   /// \param T The return type of the function.
1836   ///
1837   /// \param ParamTypes The parameter types of the function. This array
1838   /// will be modified to account for adjustments to the types of the
1839   /// function parameters.
1840   ///
1841   /// \param Loc The location of the entity whose type involves this
1842   /// function type or, if there is no such entity, the location of the
1843   /// type that will have function type.
1844   ///
1845   /// \param Entity The name of the entity that involves the function
1846   /// type, if known.
1847   ///
1848   /// \param EPI Extra information about the function type. Usually this will
1849   /// be taken from an existing function with the same prototype.
1850   ///
1851   /// \returns A suitable function type, if there are no errors. The
1852   /// unqualified type will always be a FunctionProtoType.
1853   /// Otherwise, returns a NULL type.
1854   QualType BuildFunctionType(QualType T,
1855                              MutableArrayRef<QualType> ParamTypes,
1856                              SourceLocation Loc, DeclarationName Entity,
1857                              const FunctionProtoType::ExtProtoInfo &EPI);
1858 
1859   QualType BuildMemberPointerType(QualType T, QualType Class,
1860                                   SourceLocation Loc,
1861                                   DeclarationName Entity);
1862   QualType BuildBlockPointerType(QualType T,
1863                                  SourceLocation Loc, DeclarationName Entity);
1864   QualType BuildParenType(QualType T);
1865   QualType BuildAtomicType(QualType T, SourceLocation Loc);
1866   QualType BuildReadPipeType(QualType T,
1867                          SourceLocation Loc);
1868   QualType BuildWritePipeType(QualType T,
1869                          SourceLocation Loc);
1870   QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
1871 
1872   TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1873   TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1874 
1875   /// Package the given type and TSI into a ParsedType.
1876   ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1877   DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1878   DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1879   static QualType GetTypeFromParser(ParsedType Ty,
1880                                     TypeSourceInfo **TInfo = nullptr);
1881   CanThrowResult canThrow(const Stmt *E);
1882   /// Determine whether the callee of a particular function call can throw.
1883   /// E, D and Loc are all optional.
1884   static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
1885                                        SourceLocation Loc = SourceLocation());
1886   const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1887                                                 const FunctionProtoType *FPT);
1888   void UpdateExceptionSpec(FunctionDecl *FD,
1889                            const FunctionProtoType::ExceptionSpecInfo &ESI);
1890   bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1891   bool CheckDistantExceptionSpec(QualType T);
1892   bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1893   bool CheckEquivalentExceptionSpec(
1894       const FunctionProtoType *Old, SourceLocation OldLoc,
1895       const FunctionProtoType *New, SourceLocation NewLoc);
1896   bool CheckEquivalentExceptionSpec(
1897       const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1898       const FunctionProtoType *Old, SourceLocation OldLoc,
1899       const FunctionProtoType *New, SourceLocation NewLoc);
1900   bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1901   bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1902                                 const PartialDiagnostic &NestedDiagID,
1903                                 const PartialDiagnostic &NoteID,
1904                                 const PartialDiagnostic &NoThrowDiagID,
1905                                 const FunctionProtoType *Superset,
1906                                 SourceLocation SuperLoc,
1907                                 const FunctionProtoType *Subset,
1908                                 SourceLocation SubLoc);
1909   bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1910                                const PartialDiagnostic &NoteID,
1911                                const FunctionProtoType *Target,
1912                                SourceLocation TargetLoc,
1913                                const FunctionProtoType *Source,
1914                                SourceLocation SourceLoc);
1915 
1916   TypeResult ActOnTypeName(Scope *S, Declarator &D);
1917 
1918   /// The parser has parsed the context-sensitive type 'instancetype'
1919   /// in an Objective-C message declaration. Return the appropriate type.
1920   ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1921 
1922   /// Abstract class used to diagnose incomplete types.
1923   struct TypeDiagnoser {
TypeDiagnoserTypeDiagnoser1924     TypeDiagnoser() {}
1925 
1926     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
~TypeDiagnoserTypeDiagnoser1927     virtual ~TypeDiagnoser() {}
1928   };
1929 
getPrintable(int I)1930   static int getPrintable(int I) { return I; }
getPrintable(unsigned I)1931   static unsigned getPrintable(unsigned I) { return I; }
getPrintable(bool B)1932   static bool getPrintable(bool B) { return B; }
getPrintable(const char * S)1933   static const char * getPrintable(const char *S) { return S; }
getPrintable(StringRef S)1934   static StringRef getPrintable(StringRef S) { return S; }
getPrintable(const std::string & S)1935   static const std::string &getPrintable(const std::string &S) { return S; }
getPrintable(const IdentifierInfo * II)1936   static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1937     return II;
1938   }
getPrintable(DeclarationName N)1939   static DeclarationName getPrintable(DeclarationName N) { return N; }
getPrintable(QualType T)1940   static QualType getPrintable(QualType T) { return T; }
getPrintable(SourceRange R)1941   static SourceRange getPrintable(SourceRange R) { return R; }
getPrintable(SourceLocation L)1942   static SourceRange getPrintable(SourceLocation L) { return L; }
getPrintable(const Expr * E)1943   static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
getPrintable(TypeLoc TL)1944   static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1945 
1946   template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1947   protected:
1948     unsigned DiagID;
1949     std::tuple<const Ts &...> Args;
1950 
1951     template <std::size_t... Is>
emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)1952     void emit(const SemaDiagnosticBuilder &DB,
1953               std::index_sequence<Is...>) const {
1954       // Apply all tuple elements to the builder in order.
1955       bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1956       (void)Dummy;
1957     }
1958 
1959   public:
BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)1960     BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1961         : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1962       assert(DiagID != 0 && "no diagnostic for type diagnoser");
1963     }
1964 
diagnose(Sema & S,SourceLocation Loc,QualType T)1965     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1966       const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1967       emit(DB, std::index_sequence_for<Ts...>());
1968       DB << T;
1969     }
1970   };
1971 
1972   /// Do a check to make sure \p Name looks like a legal argument for the
1973   /// swift_name attribute applied to decl \p D.  Raise a diagnostic if the name
1974   /// is invalid for the given declaration.
1975   ///
1976   /// \p AL is used to provide caret diagnostics in case of a malformed name.
1977   ///
1978   /// \returns true if the name is a valid swift name for \p D, false otherwise.
1979   bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
1980                          const ParsedAttr &AL);
1981 
1982   /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
1983   /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
1984   /// For example, a diagnostic with no other parameters would generally have
1985   /// the form "...%select{incomplete|sizeless}0 type %1...".
1986   template <typename... Ts>
1987   class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
1988   public:
SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)1989     SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
1990         : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
1991 
diagnose(Sema & S,SourceLocation Loc,QualType T)1992     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1993       const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
1994       this->emit(DB, std::index_sequence_for<Ts...>());
1995       DB << T->isSizelessType() << T;
1996     }
1997   };
1998 
1999   enum class CompleteTypeKind {
2000     /// Apply the normal rules for complete types.  In particular,
2001     /// treat all sizeless types as incomplete.
2002     Normal,
2003 
2004     /// Relax the normal rules for complete types so that they include
2005     /// sizeless built-in types.
2006     AcceptSizeless,
2007 
2008     // FIXME: Eventually we should flip the default to Normal and opt in
2009     // to AcceptSizeless rather than opt out of it.
2010     Default = AcceptSizeless
2011   };
2012 
2013 private:
2014   /// Methods for marking which expressions involve dereferencing a pointer
2015   /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2016   /// they are parsed, meaning that a noderef pointer may not be accessed. For
2017   /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2018   /// `*p`, but need to check that `address of` is called on it. This requires
2019   /// keeping a container of all pending expressions and checking if the address
2020   /// of them are eventually taken.
2021   void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2022   void CheckAddressOfNoDeref(const Expr *E);
2023   void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2024 
2025   bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2026                                CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2027 
2028   struct ModuleScope {
2029     SourceLocation BeginLoc;
2030     clang::Module *Module = nullptr;
2031     bool ModuleInterface = false;
2032     bool ImplicitGlobalModuleFragment = false;
2033     VisibleModuleSet OuterVisibleModules;
2034   };
2035   /// The modules we're currently parsing.
2036   llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2037 
2038   /// Namespace definitions that we will export when they finish.
2039   llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2040 
2041   /// Get the module whose scope we are currently within.
getCurrentModule()2042   Module *getCurrentModule() const {
2043     return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2044   }
2045 
2046   VisibleModuleSet VisibleModules;
2047 
2048 public:
2049   /// Get the module owning an entity.
getOwningModule(const Decl * Entity)2050   Module *getOwningModule(const Decl *Entity) {
2051     return Entity->getOwningModule();
2052   }
2053 
2054   /// Make a merged definition of an existing hidden definition \p ND
2055   /// visible at the specified location.
2056   void makeMergedDefinitionVisible(NamedDecl *ND);
2057 
2058   bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2059 
2060   // When loading a non-modular PCH files, this is used to restore module
2061   // visibility.
makeModuleVisible(Module * Mod,SourceLocation ImportLoc)2062   void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2063     VisibleModules.setVisible(Mod, ImportLoc);
2064   }
2065 
2066   /// Determine whether a declaration is visible to name lookup.
isVisible(const NamedDecl * D)2067   bool isVisible(const NamedDecl *D) {
2068     return D->isUnconditionallyVisible() || isVisibleSlow(D);
2069   }
2070 
2071   /// Determine whether any declaration of an entity is visible.
2072   bool
2073   hasVisibleDeclaration(const NamedDecl *D,
2074                         llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2075     return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2076   }
2077   bool hasVisibleDeclarationSlow(const NamedDecl *D,
2078                                  llvm::SmallVectorImpl<Module *> *Modules);
2079 
2080   bool hasVisibleMergedDefinition(NamedDecl *Def);
2081   bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2082 
2083   /// Determine if \p D and \p Suggested have a structurally compatible
2084   /// layout as described in C11 6.2.7/1.
2085   bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2086 
2087   /// Determine if \p D has a visible definition. If not, suggest a declaration
2088   /// that should be made visible to expose the definition.
2089   bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2090                             bool OnlyNeedComplete = false);
hasVisibleDefinition(const NamedDecl * D)2091   bool hasVisibleDefinition(const NamedDecl *D) {
2092     NamedDecl *Hidden;
2093     return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2094   }
2095 
2096   /// Determine if the template parameter \p D has a visible default argument.
2097   bool
2098   hasVisibleDefaultArgument(const NamedDecl *D,
2099                             llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2100 
2101   /// Determine if there is a visible declaration of \p D that is an explicit
2102   /// specialization declaration for a specialization of a template. (For a
2103   /// member specialization, use hasVisibleMemberSpecialization.)
2104   bool hasVisibleExplicitSpecialization(
2105       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2106 
2107   /// Determine if there is a visible declaration of \p D that is a member
2108   /// specialization declaration (as opposed to an instantiated declaration).
2109   bool hasVisibleMemberSpecialization(
2110       const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2111 
2112   /// Determine if \p A and \p B are equivalent internal linkage declarations
2113   /// from different modules, and thus an ambiguity error can be downgraded to
2114   /// an extension warning.
2115   bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2116                                               const NamedDecl *B);
2117   void diagnoseEquivalentInternalLinkageDeclarations(
2118       SourceLocation Loc, const NamedDecl *D,
2119       ArrayRef<const NamedDecl *> Equiv);
2120 
2121   bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2122 
2123   bool isCompleteType(SourceLocation Loc, QualType T,
2124                       CompleteTypeKind Kind = CompleteTypeKind::Default) {
2125     return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2126   }
2127   bool RequireCompleteType(SourceLocation Loc, QualType T,
2128                            CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2129   bool RequireCompleteType(SourceLocation Loc, QualType T,
2130                            CompleteTypeKind Kind, unsigned DiagID);
2131 
RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)2132   bool RequireCompleteType(SourceLocation Loc, QualType T,
2133                            TypeDiagnoser &Diagnoser) {
2134     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2135   }
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)2136   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2137     return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2138   }
2139 
2140   template <typename... Ts>
RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2141   bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2142                            const Ts &...Args) {
2143     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2144     return RequireCompleteType(Loc, T, Diagnoser);
2145   }
2146 
2147   template <typename... Ts>
RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2148   bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2149                                 const Ts &... Args) {
2150     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2151     return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2152   }
2153 
2154   void completeExprArrayBound(Expr *E);
2155   bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2156                                TypeDiagnoser &Diagnoser);
2157   bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2158 
2159   template <typename... Ts>
RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2160   bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2161     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2162     return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2163   }
2164 
2165   template <typename... Ts>
RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2166   bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2167                                     const Ts &... Args) {
2168     SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2169     return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2170   }
2171 
2172   bool RequireLiteralType(SourceLocation Loc, QualType T,
2173                           TypeDiagnoser &Diagnoser);
2174   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2175 
2176   template <typename... Ts>
RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2177   bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2178                           const Ts &...Args) {
2179     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2180     return RequireLiteralType(Loc, T, Diagnoser);
2181   }
2182 
2183   QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2184                              const CXXScopeSpec &SS, QualType T,
2185                              TagDecl *OwnedTagDecl = nullptr);
2186 
2187   QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
2188   /// If AsUnevaluated is false, E is treated as though it were an evaluated
2189   /// context, such as when building a type for decltype(auto).
2190   QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
2191                              bool AsUnevaluated = true);
2192   QualType BuildUnaryTransformType(QualType BaseType,
2193                                    UnaryTransformType::UTTKind UKind,
2194                                    SourceLocation Loc);
2195 
2196   //===--------------------------------------------------------------------===//
2197   // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2198   //
2199 
2200   struct SkipBodyInfo {
SkipBodyInfoSkipBodyInfo2201     SkipBodyInfo()
2202         : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2203           New(nullptr) {}
2204     bool ShouldSkip;
2205     bool CheckSameAsPrevious;
2206     NamedDecl *Previous;
2207     NamedDecl *New;
2208   };
2209 
2210   DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2211 
2212   void DiagnoseUseOfUnimplementedSelectors();
2213 
2214   bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2215 
2216   ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2217                          Scope *S, CXXScopeSpec *SS = nullptr,
2218                          bool isClassName = false, bool HasTrailingDot = false,
2219                          ParsedType ObjectType = nullptr,
2220                          bool IsCtorOrDtorName = false,
2221                          bool WantNontrivialTypeSourceInfo = false,
2222                          bool IsClassTemplateDeductionContext = true,
2223                          IdentifierInfo **CorrectedII = nullptr);
2224   TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2225   bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2226   void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2227                                SourceLocation IILoc,
2228                                Scope *S,
2229                                CXXScopeSpec *SS,
2230                                ParsedType &SuggestedType,
2231                                bool IsTemplateName = false);
2232 
2233   /// Attempt to behave like MSVC in situations where lookup of an unqualified
2234   /// type name has failed in a dependent context. In these situations, we
2235   /// automatically form a DependentTypeName that will retry lookup in a related
2236   /// scope during instantiation.
2237   ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2238                                       SourceLocation NameLoc,
2239                                       bool IsTemplateTypeArg);
2240 
2241   /// Describes the result of the name lookup and resolution performed
2242   /// by \c ClassifyName().
2243   enum NameClassificationKind {
2244     /// This name is not a type or template in this context, but might be
2245     /// something else.
2246     NC_Unknown,
2247     /// Classification failed; an error has been produced.
2248     NC_Error,
2249     /// The name has been typo-corrected to a keyword.
2250     NC_Keyword,
2251     /// The name was classified as a type.
2252     NC_Type,
2253     /// The name was classified as a specific non-type, non-template
2254     /// declaration. ActOnNameClassifiedAsNonType should be called to
2255     /// convert the declaration to an expression.
2256     NC_NonType,
2257     /// The name was classified as an ADL-only function name.
2258     /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2259     /// result to an expression.
2260     NC_UndeclaredNonType,
2261     /// The name denotes a member of a dependent type that could not be
2262     /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2263     /// convert the result to an expression.
2264     NC_DependentNonType,
2265     /// The name was classified as an overload set, and an expression
2266     /// representing that overload set has been formed.
2267     /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2268     /// expression referencing the overload set.
2269     NC_OverloadSet,
2270     /// The name was classified as a template whose specializations are types.
2271     NC_TypeTemplate,
2272     /// The name was classified as a variable template name.
2273     NC_VarTemplate,
2274     /// The name was classified as a function template name.
2275     NC_FunctionTemplate,
2276     /// The name was classified as an ADL-only function template name.
2277     NC_UndeclaredTemplate,
2278     /// The name was classified as a concept name.
2279     NC_Concept,
2280   };
2281 
2282   class NameClassification {
2283     NameClassificationKind Kind;
2284     union {
2285       ExprResult Expr;
2286       NamedDecl *NonTypeDecl;
2287       TemplateName Template;
2288       ParsedType Type;
2289     };
2290 
NameClassification(NameClassificationKind Kind)2291     explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2292 
2293   public:
NameClassification(ParsedType Type)2294     NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2295 
NameClassification(const IdentifierInfo * Keyword)2296     NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2297 
Error()2298     static NameClassification Error() {
2299       return NameClassification(NC_Error);
2300     }
2301 
Unknown()2302     static NameClassification Unknown() {
2303       return NameClassification(NC_Unknown);
2304     }
2305 
OverloadSet(ExprResult E)2306     static NameClassification OverloadSet(ExprResult E) {
2307       NameClassification Result(NC_OverloadSet);
2308       Result.Expr = E;
2309       return Result;
2310     }
2311 
NonType(NamedDecl * D)2312     static NameClassification NonType(NamedDecl *D) {
2313       NameClassification Result(NC_NonType);
2314       Result.NonTypeDecl = D;
2315       return Result;
2316     }
2317 
UndeclaredNonType()2318     static NameClassification UndeclaredNonType() {
2319       return NameClassification(NC_UndeclaredNonType);
2320     }
2321 
DependentNonType()2322     static NameClassification DependentNonType() {
2323       return NameClassification(NC_DependentNonType);
2324     }
2325 
TypeTemplate(TemplateName Name)2326     static NameClassification TypeTemplate(TemplateName Name) {
2327       NameClassification Result(NC_TypeTemplate);
2328       Result.Template = Name;
2329       return Result;
2330     }
2331 
VarTemplate(TemplateName Name)2332     static NameClassification VarTemplate(TemplateName Name) {
2333       NameClassification Result(NC_VarTemplate);
2334       Result.Template = Name;
2335       return Result;
2336     }
2337 
FunctionTemplate(TemplateName Name)2338     static NameClassification FunctionTemplate(TemplateName Name) {
2339       NameClassification Result(NC_FunctionTemplate);
2340       Result.Template = Name;
2341       return Result;
2342     }
2343 
Concept(TemplateName Name)2344     static NameClassification Concept(TemplateName Name) {
2345       NameClassification Result(NC_Concept);
2346       Result.Template = Name;
2347       return Result;
2348     }
2349 
UndeclaredTemplate(TemplateName Name)2350     static NameClassification UndeclaredTemplate(TemplateName Name) {
2351       NameClassification Result(NC_UndeclaredTemplate);
2352       Result.Template = Name;
2353       return Result;
2354     }
2355 
getKind()2356     NameClassificationKind getKind() const { return Kind; }
2357 
getExpression()2358     ExprResult getExpression() const {
2359       assert(Kind == NC_OverloadSet);
2360       return Expr;
2361     }
2362 
getType()2363     ParsedType getType() const {
2364       assert(Kind == NC_Type);
2365       return Type;
2366     }
2367 
getNonTypeDecl()2368     NamedDecl *getNonTypeDecl() const {
2369       assert(Kind == NC_NonType);
2370       return NonTypeDecl;
2371     }
2372 
getTemplateName()2373     TemplateName getTemplateName() const {
2374       assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
2375              Kind == NC_VarTemplate || Kind == NC_Concept ||
2376              Kind == NC_UndeclaredTemplate);
2377       return Template;
2378     }
2379 
getTemplateNameKind()2380     TemplateNameKind getTemplateNameKind() const {
2381       switch (Kind) {
2382       case NC_TypeTemplate:
2383         return TNK_Type_template;
2384       case NC_FunctionTemplate:
2385         return TNK_Function_template;
2386       case NC_VarTemplate:
2387         return TNK_Var_template;
2388       case NC_Concept:
2389         return TNK_Concept_template;
2390       case NC_UndeclaredTemplate:
2391         return TNK_Undeclared_template;
2392       default:
2393         llvm_unreachable("unsupported name classification.");
2394       }
2395     }
2396   };
2397 
2398   /// Perform name lookup on the given name, classifying it based on
2399   /// the results of name lookup and the following token.
2400   ///
2401   /// This routine is used by the parser to resolve identifiers and help direct
2402   /// parsing. When the identifier cannot be found, this routine will attempt
2403   /// to correct the typo and classify based on the resulting name.
2404   ///
2405   /// \param S The scope in which we're performing name lookup.
2406   ///
2407   /// \param SS The nested-name-specifier that precedes the name.
2408   ///
2409   /// \param Name The identifier. If typo correction finds an alternative name,
2410   /// this pointer parameter will be updated accordingly.
2411   ///
2412   /// \param NameLoc The location of the identifier.
2413   ///
2414   /// \param NextToken The token following the identifier. Used to help
2415   /// disambiguate the name.
2416   ///
2417   /// \param CCC The correction callback, if typo correction is desired.
2418   NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2419                                   IdentifierInfo *&Name, SourceLocation NameLoc,
2420                                   const Token &NextToken,
2421                                   CorrectionCandidateCallback *CCC = nullptr);
2422 
2423   /// Act on the result of classifying a name as an undeclared (ADL-only)
2424   /// non-type declaration.
2425   ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2426                                                     SourceLocation NameLoc);
2427   /// Act on the result of classifying a name as an undeclared member of a
2428   /// dependent base class.
2429   ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2430                                                    IdentifierInfo *Name,
2431                                                    SourceLocation NameLoc,
2432                                                    bool IsAddressOfOperand);
2433   /// Act on the result of classifying a name as a specific non-type
2434   /// declaration.
2435   ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2436                                           NamedDecl *Found,
2437                                           SourceLocation NameLoc,
2438                                           const Token &NextToken);
2439   /// Act on the result of classifying a name as an overload set.
2440   ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2441 
2442   /// Describes the detailed kind of a template name. Used in diagnostics.
2443   enum class TemplateNameKindForDiagnostics {
2444     ClassTemplate,
2445     FunctionTemplate,
2446     VarTemplate,
2447     AliasTemplate,
2448     TemplateTemplateParam,
2449     Concept,
2450     DependentTemplate
2451   };
2452   TemplateNameKindForDiagnostics
2453   getTemplateNameKindForDiagnostics(TemplateName Name);
2454 
2455   /// Determine whether it's plausible that E was intended to be a
2456   /// template-name.
mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2457   bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2458     if (!getLangOpts().CPlusPlus || E.isInvalid())
2459       return false;
2460     Dependent = false;
2461     if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2462       return !DRE->hasExplicitTemplateArgs();
2463     if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2464       return !ME->hasExplicitTemplateArgs();
2465     Dependent = true;
2466     if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2467       return !DSDRE->hasExplicitTemplateArgs();
2468     if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2469       return !DSME->hasExplicitTemplateArgs();
2470     // Any additional cases recognized here should also be handled by
2471     // diagnoseExprIntendedAsTemplateName.
2472     return false;
2473   }
2474   void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2475                                           SourceLocation Less,
2476                                           SourceLocation Greater);
2477 
2478   Decl *ActOnDeclarator(Scope *S, Declarator &D);
2479 
2480   NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2481                               MultiTemplateParamsArg TemplateParameterLists);
2482   void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2483   bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2484   bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2485                                     DeclarationName Name, SourceLocation Loc,
2486                                     bool IsTemplateId);
2487   void
2488   diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2489                             SourceLocation FallbackLoc,
2490                             SourceLocation ConstQualLoc = SourceLocation(),
2491                             SourceLocation VolatileQualLoc = SourceLocation(),
2492                             SourceLocation RestrictQualLoc = SourceLocation(),
2493                             SourceLocation AtomicQualLoc = SourceLocation(),
2494                             SourceLocation UnalignedQualLoc = SourceLocation());
2495 
2496   static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2497   void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2498   NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2499                                     const LookupResult &R);
2500   NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2501   void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2502                    const LookupResult &R);
2503   void CheckShadow(Scope *S, VarDecl *D);
2504 
2505   /// Warn if 'E', which is an expression that is about to be modified, refers
2506   /// to a shadowing declaration.
2507   void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2508 
2509   void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2510 
2511 private:
2512   /// Map of current shadowing declarations to shadowed declarations. Warn if
2513   /// it looks like the user is trying to modify the shadowing declaration.
2514   llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2515 
2516 public:
2517   void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2518   void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2519   void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2520                                     TypedefNameDecl *NewTD);
2521   void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2522   NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2523                                     TypeSourceInfo *TInfo,
2524                                     LookupResult &Previous);
2525   NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2526                                   LookupResult &Previous, bool &Redeclaration);
2527   NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2528                                      TypeSourceInfo *TInfo,
2529                                      LookupResult &Previous,
2530                                      MultiTemplateParamsArg TemplateParamLists,
2531                                      bool &AddToScope,
2532                                      ArrayRef<BindingDecl *> Bindings = None);
2533   NamedDecl *
2534   ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2535                                MultiTemplateParamsArg TemplateParamLists);
2536   // Returns true if the variable declaration is a redeclaration
2537   bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2538   void CheckVariableDeclarationType(VarDecl *NewVD);
2539   bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2540                                      Expr *Init);
2541   void CheckCompleteVariableDeclaration(VarDecl *VD);
2542   void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2543   void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2544 
2545   NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2546                                      TypeSourceInfo *TInfo,
2547                                      LookupResult &Previous,
2548                                      MultiTemplateParamsArg TemplateParamLists,
2549                                      bool &AddToScope);
2550   bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2551 
2552   enum class CheckConstexprKind {
2553     /// Diagnose issues that are non-constant or that are extensions.
2554     Diagnose,
2555     /// Identify whether this function satisfies the formal rules for constexpr
2556     /// functions in the current lanugage mode (with no extensions).
2557     CheckValid
2558   };
2559 
2560   bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2561                                         CheckConstexprKind Kind);
2562 
2563   void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2564   void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2565                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2566   void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2567                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2568   // Returns true if the function declaration is a redeclaration
2569   bool CheckFunctionDeclaration(Scope *S,
2570                                 FunctionDecl *NewFD, LookupResult &Previous,
2571                                 bool IsMemberSpecialization);
2572   bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2573   bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2574                                       QualType NewT, QualType OldT);
2575   void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2576   void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2577   Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2578                                                    bool IsDefinition);
2579   void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2580   Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2581   ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2582                                           SourceLocation Loc,
2583                                           QualType T);
2584   ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2585                               SourceLocation NameLoc, IdentifierInfo *Name,
2586                               QualType T, TypeSourceInfo *TSInfo,
2587                               StorageClass SC);
2588   void ActOnParamDefaultArgument(Decl *param,
2589                                  SourceLocation EqualLoc,
2590                                  Expr *defarg);
2591   void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2592                                          SourceLocation ArgLoc);
2593   void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2594   ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param,
2595                                          Expr *DefaultArg,
2596                                          SourceLocation EqualLoc);
2597   void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2598                                SourceLocation EqualLoc);
2599 
2600   // Contexts where using non-trivial C union types can be disallowed. This is
2601   // passed to err_non_trivial_c_union_in_invalid_context.
2602   enum NonTrivialCUnionContext {
2603     // Function parameter.
2604     NTCUC_FunctionParam,
2605     // Function return.
2606     NTCUC_FunctionReturn,
2607     // Default-initialized object.
2608     NTCUC_DefaultInitializedObject,
2609     // Variable with automatic storage duration.
2610     NTCUC_AutoVar,
2611     // Initializer expression that might copy from another object.
2612     NTCUC_CopyInit,
2613     // Assignment.
2614     NTCUC_Assignment,
2615     // Compound literal.
2616     NTCUC_CompoundLiteral,
2617     // Block capture.
2618     NTCUC_BlockCapture,
2619     // lvalue-to-rvalue conversion of volatile type.
2620     NTCUC_LValueToRValueVolatile,
2621   };
2622 
2623   /// Emit diagnostics if the initializer or any of its explicit or
2624   /// implicitly-generated subexpressions require copying or
2625   /// default-initializing a type that is or contains a C union type that is
2626   /// non-trivial to copy or default-initialize.
2627   void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2628 
2629   // These flags are passed to checkNonTrivialCUnion.
2630   enum NonTrivialCUnionKind {
2631     NTCUK_Init = 0x1,
2632     NTCUK_Destruct = 0x2,
2633     NTCUK_Copy = 0x4,
2634   };
2635 
2636   /// Emit diagnostics if a non-trivial C union type or a struct that contains
2637   /// a non-trivial C union is used in an invalid context.
2638   void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2639                              NonTrivialCUnionContext UseContext,
2640                              unsigned NonTrivialKind);
2641 
2642   void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2643   void ActOnUninitializedDecl(Decl *dcl);
2644   void ActOnInitializerError(Decl *Dcl);
2645 
2646   void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2647   void ActOnCXXForRangeDecl(Decl *D);
2648   StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2649                                         IdentifierInfo *Ident,
2650                                         ParsedAttributes &Attrs,
2651                                         SourceLocation AttrEnd);
2652   void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2653   void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2654   void CheckStaticLocalForDllExport(VarDecl *VD);
2655   void FinalizeDeclaration(Decl *D);
2656   DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2657                                          ArrayRef<Decl *> Group);
2658   DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2659 
2660   /// Should be called on all declarations that might have attached
2661   /// documentation comments.
2662   void ActOnDocumentableDecl(Decl *D);
2663   void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2664 
2665   void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2666                                        SourceLocation LocAfterDecls);
2667   void CheckForFunctionRedefinition(
2668       FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2669       SkipBodyInfo *SkipBody = nullptr);
2670   Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2671                                 MultiTemplateParamsArg TemplateParamLists,
2672                                 SkipBodyInfo *SkipBody = nullptr);
2673   Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2674                                 SkipBodyInfo *SkipBody = nullptr);
2675   void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2676   ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2677   void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
isObjCMethodDecl(Decl * D)2678   bool isObjCMethodDecl(Decl *D) {
2679     return D && isa<ObjCMethodDecl>(D);
2680   }
2681 
2682   /// Determine whether we can delay parsing the body of a function or
2683   /// function template until it is used, assuming we don't care about emitting
2684   /// code for that function.
2685   ///
2686   /// This will be \c false if we may need the body of the function in the
2687   /// middle of parsing an expression (where it's impractical to switch to
2688   /// parsing a different function), for instance, if it's constexpr in C++11
2689   /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2690   bool canDelayFunctionBody(const Declarator &D);
2691 
2692   /// Determine whether we can skip parsing the body of a function
2693   /// definition, assuming we don't care about analyzing its body or emitting
2694   /// code for that function.
2695   ///
2696   /// This will be \c false only if we may need the body of the function in
2697   /// order to parse the rest of the program (for instance, if it is
2698   /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2699   bool canSkipFunctionBody(Decl *D);
2700 
2701   void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2702   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2703   Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2704   Decl *ActOnSkippedFunctionBody(Decl *Decl);
2705   void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2706 
2707   /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2708   /// attribute for which parsing is delayed.
2709   void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2710 
2711   /// Diagnose any unused parameters in the given sequence of
2712   /// ParmVarDecl pointers.
2713   void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2714 
2715   /// Diagnose whether the size of parameters or return value of a
2716   /// function or obj-c method definition is pass-by-value and larger than a
2717   /// specified threshold.
2718   void
2719   DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2720                                          QualType ReturnTy, NamedDecl *D);
2721 
2722   void DiagnoseInvalidJumps(Stmt *Body);
2723   Decl *ActOnFileScopeAsmDecl(Expr *expr,
2724                               SourceLocation AsmLoc,
2725                               SourceLocation RParenLoc);
2726 
2727   /// Handle a C++11 empty-declaration and attribute-declaration.
2728   Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2729                               SourceLocation SemiLoc);
2730 
2731   enum class ModuleDeclKind {
2732     Interface,      ///< 'export module X;'
2733     Implementation, ///< 'module X;'
2734   };
2735 
2736   /// The parser has processed a module-declaration that begins the definition
2737   /// of a module interface or implementation.
2738   DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2739                                  SourceLocation ModuleLoc, ModuleDeclKind MDK,
2740                                  ModuleIdPath Path, bool IsFirstDecl);
2741 
2742   /// The parser has processed a global-module-fragment declaration that begins
2743   /// the definition of the global module fragment of the current module unit.
2744   /// \param ModuleLoc The location of the 'module' keyword.
2745   DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
2746 
2747   /// The parser has processed a private-module-fragment declaration that begins
2748   /// the definition of the private module fragment of the current module unit.
2749   /// \param ModuleLoc The location of the 'module' keyword.
2750   /// \param PrivateLoc The location of the 'private' keyword.
2751   DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2752                                                 SourceLocation PrivateLoc);
2753 
2754   /// The parser has processed a module import declaration.
2755   ///
2756   /// \param StartLoc The location of the first token in the declaration. This
2757   ///        could be the location of an '@', 'export', or 'import'.
2758   /// \param ExportLoc The location of the 'export' keyword, if any.
2759   /// \param ImportLoc The location of the 'import' keyword.
2760   /// \param Path The module access path.
2761   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2762                                SourceLocation ExportLoc,
2763                                SourceLocation ImportLoc, ModuleIdPath Path);
2764   DeclResult ActOnModuleImport(SourceLocation StartLoc,
2765                                SourceLocation ExportLoc,
2766                                SourceLocation ImportLoc, Module *M,
2767                                ModuleIdPath Path = {});
2768 
2769   /// The parser has processed a module import translated from a
2770   /// #include or similar preprocessing directive.
2771   void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2772   void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2773 
2774   /// The parsed has entered a submodule.
2775   void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2776   /// The parser has left a submodule.
2777   void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2778 
2779   /// Create an implicit import of the given module at the given
2780   /// source location, for error recovery, if possible.
2781   ///
2782   /// This routine is typically used when an entity found by name lookup
2783   /// is actually hidden within a module that we know about but the user
2784   /// has forgotten to import.
2785   void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2786                                                   Module *Mod);
2787 
2788   /// Kinds of missing import. Note, the values of these enumerators correspond
2789   /// to %select values in diagnostics.
2790   enum class MissingImportKind {
2791     Declaration,
2792     Definition,
2793     DefaultArgument,
2794     ExplicitSpecialization,
2795     PartialSpecialization
2796   };
2797 
2798   /// Diagnose that the specified declaration needs to be visible but
2799   /// isn't, and suggest a module import that would resolve the problem.
2800   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2801                              MissingImportKind MIK, bool Recover = true);
2802   void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2803                              SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2804                              MissingImportKind MIK, bool Recover);
2805 
2806   Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2807                              SourceLocation LBraceLoc);
2808   Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2809                               SourceLocation RBraceLoc);
2810 
2811   /// We've found a use of a templated declaration that would trigger an
2812   /// implicit instantiation. Check that any relevant explicit specializations
2813   /// and partial specializations are visible, and diagnose if not.
2814   void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2815 
2816   /// We've found a use of a template specialization that would select a
2817   /// partial specialization. Check that the partial specialization is visible,
2818   /// and diagnose if not.
2819   void checkPartialSpecializationVisibility(SourceLocation Loc,
2820                                             NamedDecl *Spec);
2821 
2822   /// Retrieve a suitable printing policy for diagnostics.
getPrintingPolicy()2823   PrintingPolicy getPrintingPolicy() const {
2824     return getPrintingPolicy(Context, PP);
2825   }
2826 
2827   /// Retrieve a suitable printing policy for diagnostics.
2828   static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2829                                           const Preprocessor &PP);
2830 
2831   /// Scope actions.
2832   void ActOnPopScope(SourceLocation Loc, Scope *S);
2833   void ActOnTranslationUnitScope(Scope *S);
2834 
2835   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2836                                    RecordDecl *&AnonRecord);
2837   Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2838                                    MultiTemplateParamsArg TemplateParams,
2839                                    bool IsExplicitInstantiation,
2840                                    RecordDecl *&AnonRecord);
2841 
2842   Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2843                                     AccessSpecifier AS,
2844                                     RecordDecl *Record,
2845                                     const PrintingPolicy &Policy);
2846 
2847   Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2848                                        RecordDecl *Record);
2849 
2850   /// Common ways to introduce type names without a tag for use in diagnostics.
2851   /// Keep in sync with err_tag_reference_non_tag.
2852   enum NonTagKind {
2853     NTK_NonStruct,
2854     NTK_NonClass,
2855     NTK_NonUnion,
2856     NTK_NonEnum,
2857     NTK_Typedef,
2858     NTK_TypeAlias,
2859     NTK_Template,
2860     NTK_TypeAliasTemplate,
2861     NTK_TemplateTemplateArgument,
2862   };
2863 
2864   /// Given a non-tag type declaration, returns an enum useful for indicating
2865   /// what kind of non-tag type this is.
2866   NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2867 
2868   bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2869                                     TagTypeKind NewTag, bool isDefinition,
2870                                     SourceLocation NewTagLoc,
2871                                     const IdentifierInfo *Name);
2872 
2873   enum TagUseKind {
2874     TUK_Reference,   // Reference to a tag:  'struct foo *X;'
2875     TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
2876     TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
2877     TUK_Friend       // Friend declaration:  'friend struct foo;'
2878   };
2879 
2880   Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2881                  SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2882                  SourceLocation NameLoc, const ParsedAttributesView &Attr,
2883                  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2884                  MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2885                  bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2886                  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2887                  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2888                  SkipBodyInfo *SkipBody = nullptr);
2889 
2890   Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2891                                 unsigned TagSpec, SourceLocation TagLoc,
2892                                 CXXScopeSpec &SS, IdentifierInfo *Name,
2893                                 SourceLocation NameLoc,
2894                                 const ParsedAttributesView &Attr,
2895                                 MultiTemplateParamsArg TempParamLists);
2896 
2897   TypeResult ActOnDependentTag(Scope *S,
2898                                unsigned TagSpec,
2899                                TagUseKind TUK,
2900                                const CXXScopeSpec &SS,
2901                                IdentifierInfo *Name,
2902                                SourceLocation TagLoc,
2903                                SourceLocation NameLoc);
2904 
2905   void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2906                  IdentifierInfo *ClassName,
2907                  SmallVectorImpl<Decl *> &Decls);
2908   Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2909                    Declarator &D, Expr *BitfieldWidth);
2910 
2911   FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2912                          Declarator &D, Expr *BitfieldWidth,
2913                          InClassInitStyle InitStyle,
2914                          AccessSpecifier AS);
2915   MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2916                                    SourceLocation DeclStart, Declarator &D,
2917                                    Expr *BitfieldWidth,
2918                                    InClassInitStyle InitStyle,
2919                                    AccessSpecifier AS,
2920                                    const ParsedAttr &MSPropertyAttr);
2921 
2922   FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2923                             TypeSourceInfo *TInfo,
2924                             RecordDecl *Record, SourceLocation Loc,
2925                             bool Mutable, Expr *BitfieldWidth,
2926                             InClassInitStyle InitStyle,
2927                             SourceLocation TSSL,
2928                             AccessSpecifier AS, NamedDecl *PrevDecl,
2929                             Declarator *D = nullptr);
2930 
2931   bool CheckNontrivialField(FieldDecl *FD);
2932   void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2933 
2934   enum TrivialABIHandling {
2935     /// The triviality of a method unaffected by "trivial_abi".
2936     TAH_IgnoreTrivialABI,
2937 
2938     /// The triviality of a method affected by "trivial_abi".
2939     TAH_ConsiderTrivialABI
2940   };
2941 
2942   bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2943                               TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2944                               bool Diagnose = false);
2945 
2946   /// For a defaulted function, the kind of defaulted function that it is.
2947   class DefaultedFunctionKind {
2948     CXXSpecialMember SpecialMember : 8;
2949     DefaultedComparisonKind Comparison : 8;
2950 
2951   public:
DefaultedFunctionKind()2952     DefaultedFunctionKind()
2953         : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
2954     }
DefaultedFunctionKind(CXXSpecialMember CSM)2955     DefaultedFunctionKind(CXXSpecialMember CSM)
2956         : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)2957     DefaultedFunctionKind(DefaultedComparisonKind Comp)
2958         : SpecialMember(CXXInvalid), Comparison(Comp) {}
2959 
isSpecialMember()2960     bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
isComparison()2961     bool isComparison() const {
2962       return Comparison != DefaultedComparisonKind::None;
2963     }
2964 
2965     explicit operator bool() const {
2966       return isSpecialMember() || isComparison();
2967     }
2968 
asSpecialMember()2969     CXXSpecialMember asSpecialMember() const { return SpecialMember; }
asComparison()2970     DefaultedComparisonKind asComparison() const { return Comparison; }
2971 
2972     /// Get the index of this function kind for use in diagnostics.
getDiagnosticIndex()2973     unsigned getDiagnosticIndex() const {
2974       static_assert(CXXInvalid > CXXDestructor,
2975                     "invalid should have highest index");
2976       static_assert((unsigned)DefaultedComparisonKind::None == 0,
2977                     "none should be equal to zero");
2978       return SpecialMember + (unsigned)Comparison;
2979     }
2980   };
2981 
2982   DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
2983 
getSpecialMember(const CXXMethodDecl * MD)2984   CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
2985     return getDefaultedFunctionKind(MD).asSpecialMember();
2986   }
getDefaultedComparisonKind(const FunctionDecl * FD)2987   DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
2988     return getDefaultedFunctionKind(FD).asComparison();
2989   }
2990 
2991   void ActOnLastBitfield(SourceLocation DeclStart,
2992                          SmallVectorImpl<Decl *> &AllIvarDecls);
2993   Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2994                   Declarator &D, Expr *BitfieldWidth,
2995                   tok::ObjCKeywordKind visibility);
2996 
2997   // This is used for both record definitions and ObjC interface declarations.
2998   void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
2999                    ArrayRef<Decl *> Fields, SourceLocation LBrac,
3000                    SourceLocation RBrac, const ParsedAttributesView &AttrList);
3001 
3002   /// ActOnTagStartDefinition - Invoked when we have entered the
3003   /// scope of a tag's definition (e.g., for an enumeration, class,
3004   /// struct, or union).
3005   void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3006 
3007   /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3008   /// Differently from C++, actually parse the body and reject / error out
3009   /// in case of a structural mismatch.
3010   bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
3011                                 SkipBodyInfo &SkipBody);
3012 
3013   typedef void *SkippedDefinitionContext;
3014 
3015   /// Invoked when we enter a tag definition that we're skipping.
3016   SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3017 
3018   Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
3019 
3020   /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3021   /// C++ record definition's base-specifiers clause and are starting its
3022   /// member declarations.
3023   void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3024                                        SourceLocation FinalLoc,
3025                                        bool IsFinalSpelledSealed,
3026                                        SourceLocation LBraceLoc);
3027 
3028   /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3029   /// the definition of a tag (enumeration, class, struct, or union).
3030   void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3031                                 SourceRange BraceRange);
3032 
3033   void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3034 
3035   void ActOnObjCContainerFinishDefinition();
3036 
3037   /// Invoked when we must temporarily exit the objective-c container
3038   /// scope for parsing/looking-up C constructs.
3039   ///
3040   /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3041   void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
3042   void ActOnObjCReenterContainerContext(DeclContext *DC);
3043 
3044   /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3045   /// error parsing the definition of a tag.
3046   void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3047 
3048   EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3049                                       EnumConstantDecl *LastEnumConst,
3050                                       SourceLocation IdLoc,
3051                                       IdentifierInfo *Id,
3052                                       Expr *val);
3053   bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3054   bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3055                               QualType EnumUnderlyingTy, bool IsFixed,
3056                               const EnumDecl *Prev);
3057 
3058   /// Determine whether the body of an anonymous enumeration should be skipped.
3059   /// \param II The name of the first enumerator.
3060   SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3061                                       SourceLocation IILoc);
3062 
3063   Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3064                           SourceLocation IdLoc, IdentifierInfo *Id,
3065                           const ParsedAttributesView &Attrs,
3066                           SourceLocation EqualLoc, Expr *Val);
3067   void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3068                      Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3069                      const ParsedAttributesView &Attr);
3070 
3071   /// Set the current declaration context until it gets popped.
3072   void PushDeclContext(Scope *S, DeclContext *DC);
3073   void PopDeclContext();
3074 
3075   /// EnterDeclaratorContext - Used when we must lookup names in the context
3076   /// of a declarator's nested name specifier.
3077   void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3078   void ExitDeclaratorContext(Scope *S);
3079 
3080   /// Enter a template parameter scope, after it's been associated with a particular
3081   /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3082   /// in the correct order.
3083   void EnterTemplatedContext(Scope *S, DeclContext *DC);
3084 
3085   /// Push the parameters of D, which must be a function, into scope.
3086   void ActOnReenterFunctionContext(Scope* S, Decl* D);
3087   void ActOnExitFunctionContext();
3088 
3089   DeclContext *getFunctionLevelDeclContext();
3090 
3091   /// getCurFunctionDecl - If inside of a function body, this returns a pointer
3092   /// to the function decl for the function being parsed.  If we're currently
3093   /// in a 'block', this returns the containing context.
3094   FunctionDecl *getCurFunctionDecl();
3095 
3096   /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3097   /// the method decl for the method being parsed.  If we're currently
3098   /// in a 'block', this returns the containing context.
3099   ObjCMethodDecl *getCurMethodDecl();
3100 
3101   /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3102   /// or C function we're in, otherwise return null.  If we're currently
3103   /// in a 'block', this returns the containing context.
3104   NamedDecl *getCurFunctionOrMethodDecl();
3105 
3106   /// Add this decl to the scope shadowed decl chains.
3107   void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3108 
3109   /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3110   /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3111   /// true if 'D' belongs to the given declaration context.
3112   ///
3113   /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3114   ///        enclosing namespace set of the context, rather than contained
3115   ///        directly within it.
3116   bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3117                      bool AllowInlineNamespace = false);
3118 
3119   /// Finds the scope corresponding to the given decl context, if it
3120   /// happens to be an enclosing scope.  Otherwise return NULL.
3121   static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3122 
3123   /// Subroutines of ActOnDeclarator().
3124   TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3125                                 TypeSourceInfo *TInfo);
3126   bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3127 
3128   /// Describes the kind of merge to perform for availability
3129   /// attributes (including "deprecated", "unavailable", and "availability").
3130   enum AvailabilityMergeKind {
3131     /// Don't merge availability attributes at all.
3132     AMK_None,
3133     /// Merge availability attributes for a redeclaration, which requires
3134     /// an exact match.
3135     AMK_Redeclaration,
3136     /// Merge availability attributes for an override, which requires
3137     /// an exact match or a weakening of constraints.
3138     AMK_Override,
3139     /// Merge availability attributes for an implementation of
3140     /// a protocol requirement.
3141     AMK_ProtocolImplementation,
3142   };
3143 
3144   /// Describes the kind of priority given to an availability attribute.
3145   ///
3146   /// The sum of priorities deteremines the final priority of the attribute.
3147   /// The final priority determines how the attribute will be merged.
3148   /// An attribute with a lower priority will always remove higher priority
3149   /// attributes for the specified platform when it is being applied. An
3150   /// attribute with a higher priority will not be applied if the declaration
3151   /// already has an availability attribute with a lower priority for the
3152   /// specified platform. The final prirority values are not expected to match
3153   /// the values in this enumeration, but instead should be treated as a plain
3154   /// integer value. This enumeration just names the priority weights that are
3155   /// used to calculate that final vaue.
3156   enum AvailabilityPriority : int {
3157     /// The availability attribute was specified explicitly next to the
3158     /// declaration.
3159     AP_Explicit = 0,
3160 
3161     /// The availability attribute was applied using '#pragma clang attribute'.
3162     AP_PragmaClangAttribute = 1,
3163 
3164     /// The availability attribute for a specific platform was inferred from
3165     /// an availability attribute for another platform.
3166     AP_InferredFromOtherPlatform = 2
3167   };
3168 
3169   /// Attribute merging methods. Return true if a new attribute was added.
3170   AvailabilityAttr *
3171   mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3172                         IdentifierInfo *Platform, bool Implicit,
3173                         VersionTuple Introduced, VersionTuple Deprecated,
3174                         VersionTuple Obsoleted, bool IsUnavailable,
3175                         StringRef Message, bool IsStrict, StringRef Replacement,
3176                         AvailabilityMergeKind AMK, int Priority);
3177   TypeVisibilityAttr *
3178   mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3179                           TypeVisibilityAttr::VisibilityType Vis);
3180   VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3181                                       VisibilityAttr::VisibilityType Vis);
3182   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3183                           StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3184   DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3185   DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3186   MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3187                                             const AttributeCommonInfo &CI,
3188                                             bool BestCase,
3189                                             MSInheritanceModel Model);
3190   FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3191                               IdentifierInfo *Format, int FormatIdx,
3192                               int FirstArg);
3193   SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3194                                 StringRef Name);
3195   CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3196                                 StringRef Name);
3197   AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3198                                           const AttributeCommonInfo &CI,
3199                                           const IdentifierInfo *Ident);
3200   MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3201   NoSpeculativeLoadHardeningAttr *
3202   mergeNoSpeculativeLoadHardeningAttr(Decl *D,
3203                                       const NoSpeculativeLoadHardeningAttr &AL);
3204   SpeculativeLoadHardeningAttr *
3205   mergeSpeculativeLoadHardeningAttr(Decl *D,
3206                                     const SpeculativeLoadHardeningAttr &AL);
3207   SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3208                                     StringRef Name);
3209   OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3210                                           const AttributeCommonInfo &CI);
3211   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3212   InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3213                                                 const InternalLinkageAttr &AL);
3214   CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
3215   CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
3216   WebAssemblyImportNameAttr *mergeImportNameAttr(
3217       Decl *D, const WebAssemblyImportNameAttr &AL);
3218   WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3219       Decl *D, const WebAssemblyImportModuleAttr &AL);
3220 
3221   void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3222                            AvailabilityMergeKind AMK = AMK_Redeclaration);
3223   void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3224                             LookupResult &OldDecls);
3225   bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3226                          bool MergeTypeWithOld);
3227   bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3228                                     Scope *S, bool MergeTypeWithOld);
3229   void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3230   void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3231   void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3232   void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3233   bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3234   void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3235   bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3236 
3237   // AssignmentAction - This is used by all the assignment diagnostic functions
3238   // to represent what is actually causing the operation
3239   enum AssignmentAction {
3240     AA_Assigning,
3241     AA_Passing,
3242     AA_Returning,
3243     AA_Converting,
3244     AA_Initializing,
3245     AA_Sending,
3246     AA_Casting,
3247     AA_Passing_CFAudited
3248   };
3249 
3250   /// C++ Overloading.
3251   enum OverloadKind {
3252     /// This is a legitimate overload: the existing declarations are
3253     /// functions or function templates with different signatures.
3254     Ovl_Overload,
3255 
3256     /// This is not an overload because the signature exactly matches
3257     /// an existing declaration.
3258     Ovl_Match,
3259 
3260     /// This is not an overload because the lookup results contain a
3261     /// non-function.
3262     Ovl_NonFunction
3263   };
3264   OverloadKind CheckOverload(Scope *S,
3265                              FunctionDecl *New,
3266                              const LookupResult &OldDecls,
3267                              NamedDecl *&OldDecl,
3268                              bool IsForUsingDecl);
3269   bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3270                   bool ConsiderCudaAttrs = true,
3271                   bool ConsiderRequiresClauses = true);
3272 
3273   enum class AllowedExplicit {
3274     /// Allow no explicit functions to be used.
3275     None,
3276     /// Allow explicit conversion functions but not explicit constructors.
3277     Conversions,
3278     /// Allow both explicit conversion functions and explicit constructors.
3279     All
3280   };
3281 
3282   ImplicitConversionSequence
3283   TryImplicitConversion(Expr *From, QualType ToType,
3284                         bool SuppressUserConversions,
3285                         AllowedExplicit AllowExplicit,
3286                         bool InOverloadResolution,
3287                         bool CStyle,
3288                         bool AllowObjCWritebackConversion);
3289 
3290   bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3291   bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3292   bool IsComplexPromotion(QualType FromType, QualType ToType);
3293   bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3294                            bool InOverloadResolution,
3295                            QualType& ConvertedType, bool &IncompatibleObjC);
3296   bool isObjCPointerConversion(QualType FromType, QualType ToType,
3297                                QualType& ConvertedType, bool &IncompatibleObjC);
3298   bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3299                                  QualType &ConvertedType);
3300   bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3301                                 QualType& ConvertedType);
3302   bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3303                                   const FunctionProtoType *NewType,
3304                                   unsigned *ArgPos = nullptr);
3305   void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3306                                   QualType FromType, QualType ToType);
3307 
3308   void maybeExtendBlockObject(ExprResult &E);
3309   CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3310   bool CheckPointerConversion(Expr *From, QualType ToType,
3311                               CastKind &Kind,
3312                               CXXCastPath& BasePath,
3313                               bool IgnoreBaseAccess,
3314                               bool Diagnose = true);
3315   bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3316                                  bool InOverloadResolution,
3317                                  QualType &ConvertedType);
3318   bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3319                                     CastKind &Kind,
3320                                     CXXCastPath &BasePath,
3321                                     bool IgnoreBaseAccess);
3322   bool IsQualificationConversion(QualType FromType, QualType ToType,
3323                                  bool CStyle, bool &ObjCLifetimeConversion);
3324   bool IsFunctionConversion(QualType FromType, QualType ToType,
3325                             QualType &ResultTy);
3326   bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3327   bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
3328 
3329   ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3330                                              const VarDecl *NRVOCandidate,
3331                                              QualType ResultType,
3332                                              Expr *Value,
3333                                              bool AllowNRVO = true);
3334 
3335   bool CanPerformAggregateInitializationForOverloadResolution(
3336       const InitializedEntity &Entity, InitListExpr *From);
3337 
3338   bool IsStringInit(Expr *Init, const ArrayType *AT);
3339 
3340   bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3341                                     ExprResult Init);
3342   ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3343                                        SourceLocation EqualLoc,
3344                                        ExprResult Init,
3345                                        bool TopLevelOfInitList = false,
3346                                        bool AllowExplicit = false);
3347   ExprResult PerformObjectArgumentInitialization(Expr *From,
3348                                                  NestedNameSpecifier *Qualifier,
3349                                                  NamedDecl *FoundDecl,
3350                                                  CXXMethodDecl *Method);
3351 
3352   /// Check that the lifetime of the initializer (and its subobjects) is
3353   /// sufficient for initializing the entity, and perform lifetime extension
3354   /// (when permitted) if not.
3355   void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3356 
3357   ExprResult PerformContextuallyConvertToBool(Expr *From);
3358   ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3359 
3360   /// Contexts in which a converted constant expression is required.
3361   enum CCEKind {
3362     CCEK_CaseValue,   ///< Expression in a case label.
3363     CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
3364     CCEK_TemplateArg, ///< Value of a non-type template parameter.
3365     CCEK_ArrayBound,  ///< Array bound in array declarator or new-expression.
3366     CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
3367     CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
3368   };
3369   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3370                                               llvm::APSInt &Value, CCEKind CCE);
3371   ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3372                                               APValue &Value, CCEKind CCE,
3373                                               NamedDecl *Dest = nullptr);
3374 
3375   /// Abstract base class used to perform a contextual implicit
3376   /// conversion from an expression to any type passing a filter.
3377   class ContextualImplicitConverter {
3378   public:
3379     bool Suppress;
3380     bool SuppressConversion;
3381 
3382     ContextualImplicitConverter(bool Suppress = false,
3383                                 bool SuppressConversion = false)
Suppress(Suppress)3384         : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3385 
3386     /// Determine whether the specified type is a valid destination type
3387     /// for this conversion.
3388     virtual bool match(QualType T) = 0;
3389 
3390     /// Emits a diagnostic complaining that the expression does not have
3391     /// integral or enumeration type.
3392     virtual SemaDiagnosticBuilder
3393     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3394 
3395     /// Emits a diagnostic when the expression has incomplete class type.
3396     virtual SemaDiagnosticBuilder
3397     diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3398 
3399     /// Emits a diagnostic when the only matching conversion function
3400     /// is explicit.
3401     virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3402         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3403 
3404     /// Emits a note for the explicit conversion function.
3405     virtual SemaDiagnosticBuilder
3406     noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3407 
3408     /// Emits a diagnostic when there are multiple possible conversion
3409     /// functions.
3410     virtual SemaDiagnosticBuilder
3411     diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3412 
3413     /// Emits a note for one of the candidate conversions.
3414     virtual SemaDiagnosticBuilder
3415     noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3416 
3417     /// Emits a diagnostic when we picked a conversion function
3418     /// (for cases when we are not allowed to pick a conversion function).
3419     virtual SemaDiagnosticBuilder diagnoseConversion(
3420         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3421 
~ContextualImplicitConverter()3422     virtual ~ContextualImplicitConverter() {}
3423   };
3424 
3425   class ICEConvertDiagnoser : public ContextualImplicitConverter {
3426     bool AllowScopedEnumerations;
3427 
3428   public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)3429     ICEConvertDiagnoser(bool AllowScopedEnumerations,
3430                         bool Suppress, bool SuppressConversion)
3431         : ContextualImplicitConverter(Suppress, SuppressConversion),
3432           AllowScopedEnumerations(AllowScopedEnumerations) {}
3433 
3434     /// Match an integral or (possibly scoped) enumeration type.
3435     bool match(QualType T) override;
3436 
3437     SemaDiagnosticBuilder
diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)3438     diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3439       return diagnoseNotInt(S, Loc, T);
3440     }
3441 
3442     /// Emits a diagnostic complaining that the expression does not have
3443     /// integral or enumeration type.
3444     virtual SemaDiagnosticBuilder
3445     diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3446   };
3447 
3448   /// Perform a contextual implicit conversion.
3449   ExprResult PerformContextualImplicitConversion(
3450       SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3451 
3452 
3453   enum ObjCSubscriptKind {
3454     OS_Array,
3455     OS_Dictionary,
3456     OS_Error
3457   };
3458   ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3459 
3460   // Note that LK_String is intentionally after the other literals, as
3461   // this is used for diagnostics logic.
3462   enum ObjCLiteralKind {
3463     LK_Array,
3464     LK_Dictionary,
3465     LK_Numeric,
3466     LK_Boxed,
3467     LK_String,
3468     LK_Block,
3469     LK_None
3470   };
3471   ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3472 
3473   ExprResult PerformObjectMemberConversion(Expr *From,
3474                                            NestedNameSpecifier *Qualifier,
3475                                            NamedDecl *FoundDecl,
3476                                            NamedDecl *Member);
3477 
3478   // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3479   // TODO: make this is a typesafe union.
3480   typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
3481   typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3482 
3483   using ADLCallKind = CallExpr::ADLCallKind;
3484 
3485   void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3486                             ArrayRef<Expr *> Args,
3487                             OverloadCandidateSet &CandidateSet,
3488                             bool SuppressUserConversions = false,
3489                             bool PartialOverloading = false,
3490                             bool AllowExplicit = true,
3491                             bool AllowExplicitConversion = false,
3492                             ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3493                             ConversionSequenceList EarlyConversions = None,
3494                             OverloadCandidateParamOrder PO = {});
3495   void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3496                       ArrayRef<Expr *> Args,
3497                       OverloadCandidateSet &CandidateSet,
3498                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3499                       bool SuppressUserConversions = false,
3500                       bool PartialOverloading = false,
3501                       bool FirstArgumentIsBase = false);
3502   void AddMethodCandidate(DeclAccessPair FoundDecl,
3503                           QualType ObjectType,
3504                           Expr::Classification ObjectClassification,
3505                           ArrayRef<Expr *> Args,
3506                           OverloadCandidateSet& CandidateSet,
3507                           bool SuppressUserConversion = false,
3508                           OverloadCandidateParamOrder PO = {});
3509   void AddMethodCandidate(CXXMethodDecl *Method,
3510                           DeclAccessPair FoundDecl,
3511                           CXXRecordDecl *ActingContext, QualType ObjectType,
3512                           Expr::Classification ObjectClassification,
3513                           ArrayRef<Expr *> Args,
3514                           OverloadCandidateSet& CandidateSet,
3515                           bool SuppressUserConversions = false,
3516                           bool PartialOverloading = false,
3517                           ConversionSequenceList EarlyConversions = None,
3518                           OverloadCandidateParamOrder PO = {});
3519   void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3520                                   DeclAccessPair FoundDecl,
3521                                   CXXRecordDecl *ActingContext,
3522                                  TemplateArgumentListInfo *ExplicitTemplateArgs,
3523                                   QualType ObjectType,
3524                                   Expr::Classification ObjectClassification,
3525                                   ArrayRef<Expr *> Args,
3526                                   OverloadCandidateSet& CandidateSet,
3527                                   bool SuppressUserConversions = false,
3528                                   bool PartialOverloading = false,
3529                                   OverloadCandidateParamOrder PO = {});
3530   void AddTemplateOverloadCandidate(
3531       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3532       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3533       OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3534       bool PartialOverloading = false, bool AllowExplicit = true,
3535       ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3536       OverloadCandidateParamOrder PO = {});
3537   bool CheckNonDependentConversions(
3538       FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3539       ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3540       ConversionSequenceList &Conversions, bool SuppressUserConversions,
3541       CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3542       Expr::Classification ObjectClassification = {},
3543       OverloadCandidateParamOrder PO = {});
3544   void AddConversionCandidate(
3545       CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3546       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3547       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3548       bool AllowExplicit, bool AllowResultConversion = true);
3549   void AddTemplateConversionCandidate(
3550       FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3551       CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3552       OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3553       bool AllowExplicit, bool AllowResultConversion = true);
3554   void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3555                              DeclAccessPair FoundDecl,
3556                              CXXRecordDecl *ActingContext,
3557                              const FunctionProtoType *Proto,
3558                              Expr *Object, ArrayRef<Expr *> Args,
3559                              OverloadCandidateSet& CandidateSet);
3560   void AddNonMemberOperatorCandidates(
3561       const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3562       OverloadCandidateSet &CandidateSet,
3563       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3564   void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3565                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
3566                                    OverloadCandidateSet &CandidateSet,
3567                                    OverloadCandidateParamOrder PO = {});
3568   void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3569                            OverloadCandidateSet& CandidateSet,
3570                            bool IsAssignmentOperator = false,
3571                            unsigned NumContextualBoolArguments = 0);
3572   void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3573                                     SourceLocation OpLoc, ArrayRef<Expr *> Args,
3574                                     OverloadCandidateSet& CandidateSet);
3575   void AddArgumentDependentLookupCandidates(DeclarationName Name,
3576                                             SourceLocation Loc,
3577                                             ArrayRef<Expr *> Args,
3578                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
3579                                             OverloadCandidateSet& CandidateSet,
3580                                             bool PartialOverloading = false);
3581 
3582   // Emit as a 'note' the specific overload candidate
3583   void NoteOverloadCandidate(
3584       NamedDecl *Found, FunctionDecl *Fn,
3585       OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3586       QualType DestType = QualType(), bool TakingAddress = false);
3587 
3588   // Emit as a series of 'note's all template and non-templates identified by
3589   // the expression Expr
3590   void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3591                                  bool TakingAddress = false);
3592 
3593   /// Check the enable_if expressions on the given function. Returns the first
3594   /// failing attribute, or NULL if they were all successful.
3595   EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3596                               ArrayRef<Expr *> Args,
3597                               bool MissingImplicitThis = false);
3598 
3599   /// Find the failed Boolean condition within a given Boolean
3600   /// constant expression, and describe it with a string.
3601   std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3602 
3603   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3604   /// non-ArgDependent DiagnoseIfAttrs.
3605   ///
3606   /// Argument-dependent diagnose_if attributes should be checked each time a
3607   /// function is used as a direct callee of a function call.
3608   ///
3609   /// Returns true if any errors were emitted.
3610   bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3611                                            const Expr *ThisArg,
3612                                            ArrayRef<const Expr *> Args,
3613                                            SourceLocation Loc);
3614 
3615   /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3616   /// ArgDependent DiagnoseIfAttrs.
3617   ///
3618   /// Argument-independent diagnose_if attributes should be checked on every use
3619   /// of a function.
3620   ///
3621   /// Returns true if any errors were emitted.
3622   bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3623                                              SourceLocation Loc);
3624 
3625   /// Returns whether the given function's address can be taken or not,
3626   /// optionally emitting a diagnostic if the address can't be taken.
3627   ///
3628   /// Returns false if taking the address of the function is illegal.
3629   bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3630                                          bool Complain = false,
3631                                          SourceLocation Loc = SourceLocation());
3632 
3633   // [PossiblyAFunctionType]  -->   [Return]
3634   // NonFunctionType --> NonFunctionType
3635   // R (A) --> R(A)
3636   // R (*)(A) --> R (A)
3637   // R (&)(A) --> R (A)
3638   // R (S::*)(A) --> R (A)
3639   QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3640 
3641   FunctionDecl *
3642   ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3643                                      QualType TargetType,
3644                                      bool Complain,
3645                                      DeclAccessPair &Found,
3646                                      bool *pHadMultipleCandidates = nullptr);
3647 
3648   FunctionDecl *
3649   resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3650 
3651   bool resolveAndFixAddressOfSingleOverloadCandidate(
3652       ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3653 
3654   FunctionDecl *
3655   ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3656                                               bool Complain = false,
3657                                               DeclAccessPair *Found = nullptr);
3658 
3659   bool ResolveAndFixSingleFunctionTemplateSpecialization(
3660                       ExprResult &SrcExpr,
3661                       bool DoFunctionPointerConverion = false,
3662                       bool Complain = false,
3663                       SourceRange OpRangeForComplaining = SourceRange(),
3664                       QualType DestTypeForComplaining = QualType(),
3665                       unsigned DiagIDForComplaining = 0);
3666 
3667 
3668   Expr *FixOverloadedFunctionReference(Expr *E,
3669                                        DeclAccessPair FoundDecl,
3670                                        FunctionDecl *Fn);
3671   ExprResult FixOverloadedFunctionReference(ExprResult,
3672                                             DeclAccessPair FoundDecl,
3673                                             FunctionDecl *Fn);
3674 
3675   void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3676                                    ArrayRef<Expr *> Args,
3677                                    OverloadCandidateSet &CandidateSet,
3678                                    bool PartialOverloading = false);
3679 
3680   // An enum used to represent the different possible results of building a
3681   // range-based for loop.
3682   enum ForRangeStatus {
3683     FRS_Success,
3684     FRS_NoViableFunction,
3685     FRS_DiagnosticIssued
3686   };
3687 
3688   ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3689                                            SourceLocation RangeLoc,
3690                                            const DeclarationNameInfo &NameInfo,
3691                                            LookupResult &MemberLookup,
3692                                            OverloadCandidateSet *CandidateSet,
3693                                            Expr *Range, ExprResult *CallExpr);
3694 
3695   ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3696                                      UnresolvedLookupExpr *ULE,
3697                                      SourceLocation LParenLoc,
3698                                      MultiExprArg Args,
3699                                      SourceLocation RParenLoc,
3700                                      Expr *ExecConfig,
3701                                      bool AllowTypoCorrection=true,
3702                                      bool CalleesAddressIsTaken=false);
3703 
3704   bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3705                               MultiExprArg Args, SourceLocation RParenLoc,
3706                               OverloadCandidateSet *CandidateSet,
3707                               ExprResult *Result);
3708 
3709   ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
3710                                         NestedNameSpecifierLoc NNSLoc,
3711                                         DeclarationNameInfo DNI,
3712                                         const UnresolvedSetImpl &Fns,
3713                                         bool PerformADL = true);
3714 
3715   ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
3716                                      UnaryOperatorKind Opc,
3717                                      const UnresolvedSetImpl &Fns,
3718                                      Expr *input, bool RequiresADL = true);
3719 
3720   void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
3721                              OverloadedOperatorKind Op,
3722                              const UnresolvedSetImpl &Fns,
3723                              ArrayRef<Expr *> Args, bool RequiresADL = true);
3724   ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
3725                                    BinaryOperatorKind Opc,
3726                                    const UnresolvedSetImpl &Fns,
3727                                    Expr *LHS, Expr *RHS,
3728                                    bool RequiresADL = true,
3729                                    bool AllowRewrittenCandidates = true,
3730                                    FunctionDecl *DefaultedFn = nullptr);
3731   ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
3732                                                 const UnresolvedSetImpl &Fns,
3733                                                 Expr *LHS, Expr *RHS,
3734                                                 FunctionDecl *DefaultedFn);
3735 
3736   ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
3737                                                 SourceLocation RLoc,
3738                                                 Expr *Base,Expr *Idx);
3739 
3740   ExprResult
3741   BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
3742                             SourceLocation LParenLoc,
3743                             MultiExprArg Args,
3744                             SourceLocation RParenLoc);
3745   ExprResult
3746   BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
3747                                MultiExprArg Args,
3748                                SourceLocation RParenLoc);
3749 
3750   ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
3751                                       SourceLocation OpLoc,
3752                                       bool *NoArrowOperatorFound = nullptr);
3753 
3754   /// CheckCallReturnType - Checks that a call expression's return type is
3755   /// complete. Returns true on failure. The location passed in is the location
3756   /// that best represents the call.
3757   bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
3758                            CallExpr *CE, FunctionDecl *FD);
3759 
3760   /// Helpers for dealing with blocks and functions.
3761   bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
3762                                 bool CheckParameterNames);
3763   void CheckCXXDefaultArguments(FunctionDecl *FD);
3764   void CheckExtraCXXDefaultArguments(Declarator &D);
3765   Scope *getNonFieldDeclScope(Scope *S);
3766 
3767   /// \name Name lookup
3768   ///
3769   /// These routines provide name lookup that is used during semantic
3770   /// analysis to resolve the various kinds of names (identifiers,
3771   /// overloaded operator names, constructor names, etc.) into zero or
3772   /// more declarations within a particular scope. The major entry
3773   /// points are LookupName, which performs unqualified name lookup,
3774   /// and LookupQualifiedName, which performs qualified name lookup.
3775   ///
3776   /// All name lookup is performed based on some specific criteria,
3777   /// which specify what names will be visible to name lookup and how
3778   /// far name lookup should work. These criteria are important both
3779   /// for capturing language semantics (certain lookups will ignore
3780   /// certain names, for example) and for performance, since name
3781   /// lookup is often a bottleneck in the compilation of C++. Name
3782   /// lookup criteria is specified via the LookupCriteria enumeration.
3783   ///
3784   /// The results of name lookup can vary based on the kind of name
3785   /// lookup performed, the current language, and the translation
3786   /// unit. In C, for example, name lookup will either return nothing
3787   /// (no entity found) or a single declaration. In C++, name lookup
3788   /// can additionally refer to a set of overloaded functions or
3789   /// result in an ambiguity. All of the possible results of name
3790   /// lookup are captured by the LookupResult class, which provides
3791   /// the ability to distinguish among them.
3792   //@{
3793 
3794   /// Describes the kind of name lookup to perform.
3795   enum LookupNameKind {
3796     /// Ordinary name lookup, which finds ordinary names (functions,
3797     /// variables, typedefs, etc.) in C and most kinds of names
3798     /// (functions, variables, members, types, etc.) in C++.
3799     LookupOrdinaryName = 0,
3800     /// Tag name lookup, which finds the names of enums, classes,
3801     /// structs, and unions.
3802     LookupTagName,
3803     /// Label name lookup.
3804     LookupLabel,
3805     /// Member name lookup, which finds the names of
3806     /// class/struct/union members.
3807     LookupMemberName,
3808     /// Look up of an operator name (e.g., operator+) for use with
3809     /// operator overloading. This lookup is similar to ordinary name
3810     /// lookup, but will ignore any declarations that are class members.
3811     LookupOperatorName,
3812     /// Look up a name following ~ in a destructor name. This is an ordinary
3813     /// lookup, but prefers tags to typedefs.
3814     LookupDestructorName,
3815     /// Look up of a name that precedes the '::' scope resolution
3816     /// operator in C++. This lookup completely ignores operator, object,
3817     /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3818     LookupNestedNameSpecifierName,
3819     /// Look up a namespace name within a C++ using directive or
3820     /// namespace alias definition, ignoring non-namespace names (C++
3821     /// [basic.lookup.udir]p1).
3822     LookupNamespaceName,
3823     /// Look up all declarations in a scope with the given name,
3824     /// including resolved using declarations.  This is appropriate
3825     /// for checking redeclarations for a using declaration.
3826     LookupUsingDeclName,
3827     /// Look up an ordinary name that is going to be redeclared as a
3828     /// name with linkage. This lookup ignores any declarations that
3829     /// are outside of the current scope unless they have linkage. See
3830     /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3831     LookupRedeclarationWithLinkage,
3832     /// Look up a friend of a local class. This lookup does not look
3833     /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3834     LookupLocalFriendName,
3835     /// Look up the name of an Objective-C protocol.
3836     LookupObjCProtocolName,
3837     /// Look up implicit 'self' parameter of an objective-c method.
3838     LookupObjCImplicitSelfParam,
3839     /// Look up the name of an OpenMP user-defined reduction operation.
3840     LookupOMPReductionName,
3841     /// Look up the name of an OpenMP user-defined mapper.
3842     LookupOMPMapperName,
3843     /// Look up any declaration with any name.
3844     LookupAnyName
3845   };
3846 
3847   /// Specifies whether (or how) name lookup is being performed for a
3848   /// redeclaration (vs. a reference).
3849   enum RedeclarationKind {
3850     /// The lookup is a reference to this name that is not for the
3851     /// purpose of redeclaring the name.
3852     NotForRedeclaration = 0,
3853     /// The lookup results will be used for redeclaration of a name,
3854     /// if an entity by that name already exists and is visible.
3855     ForVisibleRedeclaration,
3856     /// The lookup results will be used for redeclaration of a name
3857     /// with external linkage; non-visible lookup results with external linkage
3858     /// may also be found.
3859     ForExternalRedeclaration
3860   };
3861 
forRedeclarationInCurContext()3862   RedeclarationKind forRedeclarationInCurContext() {
3863     // A declaration with an owning module for linkage can never link against
3864     // anything that is not visible. We don't need to check linkage here; if
3865     // the context has internal linkage, redeclaration lookup won't find things
3866     // from other TUs, and we can't safely compute linkage yet in general.
3867     if (cast<Decl>(CurContext)
3868             ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3869       return ForVisibleRedeclaration;
3870     return ForExternalRedeclaration;
3871   }
3872 
3873   /// The possible outcomes of name lookup for a literal operator.
3874   enum LiteralOperatorLookupResult {
3875     /// The lookup resulted in an error.
3876     LOLR_Error,
3877     /// The lookup found no match but no diagnostic was issued.
3878     LOLR_ErrorNoDiagnostic,
3879     /// The lookup found a single 'cooked' literal operator, which
3880     /// expects a normal literal to be built and passed to it.
3881     LOLR_Cooked,
3882     /// The lookup found a single 'raw' literal operator, which expects
3883     /// a string literal containing the spelling of the literal token.
3884     LOLR_Raw,
3885     /// The lookup found an overload set of literal operator templates,
3886     /// which expect the characters of the spelling of the literal token to be
3887     /// passed as a non-type template argument pack.
3888     LOLR_Template,
3889     /// The lookup found an overload set of literal operator templates,
3890     /// which expect the character type and characters of the spelling of the
3891     /// string literal token to be passed as template arguments.
3892     LOLR_StringTemplatePack,
3893   };
3894 
3895   SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3896                                                   CXXSpecialMember SM,
3897                                                   bool ConstArg,
3898                                                   bool VolatileArg,
3899                                                   bool RValueThis,
3900                                                   bool ConstThis,
3901                                                   bool VolatileThis);
3902 
3903   typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3904   typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3905       TypoRecoveryCallback;
3906 
3907 private:
3908   bool CppLookupName(LookupResult &R, Scope *S);
3909 
3910   struct TypoExprState {
3911     std::unique_ptr<TypoCorrectionConsumer> Consumer;
3912     TypoDiagnosticGenerator DiagHandler;
3913     TypoRecoveryCallback RecoveryHandler;
3914     TypoExprState();
3915     TypoExprState(TypoExprState &&other) noexcept;
3916     TypoExprState &operator=(TypoExprState &&other) noexcept;
3917   };
3918 
3919   /// The set of unhandled TypoExprs and their associated state.
3920   llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3921 
3922   /// Creates a new TypoExpr AST node.
3923   TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3924                               TypoDiagnosticGenerator TDG,
3925                               TypoRecoveryCallback TRC, SourceLocation TypoLoc);
3926 
3927   // The set of known/encountered (unique, canonicalized) NamespaceDecls.
3928   //
3929   // The boolean value will be true to indicate that the namespace was loaded
3930   // from an AST/PCH file, or false otherwise.
3931   llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3932 
3933   /// Whether we have already loaded known namespaces from an extenal
3934   /// source.
3935   bool LoadedExternalKnownNamespaces;
3936 
3937   /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
3938   /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3939   /// should be skipped entirely.
3940   std::unique_ptr<TypoCorrectionConsumer>
3941   makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3942                              Sema::LookupNameKind LookupKind, Scope *S,
3943                              CXXScopeSpec *SS,
3944                              CorrectionCandidateCallback &CCC,
3945                              DeclContext *MemberContext, bool EnteringContext,
3946                              const ObjCObjectPointerType *OPT,
3947                              bool ErrorRecovery);
3948 
3949 public:
3950   const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3951 
3952   /// Clears the state of the given TypoExpr.
3953   void clearDelayedTypo(TypoExpr *TE);
3954 
3955   /// Look up a name, looking for a single declaration.  Return
3956   /// null if the results were absent, ambiguous, or overloaded.
3957   ///
3958   /// It is preferable to use the elaborated form and explicitly handle
3959   /// ambiguity and overloaded.
3960   NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3961                               SourceLocation Loc,
3962                               LookupNameKind NameKind,
3963                               RedeclarationKind Redecl
3964                                 = NotForRedeclaration);
3965   bool LookupBuiltin(LookupResult &R);
3966   void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
3967   bool LookupName(LookupResult &R, Scope *S,
3968                   bool AllowBuiltinCreation = false);
3969   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3970                            bool InUnqualifiedLookup = false);
3971   bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3972                            CXXScopeSpec &SS);
3973   bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3974                         bool AllowBuiltinCreation = false,
3975                         bool EnteringContext = false);
3976   ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3977                                    RedeclarationKind Redecl
3978                                      = NotForRedeclaration);
3979   bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3980 
3981   void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3982                                     UnresolvedSetImpl &Functions);
3983 
3984   LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3985                                  SourceLocation GnuLabelLoc = SourceLocation());
3986 
3987   DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3988   CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3989   CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3990                                                unsigned Quals);
3991   CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3992                                          bool RValueThis, unsigned ThisQuals);
3993   CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3994                                               unsigned Quals);
3995   CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3996                                         bool RValueThis, unsigned ThisQuals);
3997   CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3998 
3999   bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
4000   LiteralOperatorLookupResult
4001   LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4002                         bool AllowRaw, bool AllowTemplate,
4003                         bool AllowStringTemplate, bool DiagnoseMissing,
4004                         StringLiteral *StringLit = nullptr);
4005   bool isKnownName(StringRef name);
4006 
4007   /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4008   enum class FunctionEmissionStatus {
4009     Emitted,
4010     CUDADiscarded,     // Discarded due to CUDA/HIP hostness
4011     OMPDiscarded,      // Discarded due to OpenMP hostness
4012     TemplateDiscarded, // Discarded due to uninstantiated templates
4013     Unknown,
4014   };
4015   FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4016                                            bool Final = false);
4017 
4018   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4019   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4020 
4021   void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4022                                ArrayRef<Expr *> Args, ADLResult &Functions);
4023 
4024   void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4025                           VisibleDeclConsumer &Consumer,
4026                           bool IncludeGlobalScope = true,
4027                           bool LoadExternal = true);
4028   void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4029                           VisibleDeclConsumer &Consumer,
4030                           bool IncludeGlobalScope = true,
4031                           bool IncludeDependentBases = false,
4032                           bool LoadExternal = true);
4033 
4034   enum CorrectTypoKind {
4035     CTK_NonError,     // CorrectTypo used in a non error recovery situation.
4036     CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4037   };
4038 
4039   TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4040                              Sema::LookupNameKind LookupKind,
4041                              Scope *S, CXXScopeSpec *SS,
4042                              CorrectionCandidateCallback &CCC,
4043                              CorrectTypoKind Mode,
4044                              DeclContext *MemberContext = nullptr,
4045                              bool EnteringContext = false,
4046                              const ObjCObjectPointerType *OPT = nullptr,
4047                              bool RecordFailure = true);
4048 
4049   TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4050                                Sema::LookupNameKind LookupKind, Scope *S,
4051                                CXXScopeSpec *SS,
4052                                CorrectionCandidateCallback &CCC,
4053                                TypoDiagnosticGenerator TDG,
4054                                TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4055                                DeclContext *MemberContext = nullptr,
4056                                bool EnteringContext = false,
4057                                const ObjCObjectPointerType *OPT = nullptr);
4058 
4059   /// Process any TypoExprs in the given Expr and its children,
4060   /// generating diagnostics as appropriate and returning a new Expr if there
4061   /// were typos that were all successfully corrected and ExprError if one or
4062   /// more typos could not be corrected.
4063   ///
4064   /// \param E The Expr to check for TypoExprs.
4065   ///
4066   /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4067   /// initializer.
4068   ///
4069   /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4070   /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4071   ///
4072   /// \param Filter A function applied to a newly rebuilt Expr to determine if
4073   /// it is an acceptable/usable result from a single combination of typo
4074   /// corrections. As long as the filter returns ExprError, different
4075   /// combinations of corrections will be tried until all are exhausted.
4076   ExprResult CorrectDelayedTyposInExpr(
4077       Expr *E, VarDecl *InitDecl = nullptr,
4078       bool RecoverUncorrectedTypos = false,
4079       llvm::function_ref<ExprResult(Expr *)> Filter =
4080           [](Expr *E) -> ExprResult { return E; });
4081 
4082   ExprResult CorrectDelayedTyposInExpr(
4083       ExprResult ER, VarDecl *InitDecl = nullptr,
4084       bool RecoverUncorrectedTypos = false,
4085       llvm::function_ref<ExprResult(Expr *)> Filter =
4086           [](Expr *E) -> ExprResult { return E; }) {
4087     return ER.isInvalid()
4088                ? ER
4089                : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4090                                            RecoverUncorrectedTypos, Filter);
4091   }
4092 
4093   void diagnoseTypo(const TypoCorrection &Correction,
4094                     const PartialDiagnostic &TypoDiag,
4095                     bool ErrorRecovery = true);
4096 
4097   void diagnoseTypo(const TypoCorrection &Correction,
4098                     const PartialDiagnostic &TypoDiag,
4099                     const PartialDiagnostic &PrevNote,
4100                     bool ErrorRecovery = true);
4101 
4102   void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4103 
4104   void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4105                                           ArrayRef<Expr *> Args,
4106                                    AssociatedNamespaceSet &AssociatedNamespaces,
4107                                    AssociatedClassSet &AssociatedClasses);
4108 
4109   void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4110                             bool ConsiderLinkage, bool AllowInlineNamespace);
4111 
4112   bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4113 
4114   void DiagnoseAmbiguousLookup(LookupResult &Result);
4115   //@}
4116 
4117   /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4118   ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4119                                 ArrayRef<Expr *> SubExprs,
4120                                 QualType T = QualType());
4121 
4122   ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4123                                           SourceLocation IdLoc,
4124                                           bool TypoCorrection = false);
4125   FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4126                               SourceLocation Loc);
4127   NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4128                                  Scope *S, bool ForRedeclaration,
4129                                  SourceLocation Loc);
4130   NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4131                                       Scope *S);
4132   void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4133       FunctionDecl *FD);
4134   void AddKnownFunctionAttributes(FunctionDecl *FD);
4135 
4136   // More parsing and symbol table subroutines.
4137 
4138   void ProcessPragmaWeak(Scope *S, Decl *D);
4139   // Decl attributes - this routine is the top level dispatcher.
4140   void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4141   // Helper for delayed processing of attributes.
4142   void ProcessDeclAttributeDelayed(Decl *D,
4143                                    const ParsedAttributesView &AttrList);
4144   void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4145                              bool IncludeCXX11Attributes = true);
4146   bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4147                                    const ParsedAttributesView &AttrList);
4148 
4149   void checkUnusedDeclAttributes(Declarator &D);
4150 
4151   /// Determine if type T is a valid subject for a nonnull and similar
4152   /// attributes. By default, we look through references (the behavior used by
4153   /// nonnull), but if the second parameter is true, then we treat a reference
4154   /// type as valid.
4155   bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4156 
4157   bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4158   bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4159                             const FunctionDecl *FD = nullptr);
4160   bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4161   bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4162   bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4163                                       StringRef &Str,
4164                                       SourceLocation *ArgLocation = nullptr);
4165   bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4166   bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4167   bool checkMSInheritanceAttrOnDefinition(
4168       CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4169       MSInheritanceModel SemanticSpelling);
4170 
4171   void CheckAlignasUnderalignment(Decl *D);
4172 
4173   /// Adjust the calling convention of a method to be the ABI default if it
4174   /// wasn't specified explicitly.  This handles method types formed from
4175   /// function type typedefs and typename template arguments.
4176   void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4177                               SourceLocation Loc);
4178 
4179   // Check if there is an explicit attribute, but only look through parens.
4180   // The intent is to look for an attribute on the current declarator, but not
4181   // one that came from a typedef.
4182   bool hasExplicitCallingConv(QualType T);
4183 
4184   /// Get the outermost AttributedType node that sets a calling convention.
4185   /// Valid types should not have multiple attributes with different CCs.
4186   const AttributedType *getCallingConvAttributedType(QualType T) const;
4187 
4188   /// Stmt attributes - this routine is the top level dispatcher.
4189   StmtResult ProcessStmtAttributes(Stmt *Stmt,
4190                                    const ParsedAttributesView &Attrs,
4191                                    SourceRange Range);
4192 
4193   void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4194                                    ObjCMethodDecl *MethodDecl,
4195                                    bool IsProtocolMethodDecl);
4196 
4197   void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4198                                    ObjCMethodDecl *Overridden,
4199                                    bool IsProtocolMethodDecl);
4200 
4201   /// WarnExactTypedMethods - This routine issues a warning if method
4202   /// implementation declaration matches exactly that of its declaration.
4203   void WarnExactTypedMethods(ObjCMethodDecl *Method,
4204                              ObjCMethodDecl *MethodDecl,
4205                              bool IsProtocolMethodDecl);
4206 
4207   typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4208 
4209   /// CheckImplementationIvars - This routine checks if the instance variables
4210   /// listed in the implelementation match those listed in the interface.
4211   void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4212                                 ObjCIvarDecl **Fields, unsigned nIvars,
4213                                 SourceLocation Loc);
4214 
4215   /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4216   /// remains unimplemented in the class or category \@implementation.
4217   void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4218                                  ObjCContainerDecl* IDecl,
4219                                  bool IncompleteImpl = false);
4220 
4221   /// DiagnoseUnimplementedProperties - This routine warns on those properties
4222   /// which must be implemented by this implementation.
4223   void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4224                                        ObjCContainerDecl *CDecl,
4225                                        bool SynthesizeProperties);
4226 
4227   /// Diagnose any null-resettable synthesized setters.
4228   void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4229 
4230   /// DefaultSynthesizeProperties - This routine default synthesizes all
4231   /// properties which must be synthesized in the class's \@implementation.
4232   void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4233                                    ObjCInterfaceDecl *IDecl,
4234                                    SourceLocation AtEnd);
4235   void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4236 
4237   /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4238   /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4239   /// declared in class 'IFace'.
4240   bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4241                                       ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4242 
4243   /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4244   /// backs the property is not used in the property's accessor.
4245   void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4246                                            const ObjCImplementationDecl *ImplD);
4247 
4248   /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4249   /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4250   /// It also returns ivar's property on success.
4251   ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4252                                                const ObjCPropertyDecl *&PDecl) const;
4253 
4254   /// Called by ActOnProperty to handle \@property declarations in
4255   /// class extensions.
4256   ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4257                       SourceLocation AtLoc,
4258                       SourceLocation LParenLoc,
4259                       FieldDeclarator &FD,
4260                       Selector GetterSel,
4261                       SourceLocation GetterNameLoc,
4262                       Selector SetterSel,
4263                       SourceLocation SetterNameLoc,
4264                       const bool isReadWrite,
4265                       unsigned &Attributes,
4266                       const unsigned AttributesAsWritten,
4267                       QualType T,
4268                       TypeSourceInfo *TSI,
4269                       tok::ObjCKeywordKind MethodImplKind);
4270 
4271   /// Called by ActOnProperty and HandlePropertyInClassExtension to
4272   /// handle creating the ObjcPropertyDecl for a category or \@interface.
4273   ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4274                                        ObjCContainerDecl *CDecl,
4275                                        SourceLocation AtLoc,
4276                                        SourceLocation LParenLoc,
4277                                        FieldDeclarator &FD,
4278                                        Selector GetterSel,
4279                                        SourceLocation GetterNameLoc,
4280                                        Selector SetterSel,
4281                                        SourceLocation SetterNameLoc,
4282                                        const bool isReadWrite,
4283                                        const unsigned Attributes,
4284                                        const unsigned AttributesAsWritten,
4285                                        QualType T,
4286                                        TypeSourceInfo *TSI,
4287                                        tok::ObjCKeywordKind MethodImplKind,
4288                                        DeclContext *lexicalDC = nullptr);
4289 
4290   /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4291   /// warning) when atomic property has one but not the other user-declared
4292   /// setter or getter.
4293   void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4294                                        ObjCInterfaceDecl* IDecl);
4295 
4296   void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4297 
4298   void DiagnoseMissingDesignatedInitOverrides(
4299                                           const ObjCImplementationDecl *ImplD,
4300                                           const ObjCInterfaceDecl *IFD);
4301 
4302   void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4303 
4304   enum MethodMatchStrategy {
4305     MMS_loose,
4306     MMS_strict
4307   };
4308 
4309   /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4310   /// true, or false, accordingly.
4311   bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4312                                   const ObjCMethodDecl *PrevMethod,
4313                                   MethodMatchStrategy strategy = MMS_strict);
4314 
4315   /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4316   /// or protocol against those declared in their implementations.
4317   void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4318                                   const SelectorSet &ClsMap,
4319                                   SelectorSet &InsMapSeen,
4320                                   SelectorSet &ClsMapSeen,
4321                                   ObjCImplDecl* IMPDecl,
4322                                   ObjCContainerDecl* IDecl,
4323                                   bool &IncompleteImpl,
4324                                   bool ImmediateClass,
4325                                   bool WarnCategoryMethodImpl=false);
4326 
4327   /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4328   /// category matches with those implemented in its primary class and
4329   /// warns each time an exact match is found.
4330   void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4331 
4332   /// Add the given method to the list of globally-known methods.
4333   void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4334 
4335   /// Returns default addr space for method qualifiers.
4336   LangAS getDefaultCXXMethodAddrSpace() const;
4337 
4338 private:
4339   /// AddMethodToGlobalPool - Add an instance or factory method to the global
4340   /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4341   void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4342 
4343   /// LookupMethodInGlobalPool - Returns the instance or factory method and
4344   /// optionally warns if there are multiple signatures.
4345   ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4346                                            bool receiverIdOrClass,
4347                                            bool instance);
4348 
4349 public:
4350   /// - Returns instance or factory methods in global method pool for
4351   /// given selector. It checks the desired kind first, if none is found, and
4352   /// parameter checkTheOther is set, it then checks the other kind. If no such
4353   /// method or only one method is found, function returns false; otherwise, it
4354   /// returns true.
4355   bool
4356   CollectMultipleMethodsInGlobalPool(Selector Sel,
4357                                      SmallVectorImpl<ObjCMethodDecl*>& Methods,
4358                                      bool InstanceFirst, bool CheckTheOther,
4359                                      const ObjCObjectType *TypeBound = nullptr);
4360 
4361   bool
4362   AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4363                                  SourceRange R, bool receiverIdOrClass,
4364                                  SmallVectorImpl<ObjCMethodDecl*>& Methods);
4365 
4366   void
4367   DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4368                                      Selector Sel, SourceRange R,
4369                                      bool receiverIdOrClass);
4370 
4371 private:
4372   /// - Returns a selector which best matches given argument list or
4373   /// nullptr if none could be found
4374   ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4375                                    bool IsInstance,
4376                                    SmallVectorImpl<ObjCMethodDecl*>& Methods);
4377 
4378 
4379   /// Record the typo correction failure and return an empty correction.
4380   TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4381                                   bool RecordFailure = true) {
4382     if (RecordFailure)
4383       TypoCorrectionFailures[Typo].insert(TypoLoc);
4384     return TypoCorrection();
4385   }
4386 
4387 public:
4388   /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4389   /// unit are added to a global pool. This allows us to efficiently associate
4390   /// a selector with a method declaraation for purposes of typechecking
4391   /// messages sent to "id" (where the class of the object is unknown).
4392   void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4393     AddMethodToGlobalPool(Method, impl, /*instance*/true);
4394   }
4395 
4396   /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4397   void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4398     AddMethodToGlobalPool(Method, impl, /*instance*/false);
4399   }
4400 
4401   /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4402   /// pool.
4403   void AddAnyMethodToGlobalPool(Decl *D);
4404 
4405   /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4406   /// there are multiple signatures.
4407   ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4408                                                    bool receiverIdOrClass=false) {
4409     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4410                                     /*instance*/true);
4411   }
4412 
4413   /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4414   /// there are multiple signatures.
4415   ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4416                                                   bool receiverIdOrClass=false) {
4417     return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4418                                     /*instance*/false);
4419   }
4420 
4421   const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4422                               QualType ObjectType=QualType());
4423   /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4424   /// implementation.
4425   ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4426 
4427   /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4428   /// initialization.
4429   void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4430                                   SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4431 
4432   //===--------------------------------------------------------------------===//
4433   // Statement Parsing Callbacks: SemaStmt.cpp.
4434 public:
4435   class FullExprArg {
4436   public:
FullExprArg()4437     FullExprArg() : E(nullptr) { }
FullExprArg(Sema & actions)4438     FullExprArg(Sema &actions) : E(nullptr) { }
4439 
release()4440     ExprResult release() {
4441       return E;
4442     }
4443 
get()4444     Expr *get() const { return E; }
4445 
4446     Expr *operator->() {
4447       return E;
4448     }
4449 
4450   private:
4451     // FIXME: No need to make the entire Sema class a friend when it's just
4452     // Sema::MakeFullExpr that needs access to the constructor below.
4453     friend class Sema;
4454 
FullExprArg(Expr * expr)4455     explicit FullExprArg(Expr *expr) : E(expr) {}
4456 
4457     Expr *E;
4458   };
4459 
MakeFullExpr(Expr * Arg)4460   FullExprArg MakeFullExpr(Expr *Arg) {
4461     return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4462   }
MakeFullExpr(Expr * Arg,SourceLocation CC)4463   FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4464     return FullExprArg(
4465         ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4466   }
MakeFullDiscardedValueExpr(Expr * Arg)4467   FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4468     ExprResult FE =
4469         ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4470                             /*DiscardedValue*/ true);
4471     return FullExprArg(FE.get());
4472   }
4473 
4474   StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4475   StmtResult ActOnExprStmtError();
4476 
4477   StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4478                            bool HasLeadingEmptyMacro = false);
4479 
4480   void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4481   void ActOnAfterCompoundStatementLeadingPragmas();
4482   void ActOnFinishOfCompoundStmt();
4483   StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4484                                ArrayRef<Stmt *> Elts, bool isStmtExpr);
4485 
4486   /// A RAII object to enter scope of a compound statement.
4487   class CompoundScopeRAII {
4488   public:
S(S)4489     CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4490       S.ActOnStartOfCompoundStmt(IsStmtExpr);
4491     }
4492 
~CompoundScopeRAII()4493     ~CompoundScopeRAII() {
4494       S.ActOnFinishOfCompoundStmt();
4495     }
4496 
4497   private:
4498     Sema &S;
4499   };
4500 
4501   /// An RAII helper that pops function a function scope on exit.
4502   struct FunctionScopeRAII {
4503     Sema &S;
4504     bool Active;
FunctionScopeRAIIFunctionScopeRAII4505     FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAIIFunctionScopeRAII4506     ~FunctionScopeRAII() {
4507       if (Active)
4508         S.PopFunctionScopeInfo();
4509     }
disableFunctionScopeRAII4510     void disable() { Active = false; }
4511   };
4512 
4513   StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4514                                    SourceLocation StartLoc,
4515                                    SourceLocation EndLoc);
4516   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4517   StmtResult ActOnForEachLValueExpr(Expr *E);
4518   ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4519   StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4520                            SourceLocation DotDotDotLoc, ExprResult RHS,
4521                            SourceLocation ColonLoc);
4522   void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4523 
4524   StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4525                                       SourceLocation ColonLoc,
4526                                       Stmt *SubStmt, Scope *CurScope);
4527   StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4528                             SourceLocation ColonLoc, Stmt *SubStmt);
4529 
4530   StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
4531                                  ArrayRef<const Attr*> Attrs,
4532                                  Stmt *SubStmt);
4533 
4534   class ConditionResult;
4535   StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4536                          SourceLocation LParenLoc, Stmt *InitStmt,
4537                          ConditionResult Cond, SourceLocation RParenLoc,
4538                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4539   StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
4540                          SourceLocation LParenLoc, Stmt *InitStmt,
4541                          ConditionResult Cond, SourceLocation RParenLoc,
4542                          Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4543   StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4544                                     SourceLocation LParenLoc, Stmt *InitStmt,
4545                                     ConditionResult Cond,
4546                                     SourceLocation RParenLoc);
4547   StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4548                                            Stmt *Switch, Stmt *Body);
4549   StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4550                             ConditionResult Cond, SourceLocation RParenLoc,
4551                             Stmt *Body);
4552   StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4553                          SourceLocation WhileLoc, SourceLocation CondLParen,
4554                          Expr *Cond, SourceLocation CondRParen);
4555 
4556   StmtResult ActOnForStmt(SourceLocation ForLoc,
4557                           SourceLocation LParenLoc,
4558                           Stmt *First,
4559                           ConditionResult Second,
4560                           FullExprArg Third,
4561                           SourceLocation RParenLoc,
4562                           Stmt *Body);
4563   ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4564                                            Expr *collection);
4565   StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4566                                         Stmt *First, Expr *collection,
4567                                         SourceLocation RParenLoc);
4568   StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4569 
4570   enum BuildForRangeKind {
4571     /// Initial building of a for-range statement.
4572     BFRK_Build,
4573     /// Instantiation or recovery rebuild of a for-range statement. Don't
4574     /// attempt any typo-correction.
4575     BFRK_Rebuild,
4576     /// Determining whether a for-range statement could be built. Avoid any
4577     /// unnecessary or irreversible actions.
4578     BFRK_Check
4579   };
4580 
4581   StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4582                                   SourceLocation CoawaitLoc,
4583                                   Stmt *InitStmt,
4584                                   Stmt *LoopVar,
4585                                   SourceLocation ColonLoc, Expr *Collection,
4586                                   SourceLocation RParenLoc,
4587                                   BuildForRangeKind Kind);
4588   StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4589                                   SourceLocation CoawaitLoc,
4590                                   Stmt *InitStmt,
4591                                   SourceLocation ColonLoc,
4592                                   Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4593                                   Expr *Cond, Expr *Inc,
4594                                   Stmt *LoopVarDecl,
4595                                   SourceLocation RParenLoc,
4596                                   BuildForRangeKind Kind);
4597   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4598 
4599   StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4600                            SourceLocation LabelLoc,
4601                            LabelDecl *TheDecl);
4602   StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4603                                    SourceLocation StarLoc,
4604                                    Expr *DestExp);
4605   StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4606   StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4607 
4608   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4609                                 CapturedRegionKind Kind, unsigned NumParams);
4610   typedef std::pair<StringRef, QualType> CapturedParamNameType;
4611   void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4612                                 CapturedRegionKind Kind,
4613                                 ArrayRef<CapturedParamNameType> Params,
4614                                 unsigned OpenMPCaptureLevel = 0);
4615   StmtResult ActOnCapturedRegionEnd(Stmt *S);
4616   void ActOnCapturedRegionError();
4617   RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4618                                            SourceLocation Loc,
4619                                            unsigned NumParams);
4620 
4621   enum CopyElisionSemanticsKind {
4622     CES_Strict = 0,
4623     CES_AllowParameters = 1,
4624     CES_AllowDifferentTypes = 2,
4625     CES_AllowExceptionVariables = 4,
4626     CES_FormerDefault = (CES_AllowParameters),
4627     CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
4628     CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
4629                          CES_AllowExceptionVariables),
4630   };
4631 
4632   VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
4633                                    CopyElisionSemanticsKind CESK);
4634   bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
4635                               CopyElisionSemanticsKind CESK);
4636 
4637   StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4638                              Scope *CurScope);
4639   StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4640   StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
4641 
4642   StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4643                              bool IsVolatile, unsigned NumOutputs,
4644                              unsigned NumInputs, IdentifierInfo **Names,
4645                              MultiExprArg Constraints, MultiExprArg Exprs,
4646                              Expr *AsmString, MultiExprArg Clobbers,
4647                              unsigned NumLabels,
4648                              SourceLocation RParenLoc);
4649 
4650   void FillInlineAsmIdentifierInfo(Expr *Res,
4651                                    llvm::InlineAsmIdentifierInfo &Info);
4652   ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4653                                        SourceLocation TemplateKWLoc,
4654                                        UnqualifiedId &Id,
4655                                        bool IsUnevaluatedContext);
4656   bool LookupInlineAsmField(StringRef Base, StringRef Member,
4657                             unsigned &Offset, SourceLocation AsmLoc);
4658   ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4659                                          SourceLocation AsmLoc);
4660   StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4661                             ArrayRef<Token> AsmToks,
4662                             StringRef AsmString,
4663                             unsigned NumOutputs, unsigned NumInputs,
4664                             ArrayRef<StringRef> Constraints,
4665                             ArrayRef<StringRef> Clobbers,
4666                             ArrayRef<Expr*> Exprs,
4667                             SourceLocation EndLoc);
4668   LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4669                                    SourceLocation Location,
4670                                    bool AlwaysCreate);
4671 
4672   VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4673                                   SourceLocation StartLoc,
4674                                   SourceLocation IdLoc, IdentifierInfo *Id,
4675                                   bool Invalid = false);
4676 
4677   Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4678 
4679   StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4680                                   Decl *Parm, Stmt *Body);
4681 
4682   StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
4683 
4684   StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
4685                                 MultiStmtArg Catch, Stmt *Finally);
4686 
4687   StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
4688   StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
4689                                   Scope *CurScope);
4690   ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
4691                                             Expr *operand);
4692   StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
4693                                          Expr *SynchExpr,
4694                                          Stmt *SynchBody);
4695 
4696   StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
4697 
4698   VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
4699                                      SourceLocation StartLoc,
4700                                      SourceLocation IdLoc,
4701                                      IdentifierInfo *Id);
4702 
4703   Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
4704 
4705   StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
4706                                 Decl *ExDecl, Stmt *HandlerBlock);
4707   StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4708                               ArrayRef<Stmt *> Handlers);
4709 
4710   StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
4711                               SourceLocation TryLoc, Stmt *TryBlock,
4712                               Stmt *Handler);
4713   StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
4714                                  Expr *FilterExpr,
4715                                  Stmt *Block);
4716   void ActOnStartSEHFinallyBlock();
4717   void ActOnAbortSEHFinallyBlock();
4718   StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
4719   StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
4720 
4721   void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
4722 
4723   bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4724 
4725   /// If it's a file scoped decl that must warn if not used, keep track
4726   /// of it.
4727   void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4728 
4729   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
4730   /// whose result is unused, warn.
4731   void DiagnoseUnusedExprResult(const Stmt *S);
4732   void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4733   void DiagnoseUnusedDecl(const NamedDecl *ND);
4734 
4735   /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
4736   /// statement as a \p Body, and it is located on the same line.
4737   ///
4738   /// This helps prevent bugs due to typos, such as:
4739   ///     if (condition);
4740   ///       do_stuff();
4741   void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4742                              const Stmt *Body,
4743                              unsigned DiagID);
4744 
4745   /// Warn if a for/while loop statement \p S, which is followed by
4746   /// \p PossibleBody, has a suspicious null statement as a body.
4747   void DiagnoseEmptyLoopBody(const Stmt *S,
4748                              const Stmt *PossibleBody);
4749 
4750   /// Warn if a value is moved to itself.
4751   void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
4752                         SourceLocation OpLoc);
4753 
4754   /// Warn if we're implicitly casting from a _Nullable pointer type to a
4755   /// _Nonnull one.
4756   void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
4757                                            SourceLocation Loc);
4758 
4759   /// Warn when implicitly casting 0 to nullptr.
4760   void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
4761 
PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)4762   ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
4763     return DelayedDiagnostics.push(pool);
4764   }
4765   void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
4766 
4767   typedef ProcessingContextState ParsingClassState;
PushParsingClass()4768   ParsingClassState PushParsingClass() {
4769     ParsingClassDepth++;
4770     return DelayedDiagnostics.pushUndelayed();
4771   }
PopParsingClass(ParsingClassState state)4772   void PopParsingClass(ParsingClassState state) {
4773     ParsingClassDepth--;
4774     DelayedDiagnostics.popUndelayed(state);
4775   }
4776 
4777   void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
4778 
4779   void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4780                                   const ObjCInterfaceDecl *UnknownObjCClass,
4781                                   bool ObjCPropertyAccess,
4782                                   bool AvoidPartialAvailabilityChecks = false,
4783                                   ObjCInterfaceDecl *ClassReceiver = nullptr);
4784 
4785   bool makeUnavailableInSystemHeader(SourceLocation loc,
4786                                      UnavailableAttr::ImplicitReason reason);
4787 
4788   /// Issue any -Wunguarded-availability warnings in \c FD
4789   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
4790 
4791   void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
4792 
4793   //===--------------------------------------------------------------------===//
4794   // Expression Parsing Callbacks: SemaExpr.cpp.
4795 
4796   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
4797   bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
4798                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
4799                          bool ObjCPropertyAccess = false,
4800                          bool AvoidPartialAvailabilityChecks = false,
4801                          ObjCInterfaceDecl *ClassReciever = nullptr);
4802   void NoteDeletedFunction(FunctionDecl *FD);
4803   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
4804   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
4805                                         ObjCMethodDecl *Getter,
4806                                         SourceLocation Loc);
4807   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
4808                              ArrayRef<Expr *> Args);
4809 
4810   void PushExpressionEvaluationContext(
4811       ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
4812       ExpressionEvaluationContextRecord::ExpressionKind Type =
4813           ExpressionEvaluationContextRecord::EK_Other);
4814   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
4815   void PushExpressionEvaluationContext(
4816       ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
4817       ExpressionEvaluationContextRecord::ExpressionKind Type =
4818           ExpressionEvaluationContextRecord::EK_Other);
4819   void PopExpressionEvaluationContext();
4820 
4821   void DiscardCleanupsInEvaluationContext();
4822 
4823   ExprResult TransformToPotentiallyEvaluated(Expr *E);
4824   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
4825 
4826   ExprResult CheckUnevaluatedOperand(Expr *E);
4827   void CheckUnusedVolatileAssignment(Expr *E);
4828 
4829   ExprResult ActOnConstantExpression(ExprResult Res);
4830 
4831   // Functions for marking a declaration referenced.  These functions also
4832   // contain the relevant logic for marking if a reference to a function or
4833   // variable is an odr-use (in the C++11 sense).  There are separate variants
4834   // for expressions referring to a decl; these exist because odr-use marking
4835   // needs to be delayed for some constant variables when we build one of the
4836   // named expressions.
4837   //
4838   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4839   // should usually be true. This only needs to be set to false if the lack of
4840   // odr-use cannot be determined from the current context (for instance,
4841   // because the name denotes a virtual function and was written without an
4842   // explicit nested-name-specifier).
4843   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4844   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4845                               bool MightBeOdrUse = true);
4846   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4847   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4848   void MarkMemberReferenced(MemberExpr *E);
4849   void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
4850   void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
4851                                          unsigned CapturingScopeIndex);
4852 
4853   ExprResult CheckLValueToRValueConversionOperand(Expr *E);
4854   void CleanupVarDeclMarking();
4855 
4856   enum TryCaptureKind {
4857     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4858   };
4859 
4860   /// Try to capture the given variable.
4861   ///
4862   /// \param Var The variable to capture.
4863   ///
4864   /// \param Loc The location at which the capture occurs.
4865   ///
4866   /// \param Kind The kind of capture, which may be implicit (for either a
4867   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4868   ///
4869   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4870   /// an explicit lambda capture.
4871   ///
4872   /// \param BuildAndDiagnose Whether we are actually supposed to add the
4873   /// captures or diagnose errors. If false, this routine merely check whether
4874   /// the capture can occur without performing the capture itself or complaining
4875   /// if the variable cannot be captured.
4876   ///
4877   /// \param CaptureType Will be set to the type of the field used to capture
4878   /// this variable in the innermost block or lambda. Only valid when the
4879   /// variable can be captured.
4880   ///
4881   /// \param DeclRefType Will be set to the type of a reference to the capture
4882   /// from within the current scope. Only valid when the variable can be
4883   /// captured.
4884   ///
4885   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4886   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4887   /// This is useful when enclosing lambdas must speculatively capture
4888   /// variables that may or may not be used in certain specializations of
4889   /// a nested generic lambda.
4890   ///
4891   /// \returns true if an error occurred (i.e., the variable cannot be
4892   /// captured) and false if the capture succeeded.
4893   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4894                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4895                           QualType &CaptureType,
4896                           QualType &DeclRefType,
4897                           const unsigned *const FunctionScopeIndexToStopAt);
4898 
4899   /// Try to capture the given variable.
4900   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4901                           TryCaptureKind Kind = TryCapture_Implicit,
4902                           SourceLocation EllipsisLoc = SourceLocation());
4903 
4904   /// Checks if the variable must be captured.
4905   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4906 
4907   /// Given a variable, determine the type that a reference to that
4908   /// variable will have in the given scope.
4909   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4910 
4911   /// Mark all of the declarations referenced within a particular AST node as
4912   /// referenced. Used when template instantiation instantiates a non-dependent
4913   /// type -- entities referenced by the type are now referenced.
4914   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4915   void MarkDeclarationsReferencedInExpr(Expr *E,
4916                                         bool SkipLocalVariables = false);
4917 
4918   /// Try to recover by turning the given expression into a
4919   /// call.  Returns true if recovery was attempted or an error was
4920   /// emitted; this may also leave the ExprResult invalid.
4921   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4922                             bool ForceComplain = false,
4923                             bool (*IsPlausibleResult)(QualType) = nullptr);
4924 
4925   /// Figure out if an expression could be turned into a call.
4926   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4927                      UnresolvedSetImpl &NonTemplateOverloads);
4928 
4929   /// Try to convert an expression \p E to type \p Ty. Returns the result of the
4930   /// conversion.
4931   ExprResult tryConvertExprToType(Expr *E, QualType Ty);
4932 
4933   /// Conditionally issue a diagnostic based on the current
4934   /// evaluation context.
4935   ///
4936   /// \param Statement If Statement is non-null, delay reporting the
4937   /// diagnostic until the function body is parsed, and then do a basic
4938   /// reachability analysis to determine if the statement is reachable.
4939   /// If it is unreachable, the diagnostic will not be emitted.
4940   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4941                            const PartialDiagnostic &PD);
4942   /// Similar, but diagnostic is only produced if all the specified statements
4943   /// are reachable.
4944   bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
4945                            const PartialDiagnostic &PD);
4946 
4947   // Primary Expressions.
4948   SourceRange getExprRange(Expr *E) const;
4949 
4950   ExprResult ActOnIdExpression(
4951       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4952       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4953       CorrectionCandidateCallback *CCC = nullptr,
4954       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4955 
4956   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4957                               TemplateArgumentListInfo &Buffer,
4958                               DeclarationNameInfo &NameInfo,
4959                               const TemplateArgumentListInfo *&TemplateArgs);
4960 
4961   bool
4962   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4963                       CorrectionCandidateCallback &CCC,
4964                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4965                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4966 
4967   DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
4968                                     IdentifierInfo *II);
4969   ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
4970 
4971   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4972                                 IdentifierInfo *II,
4973                                 bool AllowBuiltinCreation=false);
4974 
4975   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4976                                         SourceLocation TemplateKWLoc,
4977                                         const DeclarationNameInfo &NameInfo,
4978                                         bool isAddressOfOperand,
4979                                 const TemplateArgumentListInfo *TemplateArgs);
4980 
4981   /// If \p D cannot be odr-used in the current expression evaluation context,
4982   /// return a reason explaining why. Otherwise, return NOUR_None.
4983   NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
4984 
4985   DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4986                                 SourceLocation Loc,
4987                                 const CXXScopeSpec *SS = nullptr);
4988   DeclRefExpr *
4989   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4990                    const DeclarationNameInfo &NameInfo,
4991                    const CXXScopeSpec *SS = nullptr,
4992                    NamedDecl *FoundD = nullptr,
4993                    SourceLocation TemplateKWLoc = SourceLocation(),
4994                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4995   DeclRefExpr *
4996   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4997                    const DeclarationNameInfo &NameInfo,
4998                    NestedNameSpecifierLoc NNS,
4999                    NamedDecl *FoundD = nullptr,
5000                    SourceLocation TemplateKWLoc = SourceLocation(),
5001                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
5002 
5003   ExprResult
5004   BuildAnonymousStructUnionMemberReference(
5005       const CXXScopeSpec &SS,
5006       SourceLocation nameLoc,
5007       IndirectFieldDecl *indirectField,
5008       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5009       Expr *baseObjectExpr = nullptr,
5010       SourceLocation opLoc = SourceLocation());
5011 
5012   ExprResult BuildPossibleImplicitMemberExpr(
5013       const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5014       const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5015       UnresolvedLookupExpr *AsULE = nullptr);
5016   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5017                                      SourceLocation TemplateKWLoc,
5018                                      LookupResult &R,
5019                                 const TemplateArgumentListInfo *TemplateArgs,
5020                                      bool IsDefiniteInstance,
5021                                      const Scope *S);
5022   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5023                                   const LookupResult &R,
5024                                   bool HasTrailingLParen);
5025 
5026   ExprResult
5027   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5028                                     const DeclarationNameInfo &NameInfo,
5029                                     bool IsAddressOfOperand, const Scope *S,
5030                                     TypeSourceInfo **RecoveryTSI = nullptr);
5031 
5032   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5033                                        SourceLocation TemplateKWLoc,
5034                                 const DeclarationNameInfo &NameInfo,
5035                                 const TemplateArgumentListInfo *TemplateArgs);
5036 
5037   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5038                                       LookupResult &R,
5039                                       bool NeedsADL,
5040                                       bool AcceptInvalidDecl = false);
5041   ExprResult BuildDeclarationNameExpr(
5042       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5043       NamedDecl *FoundD = nullptr,
5044       const TemplateArgumentListInfo *TemplateArgs = nullptr,
5045       bool AcceptInvalidDecl = false);
5046 
5047   ExprResult BuildLiteralOperatorCall(LookupResult &R,
5048                       DeclarationNameInfo &SuffixInfo,
5049                       ArrayRef<Expr *> Args,
5050                       SourceLocation LitEndLoc,
5051                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5052 
5053   ExprResult BuildPredefinedExpr(SourceLocation Loc,
5054                                  PredefinedExpr::IdentKind IK);
5055   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5056   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5057 
5058   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5059 
5060   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5061   ExprResult ActOnCharacterConstant(const Token &Tok,
5062                                     Scope *UDLScope = nullptr);
5063   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5064   ExprResult ActOnParenListExpr(SourceLocation L,
5065                                 SourceLocation R,
5066                                 MultiExprArg Val);
5067 
5068   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5069   /// fragments (e.g. "foo" "bar" L"baz").
5070   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5071                                 Scope *UDLScope = nullptr);
5072 
5073   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5074                                        SourceLocation DefaultLoc,
5075                                        SourceLocation RParenLoc,
5076                                        Expr *ControllingExpr,
5077                                        ArrayRef<ParsedType> ArgTypes,
5078                                        ArrayRef<Expr *> ArgExprs);
5079   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5080                                         SourceLocation DefaultLoc,
5081                                         SourceLocation RParenLoc,
5082                                         Expr *ControllingExpr,
5083                                         ArrayRef<TypeSourceInfo *> Types,
5084                                         ArrayRef<Expr *> Exprs);
5085 
5086   // Binary/Unary Operators.  'Tok' is the token for the operator.
5087   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5088                                   Expr *InputExpr);
5089   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5090                           UnaryOperatorKind Opc, Expr *Input);
5091   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5092                           tok::TokenKind Op, Expr *Input);
5093 
5094   bool isQualifiedMemberAccess(Expr *E);
5095   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5096 
5097   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5098                                             SourceLocation OpLoc,
5099                                             UnaryExprOrTypeTrait ExprKind,
5100                                             SourceRange R);
5101   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5102                                             UnaryExprOrTypeTrait ExprKind);
5103   ExprResult
5104     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5105                                   UnaryExprOrTypeTrait ExprKind,
5106                                   bool IsType, void *TyOrEx,
5107                                   SourceRange ArgRange);
5108 
5109   ExprResult CheckPlaceholderExpr(Expr *E);
5110   bool CheckVecStepExpr(Expr *E);
5111 
5112   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5113   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5114                                         SourceRange ExprRange,
5115                                         UnaryExprOrTypeTrait ExprKind);
5116   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5117                                           SourceLocation OpLoc,
5118                                           IdentifierInfo &Name,
5119                                           SourceLocation NameLoc,
5120                                           SourceLocation RParenLoc);
5121   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5122                                  tok::TokenKind Kind, Expr *Input);
5123 
5124   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5125                                      Expr *Idx, SourceLocation RLoc);
5126   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5127                                              Expr *Idx, SourceLocation RLoc);
5128 
5129   ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5130                                               Expr *ColumnIdx,
5131                                               SourceLocation RBLoc);
5132 
5133   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5134                                       Expr *LowerBound,
5135                                       SourceLocation ColonLocFirst,
5136                                       SourceLocation ColonLocSecond,
5137                                       Expr *Length, Expr *Stride,
5138                                       SourceLocation RBLoc);
5139   ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5140                                       SourceLocation RParenLoc,
5141                                       ArrayRef<Expr *> Dims,
5142                                       ArrayRef<SourceRange> Brackets);
5143 
5144   /// Data structure for iterator expression.
5145   struct OMPIteratorData {
5146     IdentifierInfo *DeclIdent = nullptr;
5147     SourceLocation DeclIdentLoc;
5148     ParsedType Type;
5149     OMPIteratorExpr::IteratorRange Range;
5150     SourceLocation AssignLoc;
5151     SourceLocation ColonLoc;
5152     SourceLocation SecColonLoc;
5153   };
5154 
5155   ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5156                                   SourceLocation LLoc, SourceLocation RLoc,
5157                                   ArrayRef<OMPIteratorData> Data);
5158 
5159   // This struct is for use by ActOnMemberAccess to allow
5160   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5161   // changing the access operator from a '.' to a '->' (to see if that is the
5162   // change needed to fix an error about an unknown member, e.g. when the class
5163   // defines a custom operator->).
5164   struct ActOnMemberAccessExtraArgs {
5165     Scope *S;
5166     UnqualifiedId &Id;
5167     Decl *ObjCImpDecl;
5168   };
5169 
5170   ExprResult BuildMemberReferenceExpr(
5171       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5172       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5173       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5174       const TemplateArgumentListInfo *TemplateArgs,
5175       const Scope *S,
5176       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5177 
5178   ExprResult
5179   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5180                            bool IsArrow, const CXXScopeSpec &SS,
5181                            SourceLocation TemplateKWLoc,
5182                            NamedDecl *FirstQualifierInScope, LookupResult &R,
5183                            const TemplateArgumentListInfo *TemplateArgs,
5184                            const Scope *S,
5185                            bool SuppressQualifierCheck = false,
5186                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5187 
5188   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5189                                      SourceLocation OpLoc,
5190                                      const CXXScopeSpec &SS, FieldDecl *Field,
5191                                      DeclAccessPair FoundDecl,
5192                                      const DeclarationNameInfo &MemberNameInfo);
5193 
5194   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5195 
5196   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5197                                      const CXXScopeSpec &SS,
5198                                      const LookupResult &R);
5199 
5200   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5201                                       bool IsArrow, SourceLocation OpLoc,
5202                                       const CXXScopeSpec &SS,
5203                                       SourceLocation TemplateKWLoc,
5204                                       NamedDecl *FirstQualifierInScope,
5205                                const DeclarationNameInfo &NameInfo,
5206                                const TemplateArgumentListInfo *TemplateArgs);
5207 
5208   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5209                                    SourceLocation OpLoc,
5210                                    tok::TokenKind OpKind,
5211                                    CXXScopeSpec &SS,
5212                                    SourceLocation TemplateKWLoc,
5213                                    UnqualifiedId &Member,
5214                                    Decl *ObjCImpDecl);
5215 
5216   MemberExpr *
5217   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5218                   const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5219                   ValueDecl *Member, DeclAccessPair FoundDecl,
5220                   bool HadMultipleCandidates,
5221                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5222                   ExprValueKind VK, ExprObjectKind OK,
5223                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5224   MemberExpr *
5225   BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5226                   NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5227                   ValueDecl *Member, DeclAccessPair FoundDecl,
5228                   bool HadMultipleCandidates,
5229                   const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5230                   ExprValueKind VK, ExprObjectKind OK,
5231                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
5232 
5233   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5234   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5235                                FunctionDecl *FDecl,
5236                                const FunctionProtoType *Proto,
5237                                ArrayRef<Expr *> Args,
5238                                SourceLocation RParenLoc,
5239                                bool ExecConfig = false);
5240   void CheckStaticArrayArgument(SourceLocation CallLoc,
5241                                 ParmVarDecl *Param,
5242                                 const Expr *ArgExpr);
5243 
5244   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5245   /// This provides the location of the left/right parens and a list of comma
5246   /// locations.
5247   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5248                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5249                            Expr *ExecConfig = nullptr);
5250   ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5251                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
5252                            Expr *ExecConfig = nullptr,
5253                            bool IsExecConfig = false);
5254   enum class AtomicArgumentOrder { API, AST };
5255   ExprResult
5256   BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5257                   SourceLocation RParenLoc, MultiExprArg Args,
5258                   AtomicExpr::AtomicOp Op,
5259                   AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5260   ExprResult
5261   BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5262                         ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5263                         Expr *Config = nullptr, bool IsExecConfig = false,
5264                         ADLCallKind UsesADL = ADLCallKind::NotADL);
5265 
5266   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5267                                      MultiExprArg ExecConfig,
5268                                      SourceLocation GGGLoc);
5269 
5270   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5271                            Declarator &D, ParsedType &Ty,
5272                            SourceLocation RParenLoc, Expr *CastExpr);
5273   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5274                                  TypeSourceInfo *Ty,
5275                                  SourceLocation RParenLoc,
5276                                  Expr *Op);
5277   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5278 
5279   /// Build an altivec or OpenCL literal.
5280   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5281                                 SourceLocation RParenLoc, Expr *E,
5282                                 TypeSourceInfo *TInfo);
5283 
5284   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5285 
5286   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5287                                   ParsedType Ty,
5288                                   SourceLocation RParenLoc,
5289                                   Expr *InitExpr);
5290 
5291   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5292                                       TypeSourceInfo *TInfo,
5293                                       SourceLocation RParenLoc,
5294                                       Expr *LiteralExpr);
5295 
5296   ExprResult ActOnInitList(SourceLocation LBraceLoc,
5297                            MultiExprArg InitArgList,
5298                            SourceLocation RBraceLoc);
5299 
5300   ExprResult BuildInitList(SourceLocation LBraceLoc,
5301                            MultiExprArg InitArgList,
5302                            SourceLocation RBraceLoc);
5303 
5304   ExprResult ActOnDesignatedInitializer(Designation &Desig,
5305                                         SourceLocation EqualOrColonLoc,
5306                                         bool GNUSyntax,
5307                                         ExprResult Init);
5308 
5309 private:
5310   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5311 
5312 public:
5313   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5314                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5315   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5316                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5317   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5318                                 Expr *LHSExpr, Expr *RHSExpr);
5319   void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5320                    UnresolvedSetImpl &Functions);
5321 
5322   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5323 
5324   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5325   /// in the case of a the GNU conditional expr extension.
5326   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5327                                 SourceLocation ColonLoc,
5328                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5329 
5330   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5331   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5332                             LabelDecl *TheDecl);
5333 
5334   void ActOnStartStmtExpr();
5335   ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5336                            SourceLocation RPLoc);
5337   ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5338                            SourceLocation RPLoc, unsigned TemplateDepth);
5339   // Handle the final expression in a statement expression.
5340   ExprResult ActOnStmtExprResult(ExprResult E);
5341   void ActOnStmtExprError();
5342 
5343   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5344   struct OffsetOfComponent {
5345     SourceLocation LocStart, LocEnd;
5346     bool isBrackets;  // true if [expr], false if .ident
5347     union {
5348       IdentifierInfo *IdentInfo;
5349       Expr *E;
5350     } U;
5351   };
5352 
5353   /// __builtin_offsetof(type, a.b[123][456].c)
5354   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5355                                   TypeSourceInfo *TInfo,
5356                                   ArrayRef<OffsetOfComponent> Components,
5357                                   SourceLocation RParenLoc);
5358   ExprResult ActOnBuiltinOffsetOf(Scope *S,
5359                                   SourceLocation BuiltinLoc,
5360                                   SourceLocation TypeLoc,
5361                                   ParsedType ParsedArgTy,
5362                                   ArrayRef<OffsetOfComponent> Components,
5363                                   SourceLocation RParenLoc);
5364 
5365   // __builtin_choose_expr(constExpr, expr1, expr2)
5366   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5367                              Expr *CondExpr, Expr *LHSExpr,
5368                              Expr *RHSExpr, SourceLocation RPLoc);
5369 
5370   // __builtin_va_arg(expr, type)
5371   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5372                         SourceLocation RPLoc);
5373   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5374                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
5375 
5376   // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5377   // __builtin_COLUMN()
5378   ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5379                                 SourceLocation BuiltinLoc,
5380                                 SourceLocation RPLoc);
5381 
5382   // Build a potentially resolved SourceLocExpr.
5383   ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5384                                 SourceLocation BuiltinLoc, SourceLocation RPLoc,
5385                                 DeclContext *ParentContext);
5386 
5387   // __null
5388   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5389 
5390   bool CheckCaseExpression(Expr *E);
5391 
5392   /// Describes the result of an "if-exists" condition check.
5393   enum IfExistsResult {
5394     /// The symbol exists.
5395     IER_Exists,
5396 
5397     /// The symbol does not exist.
5398     IER_DoesNotExist,
5399 
5400     /// The name is a dependent name, so the results will differ
5401     /// from one instantiation to the next.
5402     IER_Dependent,
5403 
5404     /// An error occurred.
5405     IER_Error
5406   };
5407 
5408   IfExistsResult
5409   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5410                                const DeclarationNameInfo &TargetNameInfo);
5411 
5412   IfExistsResult
5413   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5414                                bool IsIfExists, CXXScopeSpec &SS,
5415                                UnqualifiedId &Name);
5416 
5417   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5418                                         bool IsIfExists,
5419                                         NestedNameSpecifierLoc QualifierLoc,
5420                                         DeclarationNameInfo NameInfo,
5421                                         Stmt *Nested);
5422   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5423                                         bool IsIfExists,
5424                                         CXXScopeSpec &SS, UnqualifiedId &Name,
5425                                         Stmt *Nested);
5426 
5427   //===------------------------- "Block" Extension ------------------------===//
5428 
5429   /// ActOnBlockStart - This callback is invoked when a block literal is
5430   /// started.
5431   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5432 
5433   /// ActOnBlockArguments - This callback allows processing of block arguments.
5434   /// If there are no arguments, this is still invoked.
5435   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5436                            Scope *CurScope);
5437 
5438   /// ActOnBlockError - If there is an error parsing a block, this callback
5439   /// is invoked to pop the information about the block from the action impl.
5440   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5441 
5442   /// ActOnBlockStmtExpr - This is called when the body of a block statement
5443   /// literal was successfully completed.  ^(int x){...}
5444   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5445                                 Scope *CurScope);
5446 
5447   //===---------------------------- Clang Extensions ----------------------===//
5448 
5449   /// __builtin_convertvector(...)
5450   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5451                                     SourceLocation BuiltinLoc,
5452                                     SourceLocation RParenLoc);
5453 
5454   //===---------------------------- OpenCL Features -----------------------===//
5455 
5456   /// __builtin_astype(...)
5457   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5458                              SourceLocation BuiltinLoc,
5459                              SourceLocation RParenLoc);
5460 
5461   //===---------------------------- C++ Features --------------------------===//
5462 
5463   // Act on C++ namespaces
5464   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5465                                SourceLocation NamespaceLoc,
5466                                SourceLocation IdentLoc, IdentifierInfo *Ident,
5467                                SourceLocation LBrace,
5468                                const ParsedAttributesView &AttrList,
5469                                UsingDirectiveDecl *&UsingDecl);
5470   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5471 
5472   NamespaceDecl *getStdNamespace() const;
5473   NamespaceDecl *getOrCreateStdNamespace();
5474 
5475   NamespaceDecl *lookupStdExperimentalNamespace();
5476 
5477   CXXRecordDecl *getStdBadAlloc() const;
5478   EnumDecl *getStdAlignValT() const;
5479 
5480 private:
5481   // A cache representing if we've fully checked the various comparison category
5482   // types stored in ASTContext. The bit-index corresponds to the integer value
5483   // of a ComparisonCategoryType enumerator.
5484   llvm::SmallBitVector FullyCheckedComparisonCategories;
5485 
5486   ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5487                                          CXXScopeSpec &SS,
5488                                          ParsedType TemplateTypeTy,
5489                                          IdentifierInfo *MemberOrBase);
5490 
5491 public:
5492   enum class ComparisonCategoryUsage {
5493     /// The '<=>' operator was used in an expression and a builtin operator
5494     /// was selected.
5495     OperatorInExpression,
5496     /// A defaulted 'operator<=>' needed the comparison category. This
5497     /// typically only applies to 'std::strong_ordering', due to the implicit
5498     /// fallback return value.
5499     DefaultedOperator,
5500   };
5501 
5502   /// Lookup the specified comparison category types in the standard
5503   ///   library, an check the VarDecls possibly returned by the operator<=>
5504   ///   builtins for that type.
5505   ///
5506   /// \return The type of the comparison category type corresponding to the
5507   ///   specified Kind, or a null type if an error occurs
5508   QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5509                                        SourceLocation Loc,
5510                                        ComparisonCategoryUsage Usage);
5511 
5512   /// Tests whether Ty is an instance of std::initializer_list and, if
5513   /// it is and Element is not NULL, assigns the element type to Element.
5514   bool isStdInitializerList(QualType Ty, QualType *Element);
5515 
5516   /// Looks for the std::initializer_list template and instantiates it
5517   /// with Element, or emits an error if it's not found.
5518   ///
5519   /// \returns The instantiated template, or null on error.
5520   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5521 
5522   /// Determine whether Ctor is an initializer-list constructor, as
5523   /// defined in [dcl.init.list]p2.
5524   bool isInitListConstructor(const FunctionDecl *Ctor);
5525 
5526   Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5527                             SourceLocation NamespcLoc, CXXScopeSpec &SS,
5528                             SourceLocation IdentLoc,
5529                             IdentifierInfo *NamespcName,
5530                             const ParsedAttributesView &AttrList);
5531 
5532   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5533 
5534   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5535                                SourceLocation NamespaceLoc,
5536                                SourceLocation AliasLoc,
5537                                IdentifierInfo *Alias,
5538                                CXXScopeSpec &SS,
5539                                SourceLocation IdentLoc,
5540                                IdentifierInfo *Ident);
5541 
5542   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5543   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
5544                             const LookupResult &PreviousDecls,
5545                             UsingShadowDecl *&PrevShadow);
5546   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
5547                                         NamedDecl *Target,
5548                                         UsingShadowDecl *PrevDecl);
5549 
5550   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5551                                    bool HasTypenameKeyword,
5552                                    const CXXScopeSpec &SS,
5553                                    SourceLocation NameLoc,
5554                                    const LookupResult &Previous);
5555   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
5556                                bool HasTypename,
5557                                const CXXScopeSpec &SS,
5558                                const DeclarationNameInfo &NameInfo,
5559                                SourceLocation NameLoc);
5560 
5561   NamedDecl *BuildUsingDeclaration(
5562       Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5563       bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5564       DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5565       const ParsedAttributesView &AttrList, bool IsInstantiation);
5566   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5567                                 ArrayRef<NamedDecl *> Expansions);
5568 
5569   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5570 
5571   /// Given a derived-class using shadow declaration for a constructor and the
5572   /// correspnding base class constructor, find or create the implicit
5573   /// synthesized derived class constructor to use for this initialization.
5574   CXXConstructorDecl *
5575   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5576                             ConstructorUsingShadowDecl *DerivedShadow);
5577 
5578   Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5579                               SourceLocation UsingLoc,
5580                               SourceLocation TypenameLoc, CXXScopeSpec &SS,
5581                               UnqualifiedId &Name, SourceLocation EllipsisLoc,
5582                               const ParsedAttributesView &AttrList);
5583   Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5584                               MultiTemplateParamsArg TemplateParams,
5585                               SourceLocation UsingLoc, UnqualifiedId &Name,
5586                               const ParsedAttributesView &AttrList,
5587                               TypeResult Type, Decl *DeclFromDeclSpec);
5588 
5589   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5590   /// including handling of its default argument expressions.
5591   ///
5592   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5593   ExprResult
5594   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5595                         NamedDecl *FoundDecl,
5596                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5597                         bool HadMultipleCandidates, bool IsListInitialization,
5598                         bool IsStdInitListInitialization,
5599                         bool RequiresZeroInit, unsigned ConstructKind,
5600                         SourceRange ParenRange);
5601 
5602   /// Build a CXXConstructExpr whose constructor has already been resolved if
5603   /// it denotes an inherited constructor.
5604   ExprResult
5605   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5606                         CXXConstructorDecl *Constructor, bool Elidable,
5607                         MultiExprArg Exprs,
5608                         bool HadMultipleCandidates, bool IsListInitialization,
5609                         bool IsStdInitListInitialization,
5610                         bool RequiresZeroInit, unsigned ConstructKind,
5611                         SourceRange ParenRange);
5612 
5613   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5614   // the constructor can be elidable?
5615   ExprResult
5616   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5617                         NamedDecl *FoundDecl,
5618                         CXXConstructorDecl *Constructor, bool Elidable,
5619                         MultiExprArg Exprs, bool HadMultipleCandidates,
5620                         bool IsListInitialization,
5621                         bool IsStdInitListInitialization, bool RequiresZeroInit,
5622                         unsigned ConstructKind, SourceRange ParenRange);
5623 
5624   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5625 
5626 
5627   /// Instantiate or parse a C++ default argument expression as necessary.
5628   /// Return true on error.
5629   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5630                               ParmVarDecl *Param);
5631 
5632   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
5633   /// the default expr if needed.
5634   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5635                                     FunctionDecl *FD,
5636                                     ParmVarDecl *Param);
5637 
5638   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5639   /// constructed variable.
5640   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
5641 
5642   /// Helper class that collects exception specifications for
5643   /// implicitly-declared special member functions.
5644   class ImplicitExceptionSpecification {
5645     // Pointer to allow copying
5646     Sema *Self;
5647     // We order exception specifications thus:
5648     // noexcept is the most restrictive, but is only used in C++11.
5649     // throw() comes next.
5650     // Then a throw(collected exceptions)
5651     // Finally no specification, which is expressed as noexcept(false).
5652     // throw(...) is used instead if any called function uses it.
5653     ExceptionSpecificationType ComputedEST;
5654     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5655     SmallVector<QualType, 4> Exceptions;
5656 
ClearExceptions()5657     void ClearExceptions() {
5658       ExceptionsSeen.clear();
5659       Exceptions.clear();
5660     }
5661 
5662   public:
ImplicitExceptionSpecification(Sema & Self)5663     explicit ImplicitExceptionSpecification(Sema &Self)
5664       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5665       if (!Self.getLangOpts().CPlusPlus11)
5666         ComputedEST = EST_DynamicNone;
5667     }
5668 
5669     /// Get the computed exception specification type.
getExceptionSpecType()5670     ExceptionSpecificationType getExceptionSpecType() const {
5671       assert(!isComputedNoexcept(ComputedEST) &&
5672              "noexcept(expr) should not be a possible result");
5673       return ComputedEST;
5674     }
5675 
5676     /// The number of exceptions in the exception specification.
size()5677     unsigned size() const { return Exceptions.size(); }
5678 
5679     /// The set of exceptions in the exception specification.
data()5680     const QualType *data() const { return Exceptions.data(); }
5681 
5682     /// Integrate another called method into the collected data.
5683     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5684 
5685     /// Integrate an invoked expression into the collected data.
CalledExpr(Expr * E)5686     void CalledExpr(Expr *E) { CalledStmt(E); }
5687 
5688     /// Integrate an invoked statement into the collected data.
5689     void CalledStmt(Stmt *S);
5690 
5691     /// Overwrite an EPI's exception specification with this
5692     /// computed exception specification.
getExceptionSpec()5693     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5694       FunctionProtoType::ExceptionSpecInfo ESI;
5695       ESI.Type = getExceptionSpecType();
5696       if (ESI.Type == EST_Dynamic) {
5697         ESI.Exceptions = Exceptions;
5698       } else if (ESI.Type == EST_None) {
5699         /// C++11 [except.spec]p14:
5700         ///   The exception-specification is noexcept(false) if the set of
5701         ///   potential exceptions of the special member function contains "any"
5702         ESI.Type = EST_NoexceptFalse;
5703         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
5704                                                      tok::kw_false).get();
5705       }
5706       return ESI;
5707     }
5708   };
5709 
5710   /// Determine what sort of exception specification a defaulted
5711   /// copy constructor of a class will have.
5712   ImplicitExceptionSpecification
5713   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
5714                                            CXXMethodDecl *MD);
5715 
5716   /// Determine what sort of exception specification a defaulted
5717   /// default constructor of a class will have, and whether the parameter
5718   /// will be const.
5719   ImplicitExceptionSpecification
5720   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
5721 
5722   /// Determine what sort of exception specification a defaulted
5723   /// copy assignment operator of a class will have, and whether the
5724   /// parameter will be const.
5725   ImplicitExceptionSpecification
5726   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
5727 
5728   /// Determine what sort of exception specification a defaulted move
5729   /// constructor of a class will have.
5730   ImplicitExceptionSpecification
5731   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
5732 
5733   /// Determine what sort of exception specification a defaulted move
5734   /// assignment operator of a class will have.
5735   ImplicitExceptionSpecification
5736   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
5737 
5738   /// Determine what sort of exception specification a defaulted
5739   /// destructor of a class will have.
5740   ImplicitExceptionSpecification
5741   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
5742 
5743   /// Determine what sort of exception specification an inheriting
5744   /// constructor of a class will have.
5745   ImplicitExceptionSpecification
5746   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
5747                                      CXXConstructorDecl *CD);
5748 
5749   /// Evaluate the implicit exception specification for a defaulted
5750   /// special member function.
5751   void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5752 
5753   /// Check the given noexcept-specifier, convert its expression, and compute
5754   /// the appropriate ExceptionSpecificationType.
5755   ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
5756                                ExceptionSpecificationType &EST);
5757 
5758   /// Check the given exception-specification and update the
5759   /// exception specification information with the results.
5760   void checkExceptionSpecification(bool IsTopLevel,
5761                                    ExceptionSpecificationType EST,
5762                                    ArrayRef<ParsedType> DynamicExceptions,
5763                                    ArrayRef<SourceRange> DynamicExceptionRanges,
5764                                    Expr *NoexceptExpr,
5765                                    SmallVectorImpl<QualType> &Exceptions,
5766                                    FunctionProtoType::ExceptionSpecInfo &ESI);
5767 
5768   /// Determine if we're in a case where we need to (incorrectly) eagerly
5769   /// parse an exception specification to work around a libstdc++ bug.
5770   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
5771 
5772   /// Add an exception-specification to the given member function
5773   /// (or member function template). The exception-specification was parsed
5774   /// after the method itself was declared.
5775   void actOnDelayedExceptionSpecification(Decl *Method,
5776          ExceptionSpecificationType EST,
5777          SourceRange SpecificationRange,
5778          ArrayRef<ParsedType> DynamicExceptions,
5779          ArrayRef<SourceRange> DynamicExceptionRanges,
5780          Expr *NoexceptExpr);
5781 
5782   class InheritedConstructorInfo;
5783 
5784   /// Determine if a special member function should have a deleted
5785   /// definition when it is defaulted.
5786   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5787                                  InheritedConstructorInfo *ICI = nullptr,
5788                                  bool Diagnose = false);
5789 
5790   /// Produce notes explaining why a defaulted function was defined as deleted.
5791   void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5792 
5793   /// Declare the implicit default constructor for the given class.
5794   ///
5795   /// \param ClassDecl The class declaration into which the implicit
5796   /// default constructor will be added.
5797   ///
5798   /// \returns The implicitly-declared default constructor.
5799   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
5800                                                      CXXRecordDecl *ClassDecl);
5801 
5802   /// DefineImplicitDefaultConstructor - Checks for feasibility of
5803   /// defining this constructor as the default constructor.
5804   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5805                                         CXXConstructorDecl *Constructor);
5806 
5807   /// Declare the implicit destructor for the given class.
5808   ///
5809   /// \param ClassDecl The class declaration into which the implicit
5810   /// destructor will be added.
5811   ///
5812   /// \returns The implicitly-declared destructor.
5813   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5814 
5815   /// DefineImplicitDestructor - Checks for feasibility of
5816   /// defining this destructor as the default destructor.
5817   void DefineImplicitDestructor(SourceLocation CurrentLocation,
5818                                 CXXDestructorDecl *Destructor);
5819 
5820   /// Build an exception spec for destructors that don't have one.
5821   ///
5822   /// C++11 says that user-defined destructors with no exception spec get one
5823   /// that looks as if the destructor was implicitly declared.
5824   void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5825 
5826   /// Define the specified inheriting constructor.
5827   void DefineInheritingConstructor(SourceLocation UseLoc,
5828                                    CXXConstructorDecl *Constructor);
5829 
5830   /// Declare the implicit copy constructor for the given class.
5831   ///
5832   /// \param ClassDecl The class declaration into which the implicit
5833   /// copy constructor will be added.
5834   ///
5835   /// \returns The implicitly-declared copy constructor.
5836   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5837 
5838   /// DefineImplicitCopyConstructor - Checks for feasibility of
5839   /// defining this constructor as the copy constructor.
5840   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5841                                      CXXConstructorDecl *Constructor);
5842 
5843   /// Declare the implicit move constructor for the given class.
5844   ///
5845   /// \param ClassDecl The Class declaration into which the implicit
5846   /// move constructor will be added.
5847   ///
5848   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5849   /// declared.
5850   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5851 
5852   /// DefineImplicitMoveConstructor - Checks for feasibility of
5853   /// defining this constructor as the move constructor.
5854   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5855                                      CXXConstructorDecl *Constructor);
5856 
5857   /// Declare the implicit copy assignment operator for the given class.
5858   ///
5859   /// \param ClassDecl The class declaration into which the implicit
5860   /// copy assignment operator will be added.
5861   ///
5862   /// \returns The implicitly-declared copy assignment operator.
5863   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5864 
5865   /// Defines an implicitly-declared copy assignment operator.
5866   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5867                                     CXXMethodDecl *MethodDecl);
5868 
5869   /// Declare the implicit move assignment operator for the given class.
5870   ///
5871   /// \param ClassDecl The Class declaration into which the implicit
5872   /// move assignment operator will be added.
5873   ///
5874   /// \returns The implicitly-declared move assignment operator, or NULL if it
5875   /// wasn't declared.
5876   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5877 
5878   /// Defines an implicitly-declared move assignment operator.
5879   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5880                                     CXXMethodDecl *MethodDecl);
5881 
5882   /// Force the declaration of any implicitly-declared members of this
5883   /// class.
5884   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
5885 
5886   /// Check a completed declaration of an implicit special member.
5887   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5888 
5889   /// Determine whether the given function is an implicitly-deleted
5890   /// special member function.
5891   bool isImplicitlyDeleted(FunctionDecl *FD);
5892 
5893   /// Check whether 'this' shows up in the type of a static member
5894   /// function after the (naturally empty) cv-qualifier-seq would be.
5895   ///
5896   /// \returns true if an error occurred.
5897   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5898 
5899   /// Whether this' shows up in the exception specification of a static
5900   /// member function.
5901   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5902 
5903   /// Check whether 'this' shows up in the attributes of the given
5904   /// static member function.
5905   ///
5906   /// \returns true if an error occurred.
5907   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5908 
5909   /// MaybeBindToTemporary - If the passed in expression has a record type with
5910   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
5911   /// it simply returns the passed in expression.
5912   ExprResult MaybeBindToTemporary(Expr *E);
5913 
5914   /// Wrap the expression in a ConstantExpr if it is a potential immediate
5915   /// invocation.
5916   ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
5917 
5918   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5919                                MultiExprArg ArgsPtr,
5920                                SourceLocation Loc,
5921                                SmallVectorImpl<Expr*> &ConvertedArgs,
5922                                bool AllowExplicit = false,
5923                                bool IsListInitialization = false);
5924 
5925   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
5926                                           SourceLocation NameLoc,
5927                                           IdentifierInfo &Name);
5928 
5929   ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
5930                                 Scope *S, CXXScopeSpec &SS,
5931                                 bool EnteringContext);
5932   ParsedType getDestructorName(SourceLocation TildeLoc,
5933                                IdentifierInfo &II, SourceLocation NameLoc,
5934                                Scope *S, CXXScopeSpec &SS,
5935                                ParsedType ObjectType,
5936                                bool EnteringContext);
5937 
5938   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
5939                                           ParsedType ObjectType);
5940 
5941   // Checks that reinterpret casts don't have undefined behavior.
5942   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
5943                                       bool IsDereference, SourceRange Range);
5944 
5945   /// ActOnCXXNamedCast - Parse
5946   /// {dynamic,static,reinterpret,const,addrspace}_cast's.
5947   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
5948                                tok::TokenKind Kind,
5949                                SourceLocation LAngleBracketLoc,
5950                                Declarator &D,
5951                                SourceLocation RAngleBracketLoc,
5952                                SourceLocation LParenLoc,
5953                                Expr *E,
5954                                SourceLocation RParenLoc);
5955 
5956   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
5957                                tok::TokenKind Kind,
5958                                TypeSourceInfo *Ty,
5959                                Expr *E,
5960                                SourceRange AngleBrackets,
5961                                SourceRange Parens);
5962 
5963   ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
5964                                      ExprResult Operand,
5965                                      SourceLocation RParenLoc);
5966 
5967   ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
5968                                      Expr *Operand, SourceLocation RParenLoc);
5969 
5970   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5971                             SourceLocation TypeidLoc,
5972                             TypeSourceInfo *Operand,
5973                             SourceLocation RParenLoc);
5974   ExprResult BuildCXXTypeId(QualType TypeInfoType,
5975                             SourceLocation TypeidLoc,
5976                             Expr *Operand,
5977                             SourceLocation RParenLoc);
5978 
5979   /// ActOnCXXTypeid - Parse typeid( something ).
5980   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5981                             SourceLocation LParenLoc, bool isType,
5982                             void *TyOrExpr,
5983                             SourceLocation RParenLoc);
5984 
5985   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5986                             SourceLocation TypeidLoc,
5987                             TypeSourceInfo *Operand,
5988                             SourceLocation RParenLoc);
5989   ExprResult BuildCXXUuidof(QualType TypeInfoType,
5990                             SourceLocation TypeidLoc,
5991                             Expr *Operand,
5992                             SourceLocation RParenLoc);
5993 
5994   /// ActOnCXXUuidof - Parse __uuidof( something ).
5995   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5996                             SourceLocation LParenLoc, bool isType,
5997                             void *TyOrExpr,
5998                             SourceLocation RParenLoc);
5999 
6000   /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6001   ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6002                               tok::TokenKind Operator,
6003                               SourceLocation EllipsisLoc, Expr *RHS,
6004                               SourceLocation RParenLoc);
6005   ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6006                               SourceLocation LParenLoc, Expr *LHS,
6007                               BinaryOperatorKind Operator,
6008                               SourceLocation EllipsisLoc, Expr *RHS,
6009                               SourceLocation RParenLoc,
6010                               Optional<unsigned> NumExpansions);
6011   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6012                                    BinaryOperatorKind Operator);
6013 
6014   //// ActOnCXXThis -  Parse 'this' pointer.
6015   ExprResult ActOnCXXThis(SourceLocation loc);
6016 
6017   /// Build a CXXThisExpr and mark it referenced in the current context.
6018   Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6019   void MarkThisReferenced(CXXThisExpr *This);
6020 
6021   /// Try to retrieve the type of the 'this' pointer.
6022   ///
6023   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6024   QualType getCurrentThisType();
6025 
6026   /// When non-NULL, the C++ 'this' expression is allowed despite the
6027   /// current context not being a non-static member function. In such cases,
6028   /// this provides the type used for 'this'.
6029   QualType CXXThisTypeOverride;
6030 
6031   /// RAII object used to temporarily allow the C++ 'this' expression
6032   /// to be used, with the given qualifiers on the current class type.
6033   class CXXThisScopeRAII {
6034     Sema &S;
6035     QualType OldCXXThisTypeOverride;
6036     bool Enabled;
6037 
6038   public:
6039     /// Introduce a new scope where 'this' may be allowed (when enabled),
6040     /// using the given declaration (which is either a class template or a
6041     /// class) along with the given qualifiers.
6042     /// along with the qualifiers placed on '*this'.
6043     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6044                      bool Enabled = true);
6045 
6046     ~CXXThisScopeRAII();
6047   };
6048 
6049   /// Make sure the value of 'this' is actually available in the current
6050   /// context, if it is a potentially evaluated context.
6051   ///
6052   /// \param Loc The location at which the capture of 'this' occurs.
6053   ///
6054   /// \param Explicit Whether 'this' is explicitly captured in a lambda
6055   /// capture list.
6056   ///
6057   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6058   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6059   /// This is useful when enclosing lambdas must speculatively capture
6060   /// 'this' that may or may not be used in certain specializations of
6061   /// a nested generic lambda (depending on whether the name resolves to
6062   /// a non-static member function or a static function).
6063   /// \return returns 'true' if failed, 'false' if success.
6064   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6065       bool BuildAndDiagnose = true,
6066       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6067       bool ByCopy = false);
6068 
6069   /// Determine whether the given type is the type of *this that is used
6070   /// outside of the body of a member function for a type that is currently
6071   /// being defined.
6072   bool isThisOutsideMemberFunctionBody(QualType BaseType);
6073 
6074   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6075   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6076 
6077 
6078   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6079   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6080 
6081   ExprResult
6082   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6083                                  SourceLocation AtLoc, SourceLocation RParen);
6084 
6085   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6086   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6087 
6088   //// ActOnCXXThrow -  Parse throw expressions.
6089   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6090   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6091                            bool IsThrownVarInScope);
6092   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6093 
6094   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6095   /// Can be interpreted either as function-style casting ("int(x)")
6096   /// or class type construction ("ClassType(x,y,z)")
6097   /// or creation of a value-initialized type ("int()").
6098   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6099                                        SourceLocation LParenOrBraceLoc,
6100                                        MultiExprArg Exprs,
6101                                        SourceLocation RParenOrBraceLoc,
6102                                        bool ListInitialization);
6103 
6104   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6105                                        SourceLocation LParenLoc,
6106                                        MultiExprArg Exprs,
6107                                        SourceLocation RParenLoc,
6108                                        bool ListInitialization);
6109 
6110   /// ActOnCXXNew - Parsed a C++ 'new' expression.
6111   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6112                          SourceLocation PlacementLParen,
6113                          MultiExprArg PlacementArgs,
6114                          SourceLocation PlacementRParen,
6115                          SourceRange TypeIdParens, Declarator &D,
6116                          Expr *Initializer);
6117   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6118                          SourceLocation PlacementLParen,
6119                          MultiExprArg PlacementArgs,
6120                          SourceLocation PlacementRParen,
6121                          SourceRange TypeIdParens,
6122                          QualType AllocType,
6123                          TypeSourceInfo *AllocTypeInfo,
6124                          Optional<Expr *> ArraySize,
6125                          SourceRange DirectInitRange,
6126                          Expr *Initializer);
6127 
6128   /// Determine whether \p FD is an aligned allocation or deallocation
6129   /// function that is unavailable.
6130   bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6131 
6132   /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6133   /// function that is unavailable.
6134   void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6135                                             SourceLocation Loc);
6136 
6137   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6138                           SourceRange R);
6139 
6140   /// The scope in which to find allocation functions.
6141   enum AllocationFunctionScope {
6142     /// Only look for allocation functions in the global scope.
6143     AFS_Global,
6144     /// Only look for allocation functions in the scope of the
6145     /// allocated class.
6146     AFS_Class,
6147     /// Look for allocation functions in both the global scope
6148     /// and in the scope of the allocated class.
6149     AFS_Both
6150   };
6151 
6152   /// Finds the overloads of operator new and delete that are appropriate
6153   /// for the allocation.
6154   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6155                                AllocationFunctionScope NewScope,
6156                                AllocationFunctionScope DeleteScope,
6157                                QualType AllocType, bool IsArray,
6158                                bool &PassAlignment, MultiExprArg PlaceArgs,
6159                                FunctionDecl *&OperatorNew,
6160                                FunctionDecl *&OperatorDelete,
6161                                bool Diagnose = true);
6162   void DeclareGlobalNewDelete();
6163   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6164                                        ArrayRef<QualType> Params);
6165 
6166   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6167                                 DeclarationName Name, FunctionDecl* &Operator,
6168                                 bool Diagnose = true);
6169   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6170                                               bool CanProvideSize,
6171                                               bool Overaligned,
6172                                               DeclarationName Name);
6173   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6174                                                       CXXRecordDecl *RD);
6175 
6176   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6177   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6178                             bool UseGlobal, bool ArrayForm,
6179                             Expr *Operand);
6180   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6181                             bool IsDelete, bool CallCanBeVirtual,
6182                             bool WarnOnNonAbstractTypes,
6183                             SourceLocation DtorLoc);
6184 
6185   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6186                                Expr *Operand, SourceLocation RParen);
6187   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6188                                   SourceLocation RParen);
6189 
6190   /// Parsed one of the type trait support pseudo-functions.
6191   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6192                             ArrayRef<ParsedType> Args,
6193                             SourceLocation RParenLoc);
6194   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6195                             ArrayRef<TypeSourceInfo *> Args,
6196                             SourceLocation RParenLoc);
6197 
6198   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6199   /// pseudo-functions.
6200   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6201                                  SourceLocation KWLoc,
6202                                  ParsedType LhsTy,
6203                                  Expr *DimExpr,
6204                                  SourceLocation RParen);
6205 
6206   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6207                                  SourceLocation KWLoc,
6208                                  TypeSourceInfo *TSInfo,
6209                                  Expr *DimExpr,
6210                                  SourceLocation RParen);
6211 
6212   /// ActOnExpressionTrait - Parsed one of the unary type trait support
6213   /// pseudo-functions.
6214   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6215                                   SourceLocation KWLoc,
6216                                   Expr *Queried,
6217                                   SourceLocation RParen);
6218 
6219   ExprResult BuildExpressionTrait(ExpressionTrait OET,
6220                                   SourceLocation KWLoc,
6221                                   Expr *Queried,
6222                                   SourceLocation RParen);
6223 
6224   ExprResult ActOnStartCXXMemberReference(Scope *S,
6225                                           Expr *Base,
6226                                           SourceLocation OpLoc,
6227                                           tok::TokenKind OpKind,
6228                                           ParsedType &ObjectType,
6229                                           bool &MayBePseudoDestructor);
6230 
6231   ExprResult BuildPseudoDestructorExpr(Expr *Base,
6232                                        SourceLocation OpLoc,
6233                                        tok::TokenKind OpKind,
6234                                        const CXXScopeSpec &SS,
6235                                        TypeSourceInfo *ScopeType,
6236                                        SourceLocation CCLoc,
6237                                        SourceLocation TildeLoc,
6238                                      PseudoDestructorTypeStorage DestroyedType);
6239 
6240   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6241                                        SourceLocation OpLoc,
6242                                        tok::TokenKind OpKind,
6243                                        CXXScopeSpec &SS,
6244                                        UnqualifiedId &FirstTypeName,
6245                                        SourceLocation CCLoc,
6246                                        SourceLocation TildeLoc,
6247                                        UnqualifiedId &SecondTypeName);
6248 
6249   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6250                                        SourceLocation OpLoc,
6251                                        tok::TokenKind OpKind,
6252                                        SourceLocation TildeLoc,
6253                                        const DeclSpec& DS);
6254 
6255   /// MaybeCreateExprWithCleanups - If the current full-expression
6256   /// requires any cleanups, surround it with a ExprWithCleanups node.
6257   /// Otherwise, just returns the passed-in expression.
6258   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6259   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6260   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6261 
6262   MaterializeTemporaryExpr *
6263   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6264                                  bool BoundToLvalueReference);
6265 
ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)6266   ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6267     return ActOnFinishFullExpr(
6268         Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6269   }
6270   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6271                                  bool DiscardedValue, bool IsConstexpr = false);
6272   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6273 
6274   // Marks SS invalid if it represents an incomplete type.
6275   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6276 
6277   DeclContext *computeDeclContext(QualType T);
6278   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6279                                   bool EnteringContext = false);
6280   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6281   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6282 
6283   /// The parser has parsed a global nested-name-specifier '::'.
6284   ///
6285   /// \param CCLoc The location of the '::'.
6286   ///
6287   /// \param SS The nested-name-specifier, which will be updated in-place
6288   /// to reflect the parsed nested-name-specifier.
6289   ///
6290   /// \returns true if an error occurred, false otherwise.
6291   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6292 
6293   /// The parser has parsed a '__super' nested-name-specifier.
6294   ///
6295   /// \param SuperLoc The location of the '__super' keyword.
6296   ///
6297   /// \param ColonColonLoc The location of the '::'.
6298   ///
6299   /// \param SS The nested-name-specifier, which will be updated in-place
6300   /// to reflect the parsed nested-name-specifier.
6301   ///
6302   /// \returns true if an error occurred, false otherwise.
6303   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6304                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6305 
6306   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6307                                        bool *CanCorrect = nullptr);
6308   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6309 
6310   /// Keeps information about an identifier in a nested-name-spec.
6311   ///
6312   struct NestedNameSpecInfo {
6313     /// The type of the object, if we're parsing nested-name-specifier in
6314     /// a member access expression.
6315     ParsedType ObjectType;
6316 
6317     /// The identifier preceding the '::'.
6318     IdentifierInfo *Identifier;
6319 
6320     /// The location of the identifier.
6321     SourceLocation IdentifierLoc;
6322 
6323     /// The location of the '::'.
6324     SourceLocation CCLoc;
6325 
6326     /// Creates info object for the most typical case.
6327     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6328              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
ObjectTypeNestedNameSpecInfo6329       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6330         CCLoc(ColonColonLoc) {
6331     }
6332 
NestedNameSpecInfoNestedNameSpecInfo6333     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6334                        SourceLocation ColonColonLoc, QualType ObjectType)
6335       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6336         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6337     }
6338   };
6339 
6340   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6341                                     NestedNameSpecInfo &IdInfo);
6342 
6343   bool BuildCXXNestedNameSpecifier(Scope *S,
6344                                    NestedNameSpecInfo &IdInfo,
6345                                    bool EnteringContext,
6346                                    CXXScopeSpec &SS,
6347                                    NamedDecl *ScopeLookupResult,
6348                                    bool ErrorRecoveryLookup,
6349                                    bool *IsCorrectedToColon = nullptr,
6350                                    bool OnlyNamespace = false);
6351 
6352   /// The parser has parsed a nested-name-specifier 'identifier::'.
6353   ///
6354   /// \param S The scope in which this nested-name-specifier occurs.
6355   ///
6356   /// \param IdInfo Parser information about an identifier in the
6357   /// nested-name-spec.
6358   ///
6359   /// \param EnteringContext Whether we're entering the context nominated by
6360   /// this nested-name-specifier.
6361   ///
6362   /// \param SS The nested-name-specifier, which is both an input
6363   /// parameter (the nested-name-specifier before this type) and an
6364   /// output parameter (containing the full nested-name-specifier,
6365   /// including this new type).
6366   ///
6367   /// \param ErrorRecoveryLookup If true, then this method is called to improve
6368   /// error recovery. In this case do not emit error message.
6369   ///
6370   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6371   /// are allowed.  The bool value pointed by this parameter is set to 'true'
6372   /// if the identifier is treated as if it was followed by ':', not '::'.
6373   ///
6374   /// \param OnlyNamespace If true, only considers namespaces in lookup.
6375   ///
6376   /// \returns true if an error occurred, false otherwise.
6377   bool ActOnCXXNestedNameSpecifier(Scope *S,
6378                                    NestedNameSpecInfo &IdInfo,
6379                                    bool EnteringContext,
6380                                    CXXScopeSpec &SS,
6381                                    bool ErrorRecoveryLookup = false,
6382                                    bool *IsCorrectedToColon = nullptr,
6383                                    bool OnlyNamespace = false);
6384 
6385   ExprResult ActOnDecltypeExpression(Expr *E);
6386 
6387   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6388                                            const DeclSpec &DS,
6389                                            SourceLocation ColonColonLoc);
6390 
6391   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6392                                  NestedNameSpecInfo &IdInfo,
6393                                  bool EnteringContext);
6394 
6395   /// The parser has parsed a nested-name-specifier
6396   /// 'template[opt] template-name < template-args >::'.
6397   ///
6398   /// \param S The scope in which this nested-name-specifier occurs.
6399   ///
6400   /// \param SS The nested-name-specifier, which is both an input
6401   /// parameter (the nested-name-specifier before this type) and an
6402   /// output parameter (containing the full nested-name-specifier,
6403   /// including this new type).
6404   ///
6405   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6406   /// \param TemplateName the template name.
6407   /// \param TemplateNameLoc The location of the template name.
6408   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6409   /// \param TemplateArgs The template arguments.
6410   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6411   /// \param CCLoc The location of the '::'.
6412   ///
6413   /// \param EnteringContext Whether we're entering the context of the
6414   /// nested-name-specifier.
6415   ///
6416   ///
6417   /// \returns true if an error occurred, false otherwise.
6418   bool ActOnCXXNestedNameSpecifier(Scope *S,
6419                                    CXXScopeSpec &SS,
6420                                    SourceLocation TemplateKWLoc,
6421                                    TemplateTy TemplateName,
6422                                    SourceLocation TemplateNameLoc,
6423                                    SourceLocation LAngleLoc,
6424                                    ASTTemplateArgsPtr TemplateArgs,
6425                                    SourceLocation RAngleLoc,
6426                                    SourceLocation CCLoc,
6427                                    bool EnteringContext);
6428 
6429   /// Given a C++ nested-name-specifier, produce an annotation value
6430   /// that the parser can use later to reconstruct the given
6431   /// nested-name-specifier.
6432   ///
6433   /// \param SS A nested-name-specifier.
6434   ///
6435   /// \returns A pointer containing all of the information in the
6436   /// nested-name-specifier \p SS.
6437   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6438 
6439   /// Given an annotation pointer for a nested-name-specifier, restore
6440   /// the nested-name-specifier structure.
6441   ///
6442   /// \param Annotation The annotation pointer, produced by
6443   /// \c SaveNestedNameSpecifierAnnotation().
6444   ///
6445   /// \param AnnotationRange The source range corresponding to the annotation.
6446   ///
6447   /// \param SS The nested-name-specifier that will be updated with the contents
6448   /// of the annotation pointer.
6449   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6450                                             SourceRange AnnotationRange,
6451                                             CXXScopeSpec &SS);
6452 
6453   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6454 
6455   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6456   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6457   /// After this method is called, according to [C++ 3.4.3p3], names should be
6458   /// looked up in the declarator-id's scope, until the declarator is parsed and
6459   /// ActOnCXXExitDeclaratorScope is called.
6460   /// The 'SS' should be a non-empty valid CXXScopeSpec.
6461   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6462 
6463   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6464   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6465   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6466   /// Used to indicate that names should revert to being looked up in the
6467   /// defining scope.
6468   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6469 
6470   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6471   /// initializer for the declaration 'Dcl'.
6472   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6473   /// static data member of class X, names should be looked up in the scope of
6474   /// class X.
6475   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6476 
6477   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6478   /// initializer for the declaration 'Dcl'.
6479   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6480 
6481   /// Create a new lambda closure type.
6482   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6483                                          TypeSourceInfo *Info,
6484                                          bool KnownDependent,
6485                                          LambdaCaptureDefault CaptureDefault);
6486 
6487   /// Start the definition of a lambda expression.
6488   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6489                                        SourceRange IntroducerRange,
6490                                        TypeSourceInfo *MethodType,
6491                                        SourceLocation EndLoc,
6492                                        ArrayRef<ParmVarDecl *> Params,
6493                                        ConstexprSpecKind ConstexprKind,
6494                                        Expr *TrailingRequiresClause);
6495 
6496   /// Number lambda for linkage purposes if necessary.
6497   void handleLambdaNumbering(
6498       CXXRecordDecl *Class, CXXMethodDecl *Method,
6499       Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
6500 
6501   /// Endow the lambda scope info with the relevant properties.
6502   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6503                         CXXMethodDecl *CallOperator,
6504                         SourceRange IntroducerRange,
6505                         LambdaCaptureDefault CaptureDefault,
6506                         SourceLocation CaptureDefaultLoc,
6507                         bool ExplicitParams,
6508                         bool ExplicitResultType,
6509                         bool Mutable);
6510 
6511   /// Perform initialization analysis of the init-capture and perform
6512   /// any implicit conversions such as an lvalue-to-rvalue conversion if
6513   /// not being used to initialize a reference.
actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)6514   ParsedType actOnLambdaInitCaptureInitialization(
6515       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6516       IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6517     return ParsedType::make(buildLambdaInitCaptureInitialization(
6518         Loc, ByRef, EllipsisLoc, None, Id,
6519         InitKind != LambdaCaptureInitKind::CopyInit, Init));
6520   }
6521   QualType buildLambdaInitCaptureInitialization(
6522       SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6523       Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6524       Expr *&Init);
6525 
6526   /// Create a dummy variable within the declcontext of the lambda's
6527   ///  call operator, for name lookup purposes for a lambda init capture.
6528   ///
6529   ///  CodeGen handles emission of lambda captures, ignoring these dummy
6530   ///  variables appropriately.
6531   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
6532                                           QualType InitCaptureType,
6533                                           SourceLocation EllipsisLoc,
6534                                           IdentifierInfo *Id,
6535                                           unsigned InitStyle, Expr *Init);
6536 
6537   /// Add an init-capture to a lambda scope.
6538   void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6539 
6540   /// Note that we have finished the explicit captures for the
6541   /// given lambda.
6542   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6543 
6544   /// \brief This is called after parsing the explicit template parameter list
6545   /// on a lambda (if it exists) in C++2a.
6546   void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
6547                                                 ArrayRef<NamedDecl *> TParams,
6548                                                 SourceLocation RAngleLoc);
6549 
6550   /// Introduce the lambda parameters into scope.
6551   void addLambdaParameters(
6552       ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
6553       CXXMethodDecl *CallOperator, Scope *CurScope);
6554 
6555   /// Deduce a block or lambda's return type based on the return
6556   /// statements present in the body.
6557   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6558 
6559   /// ActOnStartOfLambdaDefinition - This is called just before we start
6560   /// parsing the body of a lambda; it analyzes the explicit captures and
6561   /// arguments, and sets up various data-structures for the body of the
6562   /// lambda.
6563   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6564                                     Declarator &ParamInfo, Scope *CurScope);
6565 
6566   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6567   /// is invoked to pop the information about the lambda.
6568   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6569                         bool IsInstantiation = false);
6570 
6571   /// ActOnLambdaExpr - This is called when the body of a lambda expression
6572   /// was successfully completed.
6573   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6574                              Scope *CurScope);
6575 
6576   /// Does copying/destroying the captured variable have side effects?
6577   bool CaptureHasSideEffects(const sema::Capture &From);
6578 
6579   /// Diagnose if an explicit lambda capture is unused. Returns true if a
6580   /// diagnostic is emitted.
6581   bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6582                                    const sema::Capture &From);
6583 
6584   /// Build a FieldDecl suitable to hold the given capture.
6585   FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6586 
6587   /// Initialize the given capture with a suitable expression.
6588   ExprResult BuildCaptureInit(const sema::Capture &Capture,
6589                               SourceLocation ImplicitCaptureLoc,
6590                               bool IsOpenMPMapping = false);
6591 
6592   /// Complete a lambda-expression having processed and attached the
6593   /// lambda body.
6594   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6595                              sema::LambdaScopeInfo *LSI);
6596 
6597   /// Get the return type to use for a lambda's conversion function(s) to
6598   /// function pointer type, given the type of the call operator.
6599   QualType
6600   getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
6601                                         CallingConv CC);
6602 
6603   /// Define the "body" of the conversion from a lambda object to a
6604   /// function pointer.
6605   ///
6606   /// This routine doesn't actually define a sensible body; rather, it fills
6607   /// in the initialization expression needed to copy the lambda object into
6608   /// the block, and IR generation actually generates the real body of the
6609   /// block pointer conversion.
6610   void DefineImplicitLambdaToFunctionPointerConversion(
6611          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6612 
6613   /// Define the "body" of the conversion from a lambda object to a
6614   /// block pointer.
6615   ///
6616   /// This routine doesn't actually define a sensible body; rather, it fills
6617   /// in the initialization expression needed to copy the lambda object into
6618   /// the block, and IR generation actually generates the real body of the
6619   /// block pointer conversion.
6620   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6621                                                     CXXConversionDecl *Conv);
6622 
6623   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6624                                            SourceLocation ConvLocation,
6625                                            CXXConversionDecl *Conv,
6626                                            Expr *Src);
6627 
6628   /// Check whether the given expression is a valid constraint expression.
6629   /// A diagnostic is emitted if it is not, false is returned, and
6630   /// PossibleNonPrimary will be set to true if the failure might be due to a
6631   /// non-primary expression being used as an atomic constraint.
6632   bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6633                                  bool *PossibleNonPrimary = nullptr,
6634                                  bool IsTrailingRequiresClause = false);
6635 
6636 private:
6637   /// Caches pairs of template-like decls whose associated constraints were
6638   /// checked for subsumption and whether or not the first's constraints did in
6639   /// fact subsume the second's.
6640   llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6641   /// Caches the normalized associated constraints of declarations (concepts or
6642   /// constrained declarations). If an error occurred while normalizing the
6643   /// associated constraints of the template or concept, nullptr will be cached
6644   /// here.
6645   llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6646       NormalizationCache;
6647 
6648   llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
6649       SatisfactionCache;
6650 
6651 public:
6652   const NormalizedConstraint *
6653   getNormalizedAssociatedConstraints(
6654       NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
6655 
6656   /// \brief Check whether the given declaration's associated constraints are
6657   /// at least as constrained than another declaration's according to the
6658   /// partial ordering of constraints.
6659   ///
6660   /// \param Result If no error occurred, receives the result of true if D1 is
6661   /// at least constrained than D2, and false otherwise.
6662   ///
6663   /// \returns true if an error occurred, false otherwise.
6664   bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
6665                               NamedDecl *D2, ArrayRef<const Expr *> AC2,
6666                               bool &Result);
6667 
6668   /// If D1 was not at least as constrained as D2, but would've been if a pair
6669   /// of atomic constraints involved had been declared in a concept and not
6670   /// repeated in two separate places in code.
6671   /// \returns true if such a diagnostic was emitted, false otherwise.
6672   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
6673       ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
6674 
6675   /// \brief Check whether the given list of constraint expressions are
6676   /// satisfied (as if in a 'conjunction') given template arguments.
6677   /// \param Template the template-like entity that triggered the constraints
6678   /// check (either a concept or a constrained entity).
6679   /// \param ConstraintExprs a list of constraint expressions, treated as if
6680   /// they were 'AND'ed together.
6681   /// \param TemplateArgs the list of template arguments to substitute into the
6682   /// constraint expression.
6683   /// \param TemplateIDRange The source range of the template id that
6684   /// caused the constraints check.
6685   /// \param Satisfaction if true is returned, will contain details of the
6686   /// satisfaction, with enough information to diagnose an unsatisfied
6687   /// expression.
6688   /// \returns true if an error occurred and satisfaction could not be checked,
6689   /// false otherwise.
6690   bool CheckConstraintSatisfaction(
6691       const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
6692       ArrayRef<TemplateArgument> TemplateArgs,
6693       SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
6694 
6695   /// \brief Check whether the given non-dependent constraint expression is
6696   /// satisfied. Returns false and updates Satisfaction with the satisfaction
6697   /// verdict if successful, emits a diagnostic and returns true if an error
6698   /// occured and satisfaction could not be determined.
6699   ///
6700   /// \returns true if an error occurred, false otherwise.
6701   bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
6702                                    ConstraintSatisfaction &Satisfaction);
6703 
6704   /// Check whether the given function decl's trailing requires clause is
6705   /// satisfied, if any. Returns false and updates Satisfaction with the
6706   /// satisfaction verdict if successful, emits a diagnostic and returns true if
6707   /// an error occured and satisfaction could not be determined.
6708   ///
6709   /// \returns true if an error occurred, false otherwise.
6710   bool CheckFunctionConstraints(const FunctionDecl *FD,
6711                                 ConstraintSatisfaction &Satisfaction,
6712                                 SourceLocation UsageLoc = SourceLocation());
6713 
6714 
6715   /// \brief Ensure that the given template arguments satisfy the constraints
6716   /// associated with the given template, emitting a diagnostic if they do not.
6717   ///
6718   /// \param Template The template to which the template arguments are being
6719   /// provided.
6720   ///
6721   /// \param TemplateArgs The converted, canonicalized template arguments.
6722   ///
6723   /// \param TemplateIDRange The source range of the template id that
6724   /// caused the constraints check.
6725   ///
6726   /// \returns true if the constrains are not satisfied or could not be checked
6727   /// for satisfaction, false if the constraints are satisfied.
6728   bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
6729                                        ArrayRef<TemplateArgument> TemplateArgs,
6730                                              SourceRange TemplateIDRange);
6731 
6732   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6733   /// unsatisfied.
6734   /// \param First whether this is the first time an unsatisfied constraint is
6735   /// diagnosed for this error.
6736   void
6737   DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
6738                                 bool First = true);
6739 
6740   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6741   /// unsatisfied.
6742   void
6743   DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
6744                                 bool First = true);
6745 
6746   /// \brief Emit diagnostics explaining why a constraint expression was deemed
6747   /// unsatisfied because it was ill-formed.
6748   void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
6749                                               StringRef Diagnostic);
6750 
6751   void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old,
6752                                                SourceLocation New);
6753 
6754   // ParseObjCStringLiteral - Parse Objective-C string literals.
6755   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
6756                                     ArrayRef<Expr *> Strings);
6757 
6758   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
6759 
6760   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
6761   /// numeric literal expression. Type of the expression will be "NSNumber *"
6762   /// or "id" if NSNumber is unavailable.
6763   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
6764   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
6765                                   bool Value);
6766   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
6767 
6768   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
6769   /// '@' prefixed parenthesized expression. The type of the expression will
6770   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
6771   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
6772   /// "const char *" or C structure with attribute 'objc_boxable'.
6773   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
6774 
6775   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
6776                                           Expr *IndexExpr,
6777                                           ObjCMethodDecl *getterMethod,
6778                                           ObjCMethodDecl *setterMethod);
6779 
6780   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
6781                                MutableArrayRef<ObjCDictionaryElement> Elements);
6782 
6783   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
6784                                   TypeSourceInfo *EncodedTypeInfo,
6785                                   SourceLocation RParenLoc);
6786   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
6787                                     CXXConversionDecl *Method,
6788                                     bool HadMultipleCandidates);
6789 
6790   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
6791                                        SourceLocation EncodeLoc,
6792                                        SourceLocation LParenLoc,
6793                                        ParsedType Ty,
6794                                        SourceLocation RParenLoc);
6795 
6796   /// ParseObjCSelectorExpression - Build selector expression for \@selector
6797   ExprResult ParseObjCSelectorExpression(Selector Sel,
6798                                          SourceLocation AtLoc,
6799                                          SourceLocation SelLoc,
6800                                          SourceLocation LParenLoc,
6801                                          SourceLocation RParenLoc,
6802                                          bool WarnMultipleSelectors);
6803 
6804   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
6805   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
6806                                          SourceLocation AtLoc,
6807                                          SourceLocation ProtoLoc,
6808                                          SourceLocation LParenLoc,
6809                                          SourceLocation ProtoIdLoc,
6810                                          SourceLocation RParenLoc);
6811 
6812   //===--------------------------------------------------------------------===//
6813   // C++ Declarations
6814   //
6815   Decl *ActOnStartLinkageSpecification(Scope *S,
6816                                        SourceLocation ExternLoc,
6817                                        Expr *LangStr,
6818                                        SourceLocation LBraceLoc);
6819   Decl *ActOnFinishLinkageSpecification(Scope *S,
6820                                         Decl *LinkageSpec,
6821                                         SourceLocation RBraceLoc);
6822 
6823 
6824   //===--------------------------------------------------------------------===//
6825   // C++ Classes
6826   //
6827   CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
6828   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
6829                           const CXXScopeSpec *SS = nullptr);
6830   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
6831 
6832   bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
6833                             SourceLocation ColonLoc,
6834                             const ParsedAttributesView &Attrs);
6835 
6836   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
6837                                  Declarator &D,
6838                                  MultiTemplateParamsArg TemplateParameterLists,
6839                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
6840                                  InClassInitStyle InitStyle);
6841 
6842   void ActOnStartCXXInClassMemberInitializer();
6843   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6844                                               SourceLocation EqualLoc,
6845                                               Expr *Init);
6846 
6847   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6848                                     Scope *S,
6849                                     CXXScopeSpec &SS,
6850                                     IdentifierInfo *MemberOrBase,
6851                                     ParsedType TemplateTypeTy,
6852                                     const DeclSpec &DS,
6853                                     SourceLocation IdLoc,
6854                                     SourceLocation LParenLoc,
6855                                     ArrayRef<Expr *> Args,
6856                                     SourceLocation RParenLoc,
6857                                     SourceLocation EllipsisLoc);
6858 
6859   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
6860                                     Scope *S,
6861                                     CXXScopeSpec &SS,
6862                                     IdentifierInfo *MemberOrBase,
6863                                     ParsedType TemplateTypeTy,
6864                                     const DeclSpec &DS,
6865                                     SourceLocation IdLoc,
6866                                     Expr *InitList,
6867                                     SourceLocation EllipsisLoc);
6868 
6869   MemInitResult BuildMemInitializer(Decl *ConstructorD,
6870                                     Scope *S,
6871                                     CXXScopeSpec &SS,
6872                                     IdentifierInfo *MemberOrBase,
6873                                     ParsedType TemplateTypeTy,
6874                                     const DeclSpec &DS,
6875                                     SourceLocation IdLoc,
6876                                     Expr *Init,
6877                                     SourceLocation EllipsisLoc);
6878 
6879   MemInitResult BuildMemberInitializer(ValueDecl *Member,
6880                                        Expr *Init,
6881                                        SourceLocation IdLoc);
6882 
6883   MemInitResult BuildBaseInitializer(QualType BaseType,
6884                                      TypeSourceInfo *BaseTInfo,
6885                                      Expr *Init,
6886                                      CXXRecordDecl *ClassDecl,
6887                                      SourceLocation EllipsisLoc);
6888 
6889   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
6890                                            Expr *Init,
6891                                            CXXRecordDecl *ClassDecl);
6892 
6893   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6894                                 CXXCtorInitializer *Initializer);
6895 
6896   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6897                            ArrayRef<CXXCtorInitializer *> Initializers = None);
6898 
6899   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
6900 
6901 
6902   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6903   /// mark all the non-trivial destructors of its members and bases as
6904   /// referenced.
6905   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6906                                               CXXRecordDecl *Record);
6907 
6908   /// Mark destructors of virtual bases of this class referenced. In the Itanium
6909   /// C++ ABI, this is done when emitting a destructor for any non-abstract
6910   /// class. In the Microsoft C++ ABI, this is done any time a class's
6911   /// destructor is referenced.
6912   void MarkVirtualBaseDestructorsReferenced(
6913       SourceLocation Location, CXXRecordDecl *ClassDecl,
6914       llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
6915 
6916   /// Do semantic checks to allow the complete destructor variant to be emitted
6917   /// when the destructor is defined in another translation unit. In the Itanium
6918   /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6919   /// can be emitted in separate TUs. To emit the complete variant, run a subset
6920   /// of the checks performed when emitting a regular destructor.
6921   void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6922                                       CXXDestructorDecl *Dtor);
6923 
6924   /// The list of classes whose vtables have been used within
6925   /// this translation unit, and the source locations at which the
6926   /// first use occurred.
6927   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
6928 
6929   /// The list of vtables that are required but have not yet been
6930   /// materialized.
6931   SmallVector<VTableUse, 16> VTableUses;
6932 
6933   /// The set of classes whose vtables have been used within
6934   /// this translation unit, and a bit that will be true if the vtable is
6935   /// required to be emitted (otherwise, it should be emitted only if needed
6936   /// by code generation).
6937   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6938 
6939   /// Load any externally-stored vtable uses.
6940   void LoadExternalVTableUses();
6941 
6942   /// Note that the vtable for the given class was used at the
6943   /// given location.
6944   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6945                       bool DefinitionRequired = false);
6946 
6947   /// Mark the exception specifications of all virtual member functions
6948   /// in the given class as needed.
6949   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6950                                              const CXXRecordDecl *RD);
6951 
6952   /// MarkVirtualMembersReferenced - Will mark all members of the given
6953   /// CXXRecordDecl referenced.
6954   void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6955                                     bool ConstexprOnly = false);
6956 
6957   /// Define all of the vtables that have been used in this
6958   /// translation unit and reference any virtual members used by those
6959   /// vtables.
6960   ///
6961   /// \returns true if any work was done, false otherwise.
6962   bool DefineUsedVTables();
6963 
6964   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6965 
6966   void ActOnMemInitializers(Decl *ConstructorDecl,
6967                             SourceLocation ColonLoc,
6968                             ArrayRef<CXXCtorInitializer*> MemInits,
6969                             bool AnyErrors);
6970 
6971   /// Check class-level dllimport/dllexport attribute. The caller must
6972   /// ensure that referenceDLLExportedClassMethods is called some point later
6973   /// when all outer classes of Class are complete.
6974   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6975   void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6976 
6977   void referenceDLLExportedClassMethods();
6978 
6979   void propagateDLLAttrToBaseClassTemplate(
6980       CXXRecordDecl *Class, Attr *ClassAttr,
6981       ClassTemplateSpecializationDecl *BaseTemplateSpec,
6982       SourceLocation BaseLoc);
6983 
6984   /// Add gsl::Pointer attribute to std::container::iterator
6985   /// \param ND The declaration that introduces the name
6986   /// std::container::iterator. \param UnderlyingRecord The record named by ND.
6987   void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
6988 
6989   /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
6990   void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
6991 
6992   /// Add [[gsl::Pointer]] attributes for std:: types.
6993   void inferGslPointerAttribute(TypedefNameDecl *TD);
6994 
6995   void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6996 
6997   /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6998   /// conditions that are needed for the attribute to have an effect.
6999   void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7000 
7001   void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7002                                          Decl *TagDecl, SourceLocation LBrac,
7003                                          SourceLocation RBrac,
7004                                          const ParsedAttributesView &AttrList);
7005   void ActOnFinishCXXMemberDecls();
7006   void ActOnFinishCXXNonNestedClass();
7007 
7008   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7009   unsigned ActOnReenterTemplateScope(Decl *Template,
7010                                      llvm::function_ref<Scope *()> EnterScope);
7011   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7012   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7013   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7014   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7015   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7016   void ActOnFinishDelayedMemberInitializers(Decl *Record);
7017   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7018                                 CachedTokens &Toks);
7019   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7020   bool IsInsideALocalClassWithinATemplateFunction();
7021 
7022   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7023                                      Expr *AssertExpr,
7024                                      Expr *AssertMessageExpr,
7025                                      SourceLocation RParenLoc);
7026   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7027                                      Expr *AssertExpr,
7028                                      StringLiteral *AssertMessageExpr,
7029                                      SourceLocation RParenLoc,
7030                                      bool Failed);
7031 
7032   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7033                                   SourceLocation FriendLoc,
7034                                   TypeSourceInfo *TSInfo);
7035   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7036                             MultiTemplateParamsArg TemplateParams);
7037   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7038                                      MultiTemplateParamsArg TemplateParams);
7039 
7040   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7041                                       StorageClass& SC);
7042   void CheckConstructor(CXXConstructorDecl *Constructor);
7043   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7044                                      StorageClass& SC);
7045   bool CheckDestructor(CXXDestructorDecl *Destructor);
7046   void CheckConversionDeclarator(Declarator &D, QualType &R,
7047                                  StorageClass& SC);
7048   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7049   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7050                                      StorageClass &SC);
7051   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7052 
7053   void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7054 
7055   bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7056                                              CXXSpecialMember CSM);
7057   void CheckDelayedMemberExceptionSpecs();
7058 
7059   bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7060                                           DefaultedComparisonKind DCK);
7061   void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7062                                          FunctionDecl *Spaceship);
7063   void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7064                                  DefaultedComparisonKind DCK);
7065 
7066   //===--------------------------------------------------------------------===//
7067   // C++ Derived Classes
7068   //
7069 
7070   /// ActOnBaseSpecifier - Parsed a base specifier
7071   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7072                                        SourceRange SpecifierRange,
7073                                        bool Virtual, AccessSpecifier Access,
7074                                        TypeSourceInfo *TInfo,
7075                                        SourceLocation EllipsisLoc);
7076 
7077   BaseResult ActOnBaseSpecifier(Decl *classdecl,
7078                                 SourceRange SpecifierRange,
7079                                 ParsedAttributes &Attrs,
7080                                 bool Virtual, AccessSpecifier Access,
7081                                 ParsedType basetype,
7082                                 SourceLocation BaseLoc,
7083                                 SourceLocation EllipsisLoc);
7084 
7085   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7086                             MutableArrayRef<CXXBaseSpecifier *> Bases);
7087   void ActOnBaseSpecifiers(Decl *ClassDecl,
7088                            MutableArrayRef<CXXBaseSpecifier *> Bases);
7089 
7090   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7091   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7092                      CXXBasePaths &Paths);
7093 
7094   // FIXME: I don't like this name.
7095   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7096 
7097   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7098                                     SourceLocation Loc, SourceRange Range,
7099                                     CXXCastPath *BasePath = nullptr,
7100                                     bool IgnoreAccess = false);
7101   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7102                                     unsigned InaccessibleBaseID,
7103                                     unsigned AmbiguousBaseConvID,
7104                                     SourceLocation Loc, SourceRange Range,
7105                                     DeclarationName Name,
7106                                     CXXCastPath *BasePath,
7107                                     bool IgnoreAccess = false);
7108 
7109   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7110 
7111   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7112                                          const CXXMethodDecl *Old);
7113 
7114   /// CheckOverridingFunctionReturnType - Checks whether the return types are
7115   /// covariant, according to C++ [class.virtual]p5.
7116   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7117                                          const CXXMethodDecl *Old);
7118 
7119   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7120   /// spec is a subset of base spec.
7121   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7122                                             const CXXMethodDecl *Old);
7123 
7124   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7125 
7126   /// CheckOverrideControl - Check C++11 override control semantics.
7127   void CheckOverrideControl(NamedDecl *D);
7128 
7129   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7130   /// not used in the declaration of an overriding method.
7131   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7132 
7133   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7134   /// overrides a virtual member function marked 'final', according to
7135   /// C++11 [class.virtual]p4.
7136   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7137                                               const CXXMethodDecl *Old);
7138 
7139 
7140   //===--------------------------------------------------------------------===//
7141   // C++ Access Control
7142   //
7143 
7144   enum AccessResult {
7145     AR_accessible,
7146     AR_inaccessible,
7147     AR_dependent,
7148     AR_delayed
7149   };
7150 
7151   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7152                                 NamedDecl *PrevMemberDecl,
7153                                 AccessSpecifier LexicalAS);
7154 
7155   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7156                                            DeclAccessPair FoundDecl);
7157   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7158                                            DeclAccessPair FoundDecl);
7159   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7160                                      SourceRange PlacementRange,
7161                                      CXXRecordDecl *NamingClass,
7162                                      DeclAccessPair FoundDecl,
7163                                      bool Diagnose = true);
7164   AccessResult CheckConstructorAccess(SourceLocation Loc,
7165                                       CXXConstructorDecl *D,
7166                                       DeclAccessPair FoundDecl,
7167                                       const InitializedEntity &Entity,
7168                                       bool IsCopyBindingRefToTemp = false);
7169   AccessResult CheckConstructorAccess(SourceLocation Loc,
7170                                       CXXConstructorDecl *D,
7171                                       DeclAccessPair FoundDecl,
7172                                       const InitializedEntity &Entity,
7173                                       const PartialDiagnostic &PDiag);
7174   AccessResult CheckDestructorAccess(SourceLocation Loc,
7175                                      CXXDestructorDecl *Dtor,
7176                                      const PartialDiagnostic &PDiag,
7177                                      QualType objectType = QualType());
7178   AccessResult CheckFriendAccess(NamedDecl *D);
7179   AccessResult CheckMemberAccess(SourceLocation UseLoc,
7180                                  CXXRecordDecl *NamingClass,
7181                                  DeclAccessPair Found);
7182   AccessResult
7183   CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7184                                      CXXRecordDecl *DecomposedClass,
7185                                      DeclAccessPair Field);
7186   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7187                                          Expr *ObjectExpr,
7188                                          Expr *ArgExpr,
7189                                          DeclAccessPair FoundDecl);
7190   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7191                                           DeclAccessPair FoundDecl);
7192   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7193                                     QualType Base, QualType Derived,
7194                                     const CXXBasePath &Path,
7195                                     unsigned DiagID,
7196                                     bool ForceCheck = false,
7197                                     bool ForceUnprivileged = false);
7198   void CheckLookupAccess(const LookupResult &R);
7199   bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7200                           QualType BaseType);
7201   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7202                                      DeclAccessPair Found, QualType ObjectType,
7203                                      SourceLocation Loc,
7204                                      const PartialDiagnostic &Diag);
isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)7205   bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7206                                      DeclAccessPair Found,
7207                                      QualType ObjectType) {
7208     return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7209                                          SourceLocation(), PDiag());
7210   }
7211 
7212   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7213                          const MultiLevelTemplateArgumentList &TemplateArgs);
7214   void PerformDependentDiagnostics(const DeclContext *Pattern,
7215                         const MultiLevelTemplateArgumentList &TemplateArgs);
7216 
7217   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7218 
7219   /// When true, access checking violations are treated as SFINAE
7220   /// failures rather than hard errors.
7221   bool AccessCheckingSFINAE;
7222 
7223   enum AbstractDiagSelID {
7224     AbstractNone = -1,
7225     AbstractReturnType,
7226     AbstractParamType,
7227     AbstractVariableType,
7228     AbstractFieldType,
7229     AbstractIvarType,
7230     AbstractSynthesizedIvarType,
7231     AbstractArrayType
7232   };
7233 
7234   bool isAbstractType(SourceLocation Loc, QualType T);
7235   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7236                               TypeDiagnoser &Diagnoser);
7237   template <typename... Ts>
RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)7238   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7239                               const Ts &...Args) {
7240     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7241     return RequireNonAbstractType(Loc, T, Diagnoser);
7242   }
7243 
7244   void DiagnoseAbstractType(const CXXRecordDecl *RD);
7245 
7246   //===--------------------------------------------------------------------===//
7247   // C++ Overloaded Operators [C++ 13.5]
7248   //
7249 
7250   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7251 
7252   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7253 
7254   //===--------------------------------------------------------------------===//
7255   // C++ Templates [C++ 14]
7256   //
7257   void FilterAcceptableTemplateNames(LookupResult &R,
7258                                      bool AllowFunctionTemplates = true,
7259                                      bool AllowDependent = true);
7260   bool hasAnyAcceptableTemplateNames(LookupResult &R,
7261                                      bool AllowFunctionTemplates = true,
7262                                      bool AllowDependent = true,
7263                                      bool AllowNonTemplateFunctions = false);
7264   /// Try to interpret the lookup result D as a template-name.
7265   ///
7266   /// \param D A declaration found by name lookup.
7267   /// \param AllowFunctionTemplates Whether function templates should be
7268   ///        considered valid results.
7269   /// \param AllowDependent Whether unresolved using declarations (that might
7270   ///        name templates) should be considered valid results.
7271   NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7272                                    bool AllowFunctionTemplates = true,
7273                                    bool AllowDependent = true);
7274 
7275   enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7276   /// Whether and why a template name is required in this lookup.
7277   class RequiredTemplateKind {
7278   public:
7279     /// Template name is required if TemplateKWLoc is valid.
7280     RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
TemplateKW(TemplateKWLoc)7281         : TemplateKW(TemplateKWLoc) {}
7282     /// Template name is unconditionally required.
RequiredTemplateKind(TemplateNameIsRequiredTag)7283     RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {}
7284 
getTemplateKeywordLoc()7285     SourceLocation getTemplateKeywordLoc() const {
7286       return TemplateKW.getValueOr(SourceLocation());
7287     }
hasTemplateKeyword()7288     bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
isRequired()7289     bool isRequired() const { return TemplateKW != SourceLocation(); }
7290     explicit operator bool() const { return isRequired(); }
7291 
7292   private:
7293     llvm::Optional<SourceLocation> TemplateKW;
7294   };
7295 
7296   enum class AssumedTemplateKind {
7297     /// This is not assumed to be a template name.
7298     None,
7299     /// This is assumed to be a template name because lookup found nothing.
7300     FoundNothing,
7301     /// This is assumed to be a template name because lookup found one or more
7302     /// functions (but no function templates).
7303     FoundFunctions,
7304   };
7305   bool LookupTemplateName(
7306       LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7307       bool EnteringContext, bool &MemberOfUnknownSpecialization,
7308       RequiredTemplateKind RequiredTemplate = SourceLocation(),
7309       AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7310 
7311   TemplateNameKind isTemplateName(Scope *S,
7312                                   CXXScopeSpec &SS,
7313                                   bool hasTemplateKeyword,
7314                                   const UnqualifiedId &Name,
7315                                   ParsedType ObjectType,
7316                                   bool EnteringContext,
7317                                   TemplateTy &Template,
7318                                   bool &MemberOfUnknownSpecialization,
7319                                   bool Disambiguation = false);
7320 
7321   /// Try to resolve an undeclared template name as a type template.
7322   ///
7323   /// Sets II to the identifier corresponding to the template name, and updates
7324   /// Name to a corresponding (typo-corrected) type template name and TNK to
7325   /// the corresponding kind, if possible.
7326   void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7327                                        TemplateNameKind &TNK,
7328                                        SourceLocation NameLoc,
7329                                        IdentifierInfo *&II);
7330 
7331   bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7332                                         SourceLocation NameLoc,
7333                                         bool Diagnose = true);
7334 
7335   /// Determine whether a particular identifier might be the name in a C++1z
7336   /// deduction-guide declaration.
7337   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7338                             SourceLocation NameLoc,
7339                             ParsedTemplateTy *Template = nullptr);
7340 
7341   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7342                                    SourceLocation IILoc,
7343                                    Scope *S,
7344                                    const CXXScopeSpec *SS,
7345                                    TemplateTy &SuggestedTemplate,
7346                                    TemplateNameKind &SuggestedKind);
7347 
7348   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7349                                       NamedDecl *Instantiation,
7350                                       bool InstantiatedFromMember,
7351                                       const NamedDecl *Pattern,
7352                                       const NamedDecl *PatternDef,
7353                                       TemplateSpecializationKind TSK,
7354                                       bool Complain = true);
7355 
7356   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7357   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7358 
7359   NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7360                                 SourceLocation EllipsisLoc,
7361                                 SourceLocation KeyLoc,
7362                                 IdentifierInfo *ParamName,
7363                                 SourceLocation ParamNameLoc,
7364                                 unsigned Depth, unsigned Position,
7365                                 SourceLocation EqualLoc,
7366                                 ParsedType DefaultArg, bool HasTypeConstraint);
7367 
7368   bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7369                            TemplateIdAnnotation *TypeConstraint,
7370                            TemplateTypeParmDecl *ConstrainedParameter,
7371                            SourceLocation EllipsisLoc);
7372 
7373   bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7374                             DeclarationNameInfo NameInfo,
7375                             ConceptDecl *NamedConcept,
7376                             const TemplateArgumentListInfo *TemplateArgs,
7377                             TemplateTypeParmDecl *ConstrainedParameter,
7378                             SourceLocation EllipsisLoc);
7379 
7380   bool AttachTypeConstraint(AutoTypeLoc TL,
7381                             NonTypeTemplateParmDecl *ConstrainedParameter,
7382                             SourceLocation EllipsisLoc);
7383 
7384   bool RequireStructuralType(QualType T, SourceLocation Loc);
7385 
7386   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7387                                              SourceLocation Loc);
7388   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7389 
7390   NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7391                                       unsigned Depth,
7392                                       unsigned Position,
7393                                       SourceLocation EqualLoc,
7394                                       Expr *DefaultArg);
7395   NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7396                                        SourceLocation TmpLoc,
7397                                        TemplateParameterList *Params,
7398                                        SourceLocation EllipsisLoc,
7399                                        IdentifierInfo *ParamName,
7400                                        SourceLocation ParamNameLoc,
7401                                        unsigned Depth,
7402                                        unsigned Position,
7403                                        SourceLocation EqualLoc,
7404                                        ParsedTemplateArgument DefaultArg);
7405 
7406   TemplateParameterList *
7407   ActOnTemplateParameterList(unsigned Depth,
7408                              SourceLocation ExportLoc,
7409                              SourceLocation TemplateLoc,
7410                              SourceLocation LAngleLoc,
7411                              ArrayRef<NamedDecl *> Params,
7412                              SourceLocation RAngleLoc,
7413                              Expr *RequiresClause);
7414 
7415   /// The context in which we are checking a template parameter list.
7416   enum TemplateParamListContext {
7417     TPC_ClassTemplate,
7418     TPC_VarTemplate,
7419     TPC_FunctionTemplate,
7420     TPC_ClassTemplateMember,
7421     TPC_FriendClassTemplate,
7422     TPC_FriendFunctionTemplate,
7423     TPC_FriendFunctionTemplateDefinition,
7424     TPC_TypeAliasTemplate
7425   };
7426 
7427   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7428                                   TemplateParameterList *OldParams,
7429                                   TemplateParamListContext TPC,
7430                                   SkipBodyInfo *SkipBody = nullptr);
7431   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7432       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7433       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7434       ArrayRef<TemplateParameterList *> ParamLists,
7435       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7436       bool SuppressDiagnostic = false);
7437 
7438   DeclResult CheckClassTemplate(
7439       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7440       CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7441       const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7442       AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7443       SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7444       TemplateParameterList **OuterTemplateParamLists,
7445       SkipBodyInfo *SkipBody = nullptr);
7446 
7447   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7448                                                     QualType NTTPType,
7449                                                     SourceLocation Loc);
7450 
7451   /// Get a template argument mapping the given template parameter to itself,
7452   /// e.g. for X in \c template<int X>, this would return an expression template
7453   /// argument referencing X.
7454   TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7455                                                      SourceLocation Location);
7456 
7457   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7458                                   TemplateArgumentListInfo &Out);
7459 
7460   ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7461 
7462   void NoteAllFoundTemplates(TemplateName Name);
7463 
7464   QualType CheckTemplateIdType(TemplateName Template,
7465                                SourceLocation TemplateLoc,
7466                               TemplateArgumentListInfo &TemplateArgs);
7467 
7468   TypeResult
7469   ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7470                       TemplateTy Template, IdentifierInfo *TemplateII,
7471                       SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7472                       ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7473                       bool IsCtorOrDtorName = false, bool IsClassName = false);
7474 
7475   /// Parsed an elaborated-type-specifier that refers to a template-id,
7476   /// such as \c class T::template apply<U>.
7477   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7478                                     TypeSpecifierType TagSpec,
7479                                     SourceLocation TagLoc,
7480                                     CXXScopeSpec &SS,
7481                                     SourceLocation TemplateKWLoc,
7482                                     TemplateTy TemplateD,
7483                                     SourceLocation TemplateLoc,
7484                                     SourceLocation LAngleLoc,
7485                                     ASTTemplateArgsPtr TemplateArgsIn,
7486                                     SourceLocation RAngleLoc);
7487 
7488   DeclResult ActOnVarTemplateSpecialization(
7489       Scope *S, Declarator &D, TypeSourceInfo *DI,
7490       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7491       StorageClass SC, bool IsPartialSpecialization);
7492 
7493   /// Get the specialization of the given variable template corresponding to
7494   /// the specified argument list, or a null-but-valid result if the arguments
7495   /// are dependent.
7496   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7497                                 SourceLocation TemplateLoc,
7498                                 SourceLocation TemplateNameLoc,
7499                                 const TemplateArgumentListInfo &TemplateArgs);
7500 
7501   /// Form a reference to the specialization of the given variable template
7502   /// corresponding to the specified argument list, or a null-but-valid result
7503   /// if the arguments are dependent.
7504   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7505                                 const DeclarationNameInfo &NameInfo,
7506                                 VarTemplateDecl *Template,
7507                                 SourceLocation TemplateLoc,
7508                                 const TemplateArgumentListInfo *TemplateArgs);
7509 
7510   ExprResult
7511   CheckConceptTemplateId(const CXXScopeSpec &SS,
7512                          SourceLocation TemplateKWLoc,
7513                          const DeclarationNameInfo &ConceptNameInfo,
7514                          NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7515                          const TemplateArgumentListInfo *TemplateArgs);
7516 
7517   void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7518 
7519   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7520                                  SourceLocation TemplateKWLoc,
7521                                  LookupResult &R,
7522                                  bool RequiresADL,
7523                                const TemplateArgumentListInfo *TemplateArgs);
7524 
7525   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7526                                           SourceLocation TemplateKWLoc,
7527                                const DeclarationNameInfo &NameInfo,
7528                                const TemplateArgumentListInfo *TemplateArgs);
7529 
7530   TemplateNameKind ActOnTemplateName(
7531       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7532       const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7533       TemplateTy &Template, bool AllowInjectedClassName = false);
7534 
7535   DeclResult ActOnClassTemplateSpecialization(
7536       Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7537       SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7538       TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7539       MultiTemplateParamsArg TemplateParameterLists,
7540       SkipBodyInfo *SkipBody = nullptr);
7541 
7542   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7543                                               TemplateDecl *PrimaryTemplate,
7544                                               unsigned NumExplicitArgs,
7545                                               ArrayRef<TemplateArgument> Args);
7546   void CheckTemplatePartialSpecialization(
7547       ClassTemplatePartialSpecializationDecl *Partial);
7548   void CheckTemplatePartialSpecialization(
7549       VarTemplatePartialSpecializationDecl *Partial);
7550 
7551   Decl *ActOnTemplateDeclarator(Scope *S,
7552                                 MultiTemplateParamsArg TemplateParameterLists,
7553                                 Declarator &D);
7554 
7555   bool
7556   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7557                                          TemplateSpecializationKind NewTSK,
7558                                          NamedDecl *PrevDecl,
7559                                          TemplateSpecializationKind PrevTSK,
7560                                          SourceLocation PrevPtOfInstantiation,
7561                                          bool &SuppressNew);
7562 
7563   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7564                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
7565                                                     LookupResult &Previous);
7566 
7567   bool CheckFunctionTemplateSpecialization(
7568       FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7569       LookupResult &Previous, bool QualifiedFriend = false);
7570   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7571   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7572 
7573   DeclResult ActOnExplicitInstantiation(
7574       Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7575       unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7576       TemplateTy Template, SourceLocation TemplateNameLoc,
7577       SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7578       SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7579 
7580   DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7581                                         SourceLocation TemplateLoc,
7582                                         unsigned TagSpec, SourceLocation KWLoc,
7583                                         CXXScopeSpec &SS, IdentifierInfo *Name,
7584                                         SourceLocation NameLoc,
7585                                         const ParsedAttributesView &Attr);
7586 
7587   DeclResult ActOnExplicitInstantiation(Scope *S,
7588                                         SourceLocation ExternLoc,
7589                                         SourceLocation TemplateLoc,
7590                                         Declarator &D);
7591 
7592   TemplateArgumentLoc
7593   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7594                                           SourceLocation TemplateLoc,
7595                                           SourceLocation RAngleLoc,
7596                                           Decl *Param,
7597                                           SmallVectorImpl<TemplateArgument>
7598                                             &Converted,
7599                                           bool &HasDefaultArg);
7600 
7601   /// Specifies the context in which a particular template
7602   /// argument is being checked.
7603   enum CheckTemplateArgumentKind {
7604     /// The template argument was specified in the code or was
7605     /// instantiated with some deduced template arguments.
7606     CTAK_Specified,
7607 
7608     /// The template argument was deduced via template argument
7609     /// deduction.
7610     CTAK_Deduced,
7611 
7612     /// The template argument was deduced from an array bound
7613     /// via template argument deduction.
7614     CTAK_DeducedFromArrayBound
7615   };
7616 
7617   bool CheckTemplateArgument(NamedDecl *Param,
7618                              TemplateArgumentLoc &Arg,
7619                              NamedDecl *Template,
7620                              SourceLocation TemplateLoc,
7621                              SourceLocation RAngleLoc,
7622                              unsigned ArgumentPackIndex,
7623                            SmallVectorImpl<TemplateArgument> &Converted,
7624                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
7625 
7626   /// Check that the given template arguments can be be provided to
7627   /// the given template, converting the arguments along the way.
7628   ///
7629   /// \param Template The template to which the template arguments are being
7630   /// provided.
7631   ///
7632   /// \param TemplateLoc The location of the template name in the source.
7633   ///
7634   /// \param TemplateArgs The list of template arguments. If the template is
7635   /// a template template parameter, this function may extend the set of
7636   /// template arguments to also include substituted, defaulted template
7637   /// arguments.
7638   ///
7639   /// \param PartialTemplateArgs True if the list of template arguments is
7640   /// intentionally partial, e.g., because we're checking just the initial
7641   /// set of template arguments.
7642   ///
7643   /// \param Converted Will receive the converted, canonicalized template
7644   /// arguments.
7645   ///
7646   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
7647   /// contain the converted forms of the template arguments as written.
7648   /// Otherwise, \p TemplateArgs will not be modified.
7649   ///
7650   /// \param ConstraintsNotSatisfied If provided, and an error occured, will
7651   /// receive true if the cause for the error is the associated constraints of
7652   /// the template not being satisfied by the template arguments.
7653   ///
7654   /// \returns true if an error occurred, false otherwise.
7655   bool CheckTemplateArgumentList(TemplateDecl *Template,
7656                                  SourceLocation TemplateLoc,
7657                                  TemplateArgumentListInfo &TemplateArgs,
7658                                  bool PartialTemplateArgs,
7659                                  SmallVectorImpl<TemplateArgument> &Converted,
7660                                  bool UpdateArgsWithConversions = true,
7661                                  bool *ConstraintsNotSatisfied = nullptr);
7662 
7663   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
7664                                  TemplateArgumentLoc &Arg,
7665                            SmallVectorImpl<TemplateArgument> &Converted);
7666 
7667   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
7668                              TypeSourceInfo *Arg);
7669   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7670                                    QualType InstantiatedParamType, Expr *Arg,
7671                                    TemplateArgument &Converted,
7672                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
7673   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7674                                      TemplateParameterList *Params,
7675                                      TemplateArgumentLoc &Arg);
7676 
7677   ExprResult
7678   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7679                                           QualType ParamType,
7680                                           SourceLocation Loc);
7681   ExprResult
7682   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7683                                               SourceLocation Loc);
7684 
7685   /// Enumeration describing how template parameter lists are compared
7686   /// for equality.
7687   enum TemplateParameterListEqualKind {
7688     /// We are matching the template parameter lists of two templates
7689     /// that might be redeclarations.
7690     ///
7691     /// \code
7692     /// template<typename T> struct X;
7693     /// template<typename T> struct X;
7694     /// \endcode
7695     TPL_TemplateMatch,
7696 
7697     /// We are matching the template parameter lists of two template
7698     /// template parameters as part of matching the template parameter lists
7699     /// of two templates that might be redeclarations.
7700     ///
7701     /// \code
7702     /// template<template<int I> class TT> struct X;
7703     /// template<template<int Value> class Other> struct X;
7704     /// \endcode
7705     TPL_TemplateTemplateParmMatch,
7706 
7707     /// We are matching the template parameter lists of a template
7708     /// template argument against the template parameter lists of a template
7709     /// template parameter.
7710     ///
7711     /// \code
7712     /// template<template<int Value> class Metafun> struct X;
7713     /// template<int Value> struct integer_c;
7714     /// X<integer_c> xic;
7715     /// \endcode
7716     TPL_TemplateTemplateArgumentMatch
7717   };
7718 
7719   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
7720                                       TemplateParameterList *Old,
7721                                       bool Complain,
7722                                       TemplateParameterListEqualKind Kind,
7723                                       SourceLocation TemplateArgLoc
7724                                         = SourceLocation());
7725 
7726   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
7727 
7728   /// Called when the parser has parsed a C++ typename
7729   /// specifier, e.g., "typename T::type".
7730   ///
7731   /// \param S The scope in which this typename type occurs.
7732   /// \param TypenameLoc the location of the 'typename' keyword
7733   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7734   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
7735   /// \param IdLoc the location of the identifier.
7736   TypeResult
7737   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7738                     const CXXScopeSpec &SS, const IdentifierInfo &II,
7739                     SourceLocation IdLoc);
7740 
7741   /// Called when the parser has parsed a C++ typename
7742   /// specifier that ends in a template-id, e.g.,
7743   /// "typename MetaFun::template apply<T1, T2>".
7744   ///
7745   /// \param S The scope in which this typename type occurs.
7746   /// \param TypenameLoc the location of the 'typename' keyword
7747   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
7748   /// \param TemplateLoc the location of the 'template' keyword, if any.
7749   /// \param TemplateName The template name.
7750   /// \param TemplateII The identifier used to name the template.
7751   /// \param TemplateIILoc The location of the template name.
7752   /// \param LAngleLoc The location of the opening angle bracket  ('<').
7753   /// \param TemplateArgs The template arguments.
7754   /// \param RAngleLoc The location of the closing angle bracket  ('>').
7755   TypeResult
7756   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7757                     const CXXScopeSpec &SS,
7758                     SourceLocation TemplateLoc,
7759                     TemplateTy TemplateName,
7760                     IdentifierInfo *TemplateII,
7761                     SourceLocation TemplateIILoc,
7762                     SourceLocation LAngleLoc,
7763                     ASTTemplateArgsPtr TemplateArgs,
7764                     SourceLocation RAngleLoc);
7765 
7766   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7767                              SourceLocation KeywordLoc,
7768                              NestedNameSpecifierLoc QualifierLoc,
7769                              const IdentifierInfo &II,
7770                              SourceLocation IILoc,
7771                              TypeSourceInfo **TSI,
7772                              bool DeducedTSTContext);
7773 
7774   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
7775                              SourceLocation KeywordLoc,
7776                              NestedNameSpecifierLoc QualifierLoc,
7777                              const IdentifierInfo &II,
7778                              SourceLocation IILoc,
7779                              bool DeducedTSTContext = true);
7780 
7781 
7782   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7783                                                     SourceLocation Loc,
7784                                                     DeclarationName Name);
7785   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
7786 
7787   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
7788   bool RebuildTemplateParamsInCurrentInstantiation(
7789                                                 TemplateParameterList *Params);
7790 
7791   std::string
7792   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7793                                   const TemplateArgumentList &Args);
7794 
7795   std::string
7796   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7797                                   const TemplateArgument *Args,
7798                                   unsigned NumArgs);
7799 
7800   //===--------------------------------------------------------------------===//
7801   // C++ Concepts
7802   //===--------------------------------------------------------------------===//
7803   Decl *ActOnConceptDefinition(
7804       Scope *S, MultiTemplateParamsArg TemplateParameterLists,
7805       IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
7806 
7807   RequiresExprBodyDecl *
7808   ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
7809                          ArrayRef<ParmVarDecl *> LocalParameters,
7810                          Scope *BodyScope);
7811   void ActOnFinishRequiresExpr();
7812   concepts::Requirement *ActOnSimpleRequirement(Expr *E);
7813   concepts::Requirement *ActOnTypeRequirement(
7814       SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7815       IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
7816   concepts::Requirement *ActOnCompoundRequirement(Expr *E,
7817                                                   SourceLocation NoexceptLoc);
7818   concepts::Requirement *
7819   ActOnCompoundRequirement(
7820       Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7821       TemplateIdAnnotation *TypeConstraint, unsigned Depth);
7822   concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
7823   concepts::ExprRequirement *
7824   BuildExprRequirement(
7825       Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
7826       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7827   concepts::ExprRequirement *
7828   BuildExprRequirement(
7829       concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
7830       bool IsSatisfied, SourceLocation NoexceptLoc,
7831       concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
7832   concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
7833   concepts::TypeRequirement *
7834   BuildTypeRequirement(
7835       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7836   concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
7837   concepts::NestedRequirement *
7838   BuildNestedRequirement(
7839       concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
7840   ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
7841                                RequiresExprBodyDecl *Body,
7842                                ArrayRef<ParmVarDecl *> LocalParameters,
7843                                ArrayRef<concepts::Requirement *> Requirements,
7844                                SourceLocation ClosingBraceLoc);
7845 
7846   //===--------------------------------------------------------------------===//
7847   // C++ Variadic Templates (C++0x [temp.variadic])
7848   //===--------------------------------------------------------------------===//
7849 
7850   /// Determine whether an unexpanded parameter pack might be permitted in this
7851   /// location. Useful for error recovery.
7852   bool isUnexpandedParameterPackPermitted();
7853 
7854   /// The context in which an unexpanded parameter pack is
7855   /// being diagnosed.
7856   ///
7857   /// Note that the values of this enumeration line up with the first
7858   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
7859   enum UnexpandedParameterPackContext {
7860     /// An arbitrary expression.
7861     UPPC_Expression = 0,
7862 
7863     /// The base type of a class type.
7864     UPPC_BaseType,
7865 
7866     /// The type of an arbitrary declaration.
7867     UPPC_DeclarationType,
7868 
7869     /// The type of a data member.
7870     UPPC_DataMemberType,
7871 
7872     /// The size of a bit-field.
7873     UPPC_BitFieldWidth,
7874 
7875     /// The expression in a static assertion.
7876     UPPC_StaticAssertExpression,
7877 
7878     /// The fixed underlying type of an enumeration.
7879     UPPC_FixedUnderlyingType,
7880 
7881     /// The enumerator value.
7882     UPPC_EnumeratorValue,
7883 
7884     /// A using declaration.
7885     UPPC_UsingDeclaration,
7886 
7887     /// A friend declaration.
7888     UPPC_FriendDeclaration,
7889 
7890     /// A declaration qualifier.
7891     UPPC_DeclarationQualifier,
7892 
7893     /// An initializer.
7894     UPPC_Initializer,
7895 
7896     /// A default argument.
7897     UPPC_DefaultArgument,
7898 
7899     /// The type of a non-type template parameter.
7900     UPPC_NonTypeTemplateParameterType,
7901 
7902     /// The type of an exception.
7903     UPPC_ExceptionType,
7904 
7905     /// Partial specialization.
7906     UPPC_PartialSpecialization,
7907 
7908     /// Microsoft __if_exists.
7909     UPPC_IfExists,
7910 
7911     /// Microsoft __if_not_exists.
7912     UPPC_IfNotExists,
7913 
7914     /// Lambda expression.
7915     UPPC_Lambda,
7916 
7917     /// Block expression.
7918     UPPC_Block,
7919 
7920     /// A type constraint.
7921     UPPC_TypeConstraint,
7922 
7923     // A requirement in a requires-expression.
7924     UPPC_Requirement,
7925   };
7926 
7927   /// Diagnose unexpanded parameter packs.
7928   ///
7929   /// \param Loc The location at which we should emit the diagnostic.
7930   ///
7931   /// \param UPPC The context in which we are diagnosing unexpanded
7932   /// parameter packs.
7933   ///
7934   /// \param Unexpanded the set of unexpanded parameter packs.
7935   ///
7936   /// \returns true if an error occurred, false otherwise.
7937   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
7938                                         UnexpandedParameterPackContext UPPC,
7939                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
7940 
7941   /// If the given type contains an unexpanded parameter pack,
7942   /// diagnose the error.
7943   ///
7944   /// \param Loc The source location where a diagnostc should be emitted.
7945   ///
7946   /// \param T The type that is being checked for unexpanded parameter
7947   /// packs.
7948   ///
7949   /// \returns true if an error occurred, false otherwise.
7950   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
7951                                        UnexpandedParameterPackContext UPPC);
7952 
7953   /// If the given expression contains an unexpanded parameter
7954   /// pack, diagnose the error.
7955   ///
7956   /// \param E The expression that is being checked for unexpanded
7957   /// parameter packs.
7958   ///
7959   /// \returns true if an error occurred, false otherwise.
7960   bool DiagnoseUnexpandedParameterPack(Expr *E,
7961                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
7962 
7963   /// If the given requirees-expression contains an unexpanded reference to one
7964   /// of its own parameter packs, diagnose the error.
7965   ///
7966   /// \param RE The requiress-expression that is being checked for unexpanded
7967   /// parameter packs.
7968   ///
7969   /// \returns true if an error occurred, false otherwise.
7970   bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
7971 
7972   /// If the given nested-name-specifier contains an unexpanded
7973   /// parameter pack, diagnose the error.
7974   ///
7975   /// \param SS The nested-name-specifier that is being checked for
7976   /// unexpanded parameter packs.
7977   ///
7978   /// \returns true if an error occurred, false otherwise.
7979   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
7980                                        UnexpandedParameterPackContext UPPC);
7981 
7982   /// If the given name contains an unexpanded parameter pack,
7983   /// diagnose the error.
7984   ///
7985   /// \param NameInfo The name (with source location information) that
7986   /// is being checked for unexpanded parameter packs.
7987   ///
7988   /// \returns true if an error occurred, false otherwise.
7989   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
7990                                        UnexpandedParameterPackContext UPPC);
7991 
7992   /// If the given template name contains an unexpanded parameter pack,
7993   /// diagnose the error.
7994   ///
7995   /// \param Loc The location of the template name.
7996   ///
7997   /// \param Template The template name that is being checked for unexpanded
7998   /// parameter packs.
7999   ///
8000   /// \returns true if an error occurred, false otherwise.
8001   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8002                                        TemplateName Template,
8003                                        UnexpandedParameterPackContext UPPC);
8004 
8005   /// If the given template argument contains an unexpanded parameter
8006   /// pack, diagnose the error.
8007   ///
8008   /// \param Arg The template argument that is being checked for unexpanded
8009   /// parameter packs.
8010   ///
8011   /// \returns true if an error occurred, false otherwise.
8012   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8013                                        UnexpandedParameterPackContext UPPC);
8014 
8015   /// Collect the set of unexpanded parameter packs within the given
8016   /// template argument.
8017   ///
8018   /// \param Arg The template argument that will be traversed to find
8019   /// unexpanded parameter packs.
8020   void collectUnexpandedParameterPacks(TemplateArgument Arg,
8021                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8022 
8023   /// Collect the set of unexpanded parameter packs within the given
8024   /// template argument.
8025   ///
8026   /// \param Arg The template argument that will be traversed to find
8027   /// unexpanded parameter packs.
8028   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8029                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8030 
8031   /// Collect the set of unexpanded parameter packs within the given
8032   /// type.
8033   ///
8034   /// \param T The type that will be traversed to find
8035   /// unexpanded parameter packs.
8036   void collectUnexpandedParameterPacks(QualType T,
8037                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8038 
8039   /// Collect the set of unexpanded parameter packs within the given
8040   /// type.
8041   ///
8042   /// \param TL The type that will be traversed to find
8043   /// unexpanded parameter packs.
8044   void collectUnexpandedParameterPacks(TypeLoc TL,
8045                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8046 
8047   /// Collect the set of unexpanded parameter packs within the given
8048   /// nested-name-specifier.
8049   ///
8050   /// \param NNS The nested-name-specifier that will be traversed to find
8051   /// unexpanded parameter packs.
8052   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8053                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8054 
8055   /// Collect the set of unexpanded parameter packs within the given
8056   /// name.
8057   ///
8058   /// \param NameInfo The name that will be traversed to find
8059   /// unexpanded parameter packs.
8060   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8061                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8062 
8063   /// Invoked when parsing a template argument followed by an
8064   /// ellipsis, which creates a pack expansion.
8065   ///
8066   /// \param Arg The template argument preceding the ellipsis, which
8067   /// may already be invalid.
8068   ///
8069   /// \param EllipsisLoc The location of the ellipsis.
8070   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8071                                             SourceLocation EllipsisLoc);
8072 
8073   /// Invoked when parsing a type followed by an ellipsis, which
8074   /// creates a pack expansion.
8075   ///
8076   /// \param Type The type preceding the ellipsis, which will become
8077   /// the pattern of the pack expansion.
8078   ///
8079   /// \param EllipsisLoc The location of the ellipsis.
8080   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8081 
8082   /// Construct a pack expansion type from the pattern of the pack
8083   /// expansion.
8084   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8085                                      SourceLocation EllipsisLoc,
8086                                      Optional<unsigned> NumExpansions);
8087 
8088   /// Construct a pack expansion type from the pattern of the pack
8089   /// expansion.
8090   QualType CheckPackExpansion(QualType Pattern,
8091                               SourceRange PatternRange,
8092                               SourceLocation EllipsisLoc,
8093                               Optional<unsigned> NumExpansions);
8094 
8095   /// Invoked when parsing an expression followed by an ellipsis, which
8096   /// creates a pack expansion.
8097   ///
8098   /// \param Pattern The expression preceding the ellipsis, which will become
8099   /// the pattern of the pack expansion.
8100   ///
8101   /// \param EllipsisLoc The location of the ellipsis.
8102   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8103 
8104   /// Invoked when parsing an expression followed by an ellipsis, which
8105   /// creates a pack expansion.
8106   ///
8107   /// \param Pattern The expression preceding the ellipsis, which will become
8108   /// the pattern of the pack expansion.
8109   ///
8110   /// \param EllipsisLoc The location of the ellipsis.
8111   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8112                                 Optional<unsigned> NumExpansions);
8113 
8114   /// Determine whether we could expand a pack expansion with the
8115   /// given set of parameter packs into separate arguments by repeatedly
8116   /// transforming the pattern.
8117   ///
8118   /// \param EllipsisLoc The location of the ellipsis that identifies the
8119   /// pack expansion.
8120   ///
8121   /// \param PatternRange The source range that covers the entire pattern of
8122   /// the pack expansion.
8123   ///
8124   /// \param Unexpanded The set of unexpanded parameter packs within the
8125   /// pattern.
8126   ///
8127   /// \param ShouldExpand Will be set to \c true if the transformer should
8128   /// expand the corresponding pack expansions into separate arguments. When
8129   /// set, \c NumExpansions must also be set.
8130   ///
8131   /// \param RetainExpansion Whether the caller should add an unexpanded
8132   /// pack expansion after all of the expanded arguments. This is used
8133   /// when extending explicitly-specified template argument packs per
8134   /// C++0x [temp.arg.explicit]p9.
8135   ///
8136   /// \param NumExpansions The number of separate arguments that will be in
8137   /// the expanded form of the corresponding pack expansion. This is both an
8138   /// input and an output parameter, which can be set by the caller if the
8139   /// number of expansions is known a priori (e.g., due to a prior substitution)
8140   /// and will be set by the callee when the number of expansions is known.
8141   /// The callee must set this value when \c ShouldExpand is \c true; it may
8142   /// set this value in other cases.
8143   ///
8144   /// \returns true if an error occurred (e.g., because the parameter packs
8145   /// are to be instantiated with arguments of different lengths), false
8146   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8147   /// must be set.
8148   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8149                                        SourceRange PatternRange,
8150                              ArrayRef<UnexpandedParameterPack> Unexpanded,
8151                              const MultiLevelTemplateArgumentList &TemplateArgs,
8152                                        bool &ShouldExpand,
8153                                        bool &RetainExpansion,
8154                                        Optional<unsigned> &NumExpansions);
8155 
8156   /// Determine the number of arguments in the given pack expansion
8157   /// type.
8158   ///
8159   /// This routine assumes that the number of arguments in the expansion is
8160   /// consistent across all of the unexpanded parameter packs in its pattern.
8161   ///
8162   /// Returns an empty Optional if the type can't be expanded.
8163   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8164       const MultiLevelTemplateArgumentList &TemplateArgs);
8165 
8166   /// Determine whether the given declarator contains any unexpanded
8167   /// parameter packs.
8168   ///
8169   /// This routine is used by the parser to disambiguate function declarators
8170   /// with an ellipsis prior to the ')', e.g.,
8171   ///
8172   /// \code
8173   ///   void f(T...);
8174   /// \endcode
8175   ///
8176   /// To determine whether we have an (unnamed) function parameter pack or
8177   /// a variadic function.
8178   ///
8179   /// \returns true if the declarator contains any unexpanded parameter packs,
8180   /// false otherwise.
8181   bool containsUnexpandedParameterPacks(Declarator &D);
8182 
8183   /// Returns the pattern of the pack expansion for a template argument.
8184   ///
8185   /// \param OrigLoc The template argument to expand.
8186   ///
8187   /// \param Ellipsis Will be set to the location of the ellipsis.
8188   ///
8189   /// \param NumExpansions Will be set to the number of expansions that will
8190   /// be generated from this pack expansion, if known a priori.
8191   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8192       TemplateArgumentLoc OrigLoc,
8193       SourceLocation &Ellipsis,
8194       Optional<unsigned> &NumExpansions) const;
8195 
8196   /// Given a template argument that contains an unexpanded parameter pack, but
8197   /// which has already been substituted, attempt to determine the number of
8198   /// elements that will be produced once this argument is fully-expanded.
8199   ///
8200   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8201   /// avoid actually expanding the pack where possible.
8202   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8203 
8204   //===--------------------------------------------------------------------===//
8205   // C++ Template Argument Deduction (C++ [temp.deduct])
8206   //===--------------------------------------------------------------------===//
8207 
8208   /// Adjust the type \p ArgFunctionType to match the calling convention,
8209   /// noreturn, and optionally the exception specification of \p FunctionType.
8210   /// Deduction often wants to ignore these properties when matching function
8211   /// types.
8212   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8213                                bool AdjustExceptionSpec = false);
8214 
8215   /// Describes the result of template argument deduction.
8216   ///
8217   /// The TemplateDeductionResult enumeration describes the result of
8218   /// template argument deduction, as returned from
8219   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8220   /// structure provides additional information about the results of
8221   /// template argument deduction, e.g., the deduced template argument
8222   /// list (if successful) or the specific template parameters or
8223   /// deduced arguments that were involved in the failure.
8224   enum TemplateDeductionResult {
8225     /// Template argument deduction was successful.
8226     TDK_Success = 0,
8227     /// The declaration was invalid; do nothing.
8228     TDK_Invalid,
8229     /// Template argument deduction exceeded the maximum template
8230     /// instantiation depth (which has already been diagnosed).
8231     TDK_InstantiationDepth,
8232     /// Template argument deduction did not deduce a value
8233     /// for every template parameter.
8234     TDK_Incomplete,
8235     /// Template argument deduction did not deduce a value for every
8236     /// expansion of an expanded template parameter pack.
8237     TDK_IncompletePack,
8238     /// Template argument deduction produced inconsistent
8239     /// deduced values for the given template parameter.
8240     TDK_Inconsistent,
8241     /// Template argument deduction failed due to inconsistent
8242     /// cv-qualifiers on a template parameter type that would
8243     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8244     /// but were given a non-const "X".
8245     TDK_Underqualified,
8246     /// Substitution of the deduced template argument values
8247     /// resulted in an error.
8248     TDK_SubstitutionFailure,
8249     /// After substituting deduced template arguments, a dependent
8250     /// parameter type did not match the corresponding argument.
8251     TDK_DeducedMismatch,
8252     /// After substituting deduced template arguments, an element of
8253     /// a dependent parameter type did not match the corresponding element
8254     /// of the corresponding argument (when deducing from an initializer list).
8255     TDK_DeducedMismatchNested,
8256     /// A non-depnedent component of the parameter did not match the
8257     /// corresponding component of the argument.
8258     TDK_NonDeducedMismatch,
8259     /// When performing template argument deduction for a function
8260     /// template, there were too many call arguments.
8261     TDK_TooManyArguments,
8262     /// When performing template argument deduction for a function
8263     /// template, there were too few call arguments.
8264     TDK_TooFewArguments,
8265     /// The explicitly-specified template arguments were not valid
8266     /// template arguments for the given template.
8267     TDK_InvalidExplicitArguments,
8268     /// Checking non-dependent argument conversions failed.
8269     TDK_NonDependentConversionFailure,
8270     /// The deduced arguments did not satisfy the constraints associated
8271     /// with the template.
8272     TDK_ConstraintsNotSatisfied,
8273     /// Deduction failed; that's all we know.
8274     TDK_MiscellaneousDeductionFailure,
8275     /// CUDA Target attributes do not match.
8276     TDK_CUDATargetMismatch
8277   };
8278 
8279   TemplateDeductionResult
8280   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8281                           const TemplateArgumentList &TemplateArgs,
8282                           sema::TemplateDeductionInfo &Info);
8283 
8284   TemplateDeductionResult
8285   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8286                           const TemplateArgumentList &TemplateArgs,
8287                           sema::TemplateDeductionInfo &Info);
8288 
8289   TemplateDeductionResult SubstituteExplicitTemplateArguments(
8290       FunctionTemplateDecl *FunctionTemplate,
8291       TemplateArgumentListInfo &ExplicitTemplateArgs,
8292       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8293       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8294       sema::TemplateDeductionInfo &Info);
8295 
8296   /// brief A function argument from which we performed template argument
8297   // deduction for a call.
8298   struct OriginalCallArg {
OriginalCallArgOriginalCallArg8299     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8300                     unsigned ArgIdx, QualType OriginalArgType)
8301         : OriginalParamType(OriginalParamType),
8302           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8303           OriginalArgType(OriginalArgType) {}
8304 
8305     QualType OriginalParamType;
8306     bool DecomposedParam;
8307     unsigned ArgIdx;
8308     QualType OriginalArgType;
8309   };
8310 
8311   TemplateDeductionResult FinishTemplateArgumentDeduction(
8312       FunctionTemplateDecl *FunctionTemplate,
8313       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8314       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8315       sema::TemplateDeductionInfo &Info,
8316       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8317       bool PartialOverloading = false,
8318       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8319 
8320   TemplateDeductionResult DeduceTemplateArguments(
8321       FunctionTemplateDecl *FunctionTemplate,
8322       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8323       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8324       bool PartialOverloading,
8325       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8326 
8327   TemplateDeductionResult
8328   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8329                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8330                           QualType ArgFunctionType,
8331                           FunctionDecl *&Specialization,
8332                           sema::TemplateDeductionInfo &Info,
8333                           bool IsAddressOfFunction = false);
8334 
8335   TemplateDeductionResult
8336   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8337                           QualType ToType,
8338                           CXXConversionDecl *&Specialization,
8339                           sema::TemplateDeductionInfo &Info);
8340 
8341   TemplateDeductionResult
8342   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8343                           TemplateArgumentListInfo *ExplicitTemplateArgs,
8344                           FunctionDecl *&Specialization,
8345                           sema::TemplateDeductionInfo &Info,
8346                           bool IsAddressOfFunction = false);
8347 
8348   /// Substitute Replacement for \p auto in \p TypeWithAuto
8349   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8350   /// Substitute Replacement for auto in TypeWithAuto
8351   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8352                                           QualType Replacement);
8353   /// Completely replace the \c auto in \p TypeWithAuto by
8354   /// \p Replacement. This does not retain any \c auto type sugar.
8355   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8356   TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8357                                             QualType Replacement);
8358 
8359   /// Result type of DeduceAutoType.
8360   enum DeduceAutoResult {
8361     DAR_Succeeded,
8362     DAR_Failed,
8363     DAR_FailedAlreadyDiagnosed
8364   };
8365 
8366   DeduceAutoResult
8367   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8368                  Optional<unsigned> DependentDeductionDepth = None,
8369                  bool IgnoreConstraints = false);
8370   DeduceAutoResult
8371   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8372                  Optional<unsigned> DependentDeductionDepth = None,
8373                  bool IgnoreConstraints = false);
8374   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8375   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8376                         bool Diagnose = true);
8377 
8378   /// Declare implicit deduction guides for a class template if we've
8379   /// not already done so.
8380   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8381                                       SourceLocation Loc);
8382 
8383   QualType DeduceTemplateSpecializationFromInitializer(
8384       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8385       const InitializationKind &Kind, MultiExprArg Init);
8386 
8387   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8388                                         QualType Type, TypeSourceInfo *TSI,
8389                                         SourceRange Range, bool DirectInit,
8390                                         Expr *Init);
8391 
8392   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8393 
8394   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8395                                         SourceLocation ReturnLoc,
8396                                         Expr *&RetExpr, AutoType *AT);
8397 
8398   FunctionTemplateDecl *getMoreSpecializedTemplate(
8399       FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8400       TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8401       unsigned NumCallArguments2, bool Reversed = false);
8402   UnresolvedSetIterator
8403   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8404                      TemplateSpecCandidateSet &FailedCandidates,
8405                      SourceLocation Loc,
8406                      const PartialDiagnostic &NoneDiag,
8407                      const PartialDiagnostic &AmbigDiag,
8408                      const PartialDiagnostic &CandidateDiag,
8409                      bool Complain = true, QualType TargetType = QualType());
8410 
8411   ClassTemplatePartialSpecializationDecl *
8412   getMoreSpecializedPartialSpecialization(
8413                                   ClassTemplatePartialSpecializationDecl *PS1,
8414                                   ClassTemplatePartialSpecializationDecl *PS2,
8415                                   SourceLocation Loc);
8416 
8417   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8418                                     sema::TemplateDeductionInfo &Info);
8419 
8420   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8421       VarTemplatePartialSpecializationDecl *PS1,
8422       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8423 
8424   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8425                                     sema::TemplateDeductionInfo &Info);
8426 
8427   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8428       TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8429 
8430   void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8431                                   unsigned Depth, llvm::SmallBitVector &Used);
8432 
8433   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8434                                   bool OnlyDeduced,
8435                                   unsigned Depth,
8436                                   llvm::SmallBitVector &Used);
MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)8437   void MarkDeducedTemplateParameters(
8438                                   const FunctionTemplateDecl *FunctionTemplate,
8439                                   llvm::SmallBitVector &Deduced) {
8440     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8441   }
8442   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8443                                   const FunctionTemplateDecl *FunctionTemplate,
8444                                   llvm::SmallBitVector &Deduced);
8445 
8446   //===--------------------------------------------------------------------===//
8447   // C++ Template Instantiation
8448   //
8449 
8450   MultiLevelTemplateArgumentList
8451   getTemplateInstantiationArgs(NamedDecl *D,
8452                                const TemplateArgumentList *Innermost = nullptr,
8453                                bool RelativeToPrimary = false,
8454                                const FunctionDecl *Pattern = nullptr);
8455 
8456   /// A context in which code is being synthesized (where a source location
8457   /// alone is not sufficient to identify the context). This covers template
8458   /// instantiation and various forms of implicitly-generated functions.
8459   struct CodeSynthesisContext {
8460     /// The kind of template instantiation we are performing
8461     enum SynthesisKind {
8462       /// We are instantiating a template declaration. The entity is
8463       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8464       TemplateInstantiation,
8465 
8466       /// We are instantiating a default argument for a template
8467       /// parameter. The Entity is the template parameter whose argument is
8468       /// being instantiated, the Template is the template, and the
8469       /// TemplateArgs/NumTemplateArguments provide the template arguments as
8470       /// specified.
8471       DefaultTemplateArgumentInstantiation,
8472 
8473       /// We are instantiating a default argument for a function.
8474       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8475       /// provides the template arguments as specified.
8476       DefaultFunctionArgumentInstantiation,
8477 
8478       /// We are substituting explicit template arguments provided for
8479       /// a function template. The entity is a FunctionTemplateDecl.
8480       ExplicitTemplateArgumentSubstitution,
8481 
8482       /// We are substituting template argument determined as part of
8483       /// template argument deduction for either a class template
8484       /// partial specialization or a function template. The
8485       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8486       /// a TemplateDecl.
8487       DeducedTemplateArgumentSubstitution,
8488 
8489       /// We are substituting prior template arguments into a new
8490       /// template parameter. The template parameter itself is either a
8491       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8492       PriorTemplateArgumentSubstitution,
8493 
8494       /// We are checking the validity of a default template argument that
8495       /// has been used when naming a template-id.
8496       DefaultTemplateArgumentChecking,
8497 
8498       /// We are computing the exception specification for a defaulted special
8499       /// member function.
8500       ExceptionSpecEvaluation,
8501 
8502       /// We are instantiating the exception specification for a function
8503       /// template which was deferred until it was needed.
8504       ExceptionSpecInstantiation,
8505 
8506       /// We are instantiating a requirement of a requires expression.
8507       RequirementInstantiation,
8508 
8509       /// We are checking the satisfaction of a nested requirement of a requires
8510       /// expression.
8511       NestedRequirementConstraintsCheck,
8512 
8513       /// We are declaring an implicit special member function.
8514       DeclaringSpecialMember,
8515 
8516       /// We are declaring an implicit 'operator==' for a defaulted
8517       /// 'operator<=>'.
8518       DeclaringImplicitEqualityComparison,
8519 
8520       /// We are defining a synthesized function (such as a defaulted special
8521       /// member).
8522       DefiningSynthesizedFunction,
8523 
8524       // We are checking the constraints associated with a constrained entity or
8525       // the constraint expression of a concept. This includes the checks that
8526       // atomic constraints have the type 'bool' and that they can be constant
8527       // evaluated.
8528       ConstraintsCheck,
8529 
8530       // We are substituting template arguments into a constraint expression.
8531       ConstraintSubstitution,
8532 
8533       // We are normalizing a constraint expression.
8534       ConstraintNormalization,
8535 
8536       // We are substituting into the parameter mapping of an atomic constraint
8537       // during normalization.
8538       ParameterMappingSubstitution,
8539 
8540       /// We are rewriting a comparison operator in terms of an operator<=>.
8541       RewritingOperatorAsSpaceship,
8542 
8543       /// We are initializing a structured binding.
8544       InitializingStructuredBinding,
8545 
8546       /// We are marking a class as __dllexport.
8547       MarkingClassDllexported,
8548 
8549       /// Added for Template instantiation observation.
8550       /// Memoization means we are _not_ instantiating a template because
8551       /// it is already instantiated (but we entered a context where we
8552       /// would have had to if it was not already instantiated).
8553       Memoization
8554     } Kind;
8555 
8556     /// Was the enclosing context a non-instantiation SFINAE context?
8557     bool SavedInNonInstantiationSFINAEContext;
8558 
8559     /// The point of instantiation or synthesis within the source code.
8560     SourceLocation PointOfInstantiation;
8561 
8562     /// The entity that is being synthesized.
8563     Decl *Entity;
8564 
8565     /// The template (or partial specialization) in which we are
8566     /// performing the instantiation, for substitutions of prior template
8567     /// arguments.
8568     NamedDecl *Template;
8569 
8570     /// The list of template arguments we are substituting, if they
8571     /// are not part of the entity.
8572     const TemplateArgument *TemplateArgs;
8573 
8574     // FIXME: Wrap this union around more members, or perhaps store the
8575     // kind-specific members in the RAII object owning the context.
8576     union {
8577       /// The number of template arguments in TemplateArgs.
8578       unsigned NumTemplateArgs;
8579 
8580       /// The special member being declared or defined.
8581       CXXSpecialMember SpecialMember;
8582     };
8583 
template_argumentsCodeSynthesisContext8584     ArrayRef<TemplateArgument> template_arguments() const {
8585       assert(Kind != DeclaringSpecialMember);
8586       return {TemplateArgs, NumTemplateArgs};
8587     }
8588 
8589     /// The template deduction info object associated with the
8590     /// substitution or checking of explicit or deduced template arguments.
8591     sema::TemplateDeductionInfo *DeductionInfo;
8592 
8593     /// The source range that covers the construct that cause
8594     /// the instantiation, e.g., the template-id that causes a class
8595     /// template instantiation.
8596     SourceRange InstantiationRange;
8597 
CodeSynthesisContextCodeSynthesisContext8598     CodeSynthesisContext()
8599         : Kind(TemplateInstantiation),
8600           SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8601           Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8602           DeductionInfo(nullptr) {}
8603 
8604     /// Determines whether this template is an actual instantiation
8605     /// that should be counted toward the maximum instantiation depth.
8606     bool isInstantiationRecord() const;
8607   };
8608 
8609   /// List of active code synthesis contexts.
8610   ///
8611   /// This vector is treated as a stack. As synthesis of one entity requires
8612   /// synthesis of another, additional contexts are pushed onto the stack.
8613   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8614 
8615   /// Specializations whose definitions are currently being instantiated.
8616   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8617 
8618   /// Non-dependent types used in templates that have already been instantiated
8619   /// by some template instantiation.
8620   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8621 
8622   /// Extra modules inspected when performing a lookup during a template
8623   /// instantiation. Computed lazily.
8624   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8625 
8626   /// Cache of additional modules that should be used for name lookup
8627   /// within the current template instantiation. Computed lazily; use
8628   /// getLookupModules() to get a complete set.
8629   llvm::DenseSet<Module*> LookupModulesCache;
8630 
8631   /// Get the set of additional modules that should be checked during
8632   /// name lookup. A module and its imports become visible when instanting a
8633   /// template defined within it.
8634   llvm::DenseSet<Module*> &getLookupModules();
8635 
8636   /// Map from the most recent declaration of a namespace to the most
8637   /// recent visible declaration of that namespace.
8638   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
8639 
8640   /// Whether we are in a SFINAE context that is not associated with
8641   /// template instantiation.
8642   ///
8643   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
8644   /// of a template instantiation or template argument deduction.
8645   bool InNonInstantiationSFINAEContext;
8646 
8647   /// The number of \p CodeSynthesisContexts that are not template
8648   /// instantiations and, therefore, should not be counted as part of the
8649   /// instantiation depth.
8650   ///
8651   /// When the instantiation depth reaches the user-configurable limit
8652   /// \p LangOptions::InstantiationDepth we will abort instantiation.
8653   // FIXME: Should we have a similar limit for other forms of synthesis?
8654   unsigned NonInstantiationEntries;
8655 
8656   /// The depth of the context stack at the point when the most recent
8657   /// error or warning was produced.
8658   ///
8659   /// This value is used to suppress printing of redundant context stacks
8660   /// when there are multiple errors or warnings in the same instantiation.
8661   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
8662   unsigned LastEmittedCodeSynthesisContextDepth = 0;
8663 
8664   /// The template instantiation callbacks to trace or track
8665   /// instantiations (objects can be chained).
8666   ///
8667   /// This callbacks is used to print, trace or track template
8668   /// instantiations as they are being constructed.
8669   std::vector<std::unique_ptr<TemplateInstantiationCallback>>
8670       TemplateInstCallbacks;
8671 
8672   /// The current index into pack expansion arguments that will be
8673   /// used for substitution of parameter packs.
8674   ///
8675   /// The pack expansion index will be -1 to indicate that parameter packs
8676   /// should be instantiated as themselves. Otherwise, the index specifies
8677   /// which argument within the parameter pack will be used for substitution.
8678   int ArgumentPackSubstitutionIndex;
8679 
8680   /// RAII object used to change the argument pack substitution index
8681   /// within a \c Sema object.
8682   ///
8683   /// See \c ArgumentPackSubstitutionIndex for more information.
8684   class ArgumentPackSubstitutionIndexRAII {
8685     Sema &Self;
8686     int OldSubstitutionIndex;
8687 
8688   public:
ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)8689     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
8690       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
8691       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
8692     }
8693 
~ArgumentPackSubstitutionIndexRAII()8694     ~ArgumentPackSubstitutionIndexRAII() {
8695       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
8696     }
8697   };
8698 
8699   friend class ArgumentPackSubstitutionRAII;
8700 
8701   /// For each declaration that involved template argument deduction, the
8702   /// set of diagnostics that were suppressed during that template argument
8703   /// deduction.
8704   ///
8705   /// FIXME: Serialize this structure to the AST file.
8706   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
8707     SuppressedDiagnosticsMap;
8708   SuppressedDiagnosticsMap SuppressedDiagnostics;
8709 
8710   /// A stack object to be created when performing template
8711   /// instantiation.
8712   ///
8713   /// Construction of an object of type \c InstantiatingTemplate
8714   /// pushes the current instantiation onto the stack of active
8715   /// instantiations. If the size of this stack exceeds the maximum
8716   /// number of recursive template instantiations, construction
8717   /// produces an error and evaluates true.
8718   ///
8719   /// Destruction of this object will pop the named instantiation off
8720   /// the stack.
8721   struct InstantiatingTemplate {
8722     /// Note that we are instantiating a class template,
8723     /// function template, variable template, alias template,
8724     /// or a member thereof.
8725     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8726                           Decl *Entity,
8727                           SourceRange InstantiationRange = SourceRange());
8728 
8729     struct ExceptionSpecification {};
8730     /// Note that we are instantiating an exception specification
8731     /// of a function template.
8732     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8733                           FunctionDecl *Entity, ExceptionSpecification,
8734                           SourceRange InstantiationRange = SourceRange());
8735 
8736     /// Note that we are instantiating a default argument in a
8737     /// template-id.
8738     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8739                           TemplateParameter Param, TemplateDecl *Template,
8740                           ArrayRef<TemplateArgument> TemplateArgs,
8741                           SourceRange InstantiationRange = SourceRange());
8742 
8743     /// Note that we are substituting either explicitly-specified or
8744     /// deduced template arguments during function template argument deduction.
8745     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8746                           FunctionTemplateDecl *FunctionTemplate,
8747                           ArrayRef<TemplateArgument> TemplateArgs,
8748                           CodeSynthesisContext::SynthesisKind Kind,
8749                           sema::TemplateDeductionInfo &DeductionInfo,
8750                           SourceRange InstantiationRange = SourceRange());
8751 
8752     /// Note that we are instantiating as part of template
8753     /// argument deduction for a class template declaration.
8754     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8755                           TemplateDecl *Template,
8756                           ArrayRef<TemplateArgument> TemplateArgs,
8757                           sema::TemplateDeductionInfo &DeductionInfo,
8758                           SourceRange InstantiationRange = SourceRange());
8759 
8760     /// Note that we are instantiating as part of template
8761     /// argument deduction for a class template partial
8762     /// specialization.
8763     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8764                           ClassTemplatePartialSpecializationDecl *PartialSpec,
8765                           ArrayRef<TemplateArgument> TemplateArgs,
8766                           sema::TemplateDeductionInfo &DeductionInfo,
8767                           SourceRange InstantiationRange = SourceRange());
8768 
8769     /// Note that we are instantiating as part of template
8770     /// argument deduction for a variable template partial
8771     /// specialization.
8772     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8773                           VarTemplatePartialSpecializationDecl *PartialSpec,
8774                           ArrayRef<TemplateArgument> TemplateArgs,
8775                           sema::TemplateDeductionInfo &DeductionInfo,
8776                           SourceRange InstantiationRange = SourceRange());
8777 
8778     /// Note that we are instantiating a default argument for a function
8779     /// parameter.
8780     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8781                           ParmVarDecl *Param,
8782                           ArrayRef<TemplateArgument> TemplateArgs,
8783                           SourceRange InstantiationRange = SourceRange());
8784 
8785     /// Note that we are substituting prior template arguments into a
8786     /// non-type parameter.
8787     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8788                           NamedDecl *Template,
8789                           NonTypeTemplateParmDecl *Param,
8790                           ArrayRef<TemplateArgument> TemplateArgs,
8791                           SourceRange InstantiationRange);
8792 
8793     /// Note that we are substituting prior template arguments into a
8794     /// template template parameter.
8795     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8796                           NamedDecl *Template,
8797                           TemplateTemplateParmDecl *Param,
8798                           ArrayRef<TemplateArgument> TemplateArgs,
8799                           SourceRange InstantiationRange);
8800 
8801     /// Note that we are checking the default template argument
8802     /// against the template parameter for a given template-id.
8803     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8804                           TemplateDecl *Template,
8805                           NamedDecl *Param,
8806                           ArrayRef<TemplateArgument> TemplateArgs,
8807                           SourceRange InstantiationRange);
8808 
8809     struct ConstraintsCheck {};
8810     /// \brief Note that we are checking the constraints associated with some
8811     /// constrained entity (a concept declaration or a template with associated
8812     /// constraints).
8813     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8814                           ConstraintsCheck, NamedDecl *Template,
8815                           ArrayRef<TemplateArgument> TemplateArgs,
8816                           SourceRange InstantiationRange);
8817 
8818     struct ConstraintSubstitution {};
8819     /// \brief Note that we are checking a constraint expression associated
8820     /// with a template declaration or as part of the satisfaction check of a
8821     /// concept.
8822     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8823                           ConstraintSubstitution, NamedDecl *Template,
8824                           sema::TemplateDeductionInfo &DeductionInfo,
8825                           SourceRange InstantiationRange);
8826 
8827     struct ConstraintNormalization {};
8828     /// \brief Note that we are normalizing a constraint expression.
8829     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8830                           ConstraintNormalization, NamedDecl *Template,
8831                           SourceRange InstantiationRange);
8832 
8833     struct ParameterMappingSubstitution {};
8834     /// \brief Note that we are subtituting into the parameter mapping of an
8835     /// atomic constraint during constraint normalization.
8836     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8837                           ParameterMappingSubstitution, NamedDecl *Template,
8838                           SourceRange InstantiationRange);
8839 
8840     /// \brief Note that we are substituting template arguments into a part of
8841     /// a requirement of a requires expression.
8842     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8843                           concepts::Requirement *Req,
8844                           sema::TemplateDeductionInfo &DeductionInfo,
8845                           SourceRange InstantiationRange = SourceRange());
8846 
8847     /// \brief Note that we are checking the satisfaction of the constraint
8848     /// expression inside of a nested requirement.
8849     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
8850                           concepts::NestedRequirement *Req, ConstraintsCheck,
8851                           SourceRange InstantiationRange = SourceRange());
8852 
8853     /// Note that we have finished instantiating this template.
8854     void Clear();
8855 
~InstantiatingTemplateInstantiatingTemplate8856     ~InstantiatingTemplate() { Clear(); }
8857 
8858     /// Determines whether we have exceeded the maximum
8859     /// recursive template instantiations.
isInvalidInstantiatingTemplate8860     bool isInvalid() const { return Invalid; }
8861 
8862     /// Determine whether we are already instantiating this
8863     /// specialization in some surrounding active instantiation.
isAlreadyInstantiatingInstantiatingTemplate8864     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
8865 
8866   private:
8867     Sema &SemaRef;
8868     bool Invalid;
8869     bool AlreadyInstantiating;
8870     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
8871                                  SourceRange InstantiationRange);
8872 
8873     InstantiatingTemplate(
8874         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
8875         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
8876         Decl *Entity, NamedDecl *Template = nullptr,
8877         ArrayRef<TemplateArgument> TemplateArgs = None,
8878         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
8879 
8880     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
8881 
8882     InstantiatingTemplate&
8883     operator=(const InstantiatingTemplate&) = delete;
8884   };
8885 
8886   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
8887   void popCodeSynthesisContext();
8888 
8889   /// Determine whether we are currently performing template instantiation.
inTemplateInstantiation()8890   bool inTemplateInstantiation() const {
8891     return CodeSynthesisContexts.size() > NonInstantiationEntries;
8892   }
8893 
PrintContextStack()8894   void PrintContextStack() {
8895     if (!CodeSynthesisContexts.empty() &&
8896         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
8897       PrintInstantiationStack();
8898       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
8899     }
8900     if (PragmaAttributeCurrentTargetDecl)
8901       PrintPragmaAttributeInstantiationPoint();
8902   }
8903   void PrintInstantiationStack();
8904 
8905   void PrintPragmaAttributeInstantiationPoint();
8906 
8907   /// Determines whether we are currently in a context where
8908   /// template argument substitution failures are not considered
8909   /// errors.
8910   ///
8911   /// \returns An empty \c Optional if we're not in a SFINAE context.
8912   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
8913   /// template-deduction context object, which can be used to capture
8914   /// diagnostics that will be suppressed.
8915   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
8916 
8917   /// Determines whether we are currently in a context that
8918   /// is not evaluated as per C++ [expr] p5.
isUnevaluatedContext()8919   bool isUnevaluatedContext() const {
8920     assert(!ExprEvalContexts.empty() &&
8921            "Must be in an expression evaluation context");
8922     return ExprEvalContexts.back().isUnevaluated();
8923   }
8924 
8925   /// RAII class used to determine whether SFINAE has
8926   /// trapped any errors that occur during template argument
8927   /// deduction.
8928   class SFINAETrap {
8929     Sema &SemaRef;
8930     unsigned PrevSFINAEErrors;
8931     bool PrevInNonInstantiationSFINAEContext;
8932     bool PrevAccessCheckingSFINAE;
8933     bool PrevLastDiagnosticIgnored;
8934 
8935   public:
8936     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
SemaRef(SemaRef)8937       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
8938         PrevInNonInstantiationSFINAEContext(
8939                                       SemaRef.InNonInstantiationSFINAEContext),
8940         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
8941         PrevLastDiagnosticIgnored(
8942             SemaRef.getDiagnostics().isLastDiagnosticIgnored())
8943     {
8944       if (!SemaRef.isSFINAEContext())
8945         SemaRef.InNonInstantiationSFINAEContext = true;
8946       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
8947     }
8948 
~SFINAETrap()8949     ~SFINAETrap() {
8950       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
8951       SemaRef.InNonInstantiationSFINAEContext
8952         = PrevInNonInstantiationSFINAEContext;
8953       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
8954       SemaRef.getDiagnostics().setLastDiagnosticIgnored(
8955           PrevLastDiagnosticIgnored);
8956     }
8957 
8958     /// Determine whether any SFINAE errors have been trapped.
hasErrorOccurred()8959     bool hasErrorOccurred() const {
8960       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
8961     }
8962   };
8963 
8964   /// RAII class used to indicate that we are performing provisional
8965   /// semantic analysis to determine the validity of a construct, so
8966   /// typo-correction and diagnostics in the immediate context (not within
8967   /// implicitly-instantiated templates) should be suppressed.
8968   class TentativeAnalysisScope {
8969     Sema &SemaRef;
8970     // FIXME: Using a SFINAETrap for this is a hack.
8971     SFINAETrap Trap;
8972     bool PrevDisableTypoCorrection;
8973   public:
TentativeAnalysisScope(Sema & SemaRef)8974     explicit TentativeAnalysisScope(Sema &SemaRef)
8975         : SemaRef(SemaRef), Trap(SemaRef, true),
8976           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
8977       SemaRef.DisableTypoCorrection = true;
8978     }
~TentativeAnalysisScope()8979     ~TentativeAnalysisScope() {
8980       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
8981     }
8982   };
8983 
8984   /// The current instantiation scope used to store local
8985   /// variables.
8986   LocalInstantiationScope *CurrentInstantiationScope;
8987 
8988   /// Tracks whether we are in a context where typo correction is
8989   /// disabled.
8990   bool DisableTypoCorrection;
8991 
8992   /// The number of typos corrected by CorrectTypo.
8993   unsigned TyposCorrected;
8994 
8995   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
8996   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
8997 
8998   /// A cache containing identifiers for which typo correction failed and
8999   /// their locations, so that repeated attempts to correct an identifier in a
9000   /// given location are ignored if typo correction already failed for it.
9001   IdentifierSourceLocations TypoCorrectionFailures;
9002 
9003   /// Worker object for performing CFG-based warnings.
9004   sema::AnalysisBasedWarnings AnalysisWarnings;
9005   threadSafety::BeforeSet *ThreadSafetyDeclCache;
9006 
9007   /// An entity for which implicit template instantiation is required.
9008   ///
9009   /// The source location associated with the declaration is the first place in
9010   /// the source code where the declaration was "used". It is not necessarily
9011   /// the point of instantiation (which will be either before or after the
9012   /// namespace-scope declaration that triggered this implicit instantiation),
9013   /// However, it is the location that diagnostics should generally refer to,
9014   /// because users will need to know what code triggered the instantiation.
9015   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9016 
9017   /// The queue of implicit template instantiations that are required
9018   /// but have not yet been performed.
9019   std::deque<PendingImplicitInstantiation> PendingInstantiations;
9020 
9021   /// Queue of implicit template instantiations that cannot be performed
9022   /// eagerly.
9023   SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9024 
9025   class GlobalEagerInstantiationScope {
9026   public:
GlobalEagerInstantiationScope(Sema & S,bool Enabled)9027     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9028         : S(S), Enabled(Enabled) {
9029       if (!Enabled) return;
9030 
9031       SavedPendingInstantiations.swap(S.PendingInstantiations);
9032       SavedVTableUses.swap(S.VTableUses);
9033     }
9034 
perform()9035     void perform() {
9036       if (Enabled) {
9037         S.DefineUsedVTables();
9038         S.PerformPendingInstantiations();
9039       }
9040     }
9041 
~GlobalEagerInstantiationScope()9042     ~GlobalEagerInstantiationScope() {
9043       if (!Enabled) return;
9044 
9045       // Restore the set of pending vtables.
9046       assert(S.VTableUses.empty() &&
9047              "VTableUses should be empty before it is discarded.");
9048       S.VTableUses.swap(SavedVTableUses);
9049 
9050       // Restore the set of pending implicit instantiations.
9051       if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9052         assert(S.PendingInstantiations.empty() &&
9053                "PendingInstantiations should be empty before it is discarded.");
9054         S.PendingInstantiations.swap(SavedPendingInstantiations);
9055       } else {
9056         // Template instantiations in the PCH may be delayed until the TU.
9057         S.PendingInstantiations.swap(SavedPendingInstantiations);
9058         S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9059                                        SavedPendingInstantiations.begin(),
9060                                        SavedPendingInstantiations.end());
9061       }
9062     }
9063 
9064   private:
9065     Sema &S;
9066     SmallVector<VTableUse, 16> SavedVTableUses;
9067     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9068     bool Enabled;
9069   };
9070 
9071   /// The queue of implicit template instantiations that are required
9072   /// and must be performed within the current local scope.
9073   ///
9074   /// This queue is only used for member functions of local classes in
9075   /// templates, which must be instantiated in the same scope as their
9076   /// enclosing function, so that they can reference function-local
9077   /// types, static variables, enumerators, etc.
9078   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9079 
9080   class LocalEagerInstantiationScope {
9081   public:
LocalEagerInstantiationScope(Sema & S)9082     LocalEagerInstantiationScope(Sema &S) : S(S) {
9083       SavedPendingLocalImplicitInstantiations.swap(
9084           S.PendingLocalImplicitInstantiations);
9085     }
9086 
perform()9087     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9088 
~LocalEagerInstantiationScope()9089     ~LocalEagerInstantiationScope() {
9090       assert(S.PendingLocalImplicitInstantiations.empty() &&
9091              "there shouldn't be any pending local implicit instantiations");
9092       SavedPendingLocalImplicitInstantiations.swap(
9093           S.PendingLocalImplicitInstantiations);
9094     }
9095 
9096   private:
9097     Sema &S;
9098     std::deque<PendingImplicitInstantiation>
9099         SavedPendingLocalImplicitInstantiations;
9100   };
9101 
9102   /// A helper class for building up ExtParameterInfos.
9103   class ExtParameterInfoBuilder {
9104     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9105     bool HasInteresting = false;
9106 
9107   public:
9108     /// Set the ExtParameterInfo for the parameter at the given index,
9109     ///
set(unsigned index,FunctionProtoType::ExtParameterInfo info)9110     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9111       assert(Infos.size() <= index);
9112       Infos.resize(index);
9113       Infos.push_back(info);
9114 
9115       if (!HasInteresting)
9116         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9117     }
9118 
9119     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9120     /// ExtParameterInfo array we've built up.
9121     const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams)9122     getPointerOrNull(unsigned numParams) {
9123       if (!HasInteresting) return nullptr;
9124       Infos.resize(numParams);
9125       return Infos.data();
9126     }
9127   };
9128 
9129   void PerformPendingInstantiations(bool LocalOnly = false);
9130 
9131   TypeSourceInfo *SubstType(TypeSourceInfo *T,
9132                             const MultiLevelTemplateArgumentList &TemplateArgs,
9133                             SourceLocation Loc, DeclarationName Entity,
9134                             bool AllowDeducedTST = false);
9135 
9136   QualType SubstType(QualType T,
9137                      const MultiLevelTemplateArgumentList &TemplateArgs,
9138                      SourceLocation Loc, DeclarationName Entity);
9139 
9140   TypeSourceInfo *SubstType(TypeLoc TL,
9141                             const MultiLevelTemplateArgumentList &TemplateArgs,
9142                             SourceLocation Loc, DeclarationName Entity);
9143 
9144   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9145                             const MultiLevelTemplateArgumentList &TemplateArgs,
9146                                         SourceLocation Loc,
9147                                         DeclarationName Entity,
9148                                         CXXRecordDecl *ThisContext,
9149                                         Qualifiers ThisTypeQuals);
9150   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9151                           const MultiLevelTemplateArgumentList &Args);
9152   bool SubstExceptionSpec(SourceLocation Loc,
9153                           FunctionProtoType::ExceptionSpecInfo &ESI,
9154                           SmallVectorImpl<QualType> &ExceptionStorage,
9155                           const MultiLevelTemplateArgumentList &Args);
9156   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9157                             const MultiLevelTemplateArgumentList &TemplateArgs,
9158                                 int indexAdjustment,
9159                                 Optional<unsigned> NumExpansions,
9160                                 bool ExpectParameterPack);
9161   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9162                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9163                       const MultiLevelTemplateArgumentList &TemplateArgs,
9164                       SmallVectorImpl<QualType> &ParamTypes,
9165                       SmallVectorImpl<ParmVarDecl *> *OutParams,
9166                       ExtParameterInfoBuilder &ParamInfos);
9167   ExprResult SubstExpr(Expr *E,
9168                        const MultiLevelTemplateArgumentList &TemplateArgs);
9169 
9170   /// Substitute the given template arguments into a list of
9171   /// expressions, expanding pack expansions if required.
9172   ///
9173   /// \param Exprs The list of expressions to substitute into.
9174   ///
9175   /// \param IsCall Whether this is some form of call, in which case
9176   /// default arguments will be dropped.
9177   ///
9178   /// \param TemplateArgs The set of template arguments to substitute.
9179   ///
9180   /// \param Outputs Will receive all of the substituted arguments.
9181   ///
9182   /// \returns true if an error occurred, false otherwise.
9183   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9184                   const MultiLevelTemplateArgumentList &TemplateArgs,
9185                   SmallVectorImpl<Expr *> &Outputs);
9186 
9187   StmtResult SubstStmt(Stmt *S,
9188                        const MultiLevelTemplateArgumentList &TemplateArgs);
9189 
9190   TemplateParameterList *
9191   SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9192                       const MultiLevelTemplateArgumentList &TemplateArgs);
9193 
9194   bool
9195   SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9196                          const MultiLevelTemplateArgumentList &TemplateArgs,
9197                          TemplateArgumentListInfo &Outputs);
9198 
9199 
9200   Decl *SubstDecl(Decl *D, DeclContext *Owner,
9201                   const MultiLevelTemplateArgumentList &TemplateArgs);
9202 
9203   /// Substitute the name and return type of a defaulted 'operator<=>' to form
9204   /// an implicit 'operator=='.
9205   FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9206                                            FunctionDecl *Spaceship);
9207 
9208   ExprResult SubstInitializer(Expr *E,
9209                        const MultiLevelTemplateArgumentList &TemplateArgs,
9210                        bool CXXDirectInit);
9211 
9212   bool
9213   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9214                       CXXRecordDecl *Pattern,
9215                       const MultiLevelTemplateArgumentList &TemplateArgs);
9216 
9217   bool
9218   InstantiateClass(SourceLocation PointOfInstantiation,
9219                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9220                    const MultiLevelTemplateArgumentList &TemplateArgs,
9221                    TemplateSpecializationKind TSK,
9222                    bool Complain = true);
9223 
9224   bool InstantiateEnum(SourceLocation PointOfInstantiation,
9225                        EnumDecl *Instantiation, EnumDecl *Pattern,
9226                        const MultiLevelTemplateArgumentList &TemplateArgs,
9227                        TemplateSpecializationKind TSK);
9228 
9229   bool InstantiateInClassInitializer(
9230       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9231       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9232 
9233   struct LateInstantiatedAttribute {
9234     const Attr *TmplAttr;
9235     LocalInstantiationScope *Scope;
9236     Decl *NewDecl;
9237 
LateInstantiatedAttributeLateInstantiatedAttribute9238     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9239                               Decl *D)
9240       : TmplAttr(A), Scope(S), NewDecl(D)
9241     { }
9242   };
9243   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9244 
9245   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9246                         const Decl *Pattern, Decl *Inst,
9247                         LateInstantiatedAttrVec *LateAttrs = nullptr,
9248                         LocalInstantiationScope *OuterMostScope = nullptr);
9249 
9250   void
9251   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9252                           const Decl *Pattern, Decl *Inst,
9253                           LateInstantiatedAttrVec *LateAttrs = nullptr,
9254                           LocalInstantiationScope *OuterMostScope = nullptr);
9255 
9256   bool usesPartialOrExplicitSpecialization(
9257       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9258 
9259   bool
9260   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9261                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9262                            TemplateSpecializationKind TSK,
9263                            bool Complain = true);
9264 
9265   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9266                                CXXRecordDecl *Instantiation,
9267                             const MultiLevelTemplateArgumentList &TemplateArgs,
9268                                TemplateSpecializationKind TSK);
9269 
9270   void InstantiateClassTemplateSpecializationMembers(
9271                                           SourceLocation PointOfInstantiation,
9272                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
9273                                                 TemplateSpecializationKind TSK);
9274 
9275   NestedNameSpecifierLoc
9276   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9277                            const MultiLevelTemplateArgumentList &TemplateArgs);
9278 
9279   DeclarationNameInfo
9280   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9281                            const MultiLevelTemplateArgumentList &TemplateArgs);
9282   TemplateName
9283   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9284                     SourceLocation Loc,
9285                     const MultiLevelTemplateArgumentList &TemplateArgs);
9286   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
9287              TemplateArgumentListInfo &Result,
9288              const MultiLevelTemplateArgumentList &TemplateArgs);
9289 
9290   bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9291                                   ParmVarDecl *Param);
9292   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9293                                 FunctionDecl *Function);
9294   bool CheckInstantiatedFunctionTemplateConstraints(
9295       SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9296       ArrayRef<TemplateArgument> TemplateArgs,
9297       ConstraintSatisfaction &Satisfaction);
9298   FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9299                                                const TemplateArgumentList *Args,
9300                                                SourceLocation Loc);
9301   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9302                                      FunctionDecl *Function,
9303                                      bool Recursive = false,
9304                                      bool DefinitionRequired = false,
9305                                      bool AtEndOfTU = false);
9306   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9307       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9308       const TemplateArgumentList &TemplateArgList,
9309       const TemplateArgumentListInfo &TemplateArgsInfo,
9310       SmallVectorImpl<TemplateArgument> &Converted,
9311       SourceLocation PointOfInstantiation,
9312       LateInstantiatedAttrVec *LateAttrs = nullptr,
9313       LocalInstantiationScope *StartingScope = nullptr);
9314   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9315       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9316       const MultiLevelTemplateArgumentList &TemplateArgs);
9317   void
9318   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9319                              const MultiLevelTemplateArgumentList &TemplateArgs,
9320                              LateInstantiatedAttrVec *LateAttrs,
9321                              DeclContext *Owner,
9322                              LocalInstantiationScope *StartingScope,
9323                              bool InstantiatingVarTemplate = false,
9324                              VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9325 
9326   void InstantiateVariableInitializer(
9327       VarDecl *Var, VarDecl *OldVar,
9328       const MultiLevelTemplateArgumentList &TemplateArgs);
9329   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9330                                      VarDecl *Var, bool Recursive = false,
9331                                      bool DefinitionRequired = false,
9332                                      bool AtEndOfTU = false);
9333 
9334   void InstantiateMemInitializers(CXXConstructorDecl *New,
9335                                   const CXXConstructorDecl *Tmpl,
9336                             const MultiLevelTemplateArgumentList &TemplateArgs);
9337 
9338   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9339                           const MultiLevelTemplateArgumentList &TemplateArgs,
9340                           bool FindingInstantiatedContext = false);
9341   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9342                           const MultiLevelTemplateArgumentList &TemplateArgs);
9343 
9344   // Objective-C declarations.
9345   enum ObjCContainerKind {
9346     OCK_None = -1,
9347     OCK_Interface = 0,
9348     OCK_Protocol,
9349     OCK_Category,
9350     OCK_ClassExtension,
9351     OCK_Implementation,
9352     OCK_CategoryImplementation
9353   };
9354   ObjCContainerKind getObjCContainerKind() const;
9355 
9356   DeclResult actOnObjCTypeParam(Scope *S,
9357                                 ObjCTypeParamVariance variance,
9358                                 SourceLocation varianceLoc,
9359                                 unsigned index,
9360                                 IdentifierInfo *paramName,
9361                                 SourceLocation paramLoc,
9362                                 SourceLocation colonLoc,
9363                                 ParsedType typeBound);
9364 
9365   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9366                                             ArrayRef<Decl *> typeParams,
9367                                             SourceLocation rAngleLoc);
9368   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9369 
9370   Decl *ActOnStartClassInterface(
9371       Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9372       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9373       IdentifierInfo *SuperName, SourceLocation SuperLoc,
9374       ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9375       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9376       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9377       const ParsedAttributesView &AttrList);
9378 
9379   void ActOnSuperClassOfClassInterface(Scope *S,
9380                                        SourceLocation AtInterfaceLoc,
9381                                        ObjCInterfaceDecl *IDecl,
9382                                        IdentifierInfo *ClassName,
9383                                        SourceLocation ClassLoc,
9384                                        IdentifierInfo *SuperName,
9385                                        SourceLocation SuperLoc,
9386                                        ArrayRef<ParsedType> SuperTypeArgs,
9387                                        SourceRange SuperTypeArgsRange);
9388 
9389   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9390                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
9391                                IdentifierInfo *SuperName,
9392                                SourceLocation SuperLoc);
9393 
9394   Decl *ActOnCompatibilityAlias(
9395                     SourceLocation AtCompatibilityAliasLoc,
9396                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
9397                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
9398 
9399   bool CheckForwardProtocolDeclarationForCircularDependency(
9400     IdentifierInfo *PName,
9401     SourceLocation &PLoc, SourceLocation PrevLoc,
9402     const ObjCList<ObjCProtocolDecl> &PList);
9403 
9404   Decl *ActOnStartProtocolInterface(
9405       SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9406       SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9407       unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9408       SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9409 
9410   Decl *ActOnStartCategoryInterface(
9411       SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9412       SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9413       IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9414       Decl *const *ProtoRefs, unsigned NumProtoRefs,
9415       const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9416       const ParsedAttributesView &AttrList);
9417 
9418   Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9419                                       IdentifierInfo *ClassName,
9420                                       SourceLocation ClassLoc,
9421                                       IdentifierInfo *SuperClassname,
9422                                       SourceLocation SuperClassLoc,
9423                                       const ParsedAttributesView &AttrList);
9424 
9425   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9426                                          IdentifierInfo *ClassName,
9427                                          SourceLocation ClassLoc,
9428                                          IdentifierInfo *CatName,
9429                                          SourceLocation CatLoc,
9430                                          const ParsedAttributesView &AttrList);
9431 
9432   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9433                                                ArrayRef<Decl *> Decls);
9434 
9435   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9436                    IdentifierInfo **IdentList,
9437                    SourceLocation *IdentLocs,
9438                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
9439                    unsigned NumElts);
9440 
9441   DeclGroupPtrTy
9442   ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9443                                   ArrayRef<IdentifierLocPair> IdentList,
9444                                   const ParsedAttributesView &attrList);
9445 
9446   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9447                                ArrayRef<IdentifierLocPair> ProtocolId,
9448                                SmallVectorImpl<Decl *> &Protocols);
9449 
9450   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9451                                     SourceLocation ProtocolLoc,
9452                                     IdentifierInfo *TypeArgId,
9453                                     SourceLocation TypeArgLoc,
9454                                     bool SelectProtocolFirst = false);
9455 
9456   /// Given a list of identifiers (and their locations), resolve the
9457   /// names to either Objective-C protocol qualifiers or type
9458   /// arguments, as appropriate.
9459   void actOnObjCTypeArgsOrProtocolQualifiers(
9460          Scope *S,
9461          ParsedType baseType,
9462          SourceLocation lAngleLoc,
9463          ArrayRef<IdentifierInfo *> identifiers,
9464          ArrayRef<SourceLocation> identifierLocs,
9465          SourceLocation rAngleLoc,
9466          SourceLocation &typeArgsLAngleLoc,
9467          SmallVectorImpl<ParsedType> &typeArgs,
9468          SourceLocation &typeArgsRAngleLoc,
9469          SourceLocation &protocolLAngleLoc,
9470          SmallVectorImpl<Decl *> &protocols,
9471          SourceLocation &protocolRAngleLoc,
9472          bool warnOnIncompleteProtocols);
9473 
9474   /// Build a an Objective-C protocol-qualified 'id' type where no
9475   /// base type was specified.
9476   TypeResult actOnObjCProtocolQualifierType(
9477                SourceLocation lAngleLoc,
9478                ArrayRef<Decl *> protocols,
9479                ArrayRef<SourceLocation> protocolLocs,
9480                SourceLocation rAngleLoc);
9481 
9482   /// Build a specialized and/or protocol-qualified Objective-C type.
9483   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9484                Scope *S,
9485                SourceLocation Loc,
9486                ParsedType BaseType,
9487                SourceLocation TypeArgsLAngleLoc,
9488                ArrayRef<ParsedType> TypeArgs,
9489                SourceLocation TypeArgsRAngleLoc,
9490                SourceLocation ProtocolLAngleLoc,
9491                ArrayRef<Decl *> Protocols,
9492                ArrayRef<SourceLocation> ProtocolLocs,
9493                SourceLocation ProtocolRAngleLoc);
9494 
9495   /// Build an Objective-C type parameter type.
9496   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9497                                   SourceLocation ProtocolLAngleLoc,
9498                                   ArrayRef<ObjCProtocolDecl *> Protocols,
9499                                   ArrayRef<SourceLocation> ProtocolLocs,
9500                                   SourceLocation ProtocolRAngleLoc,
9501                                   bool FailOnError = false);
9502 
9503   /// Build an Objective-C object pointer type.
9504   QualType BuildObjCObjectType(QualType BaseType,
9505                                SourceLocation Loc,
9506                                SourceLocation TypeArgsLAngleLoc,
9507                                ArrayRef<TypeSourceInfo *> TypeArgs,
9508                                SourceLocation TypeArgsRAngleLoc,
9509                                SourceLocation ProtocolLAngleLoc,
9510                                ArrayRef<ObjCProtocolDecl *> Protocols,
9511                                ArrayRef<SourceLocation> ProtocolLocs,
9512                                SourceLocation ProtocolRAngleLoc,
9513                                bool FailOnError = false);
9514 
9515   /// Ensure attributes are consistent with type.
9516   /// \param [in, out] Attributes The attributes to check; they will
9517   /// be modified to be consistent with \p PropertyTy.
9518   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9519                                    SourceLocation Loc,
9520                                    unsigned &Attributes,
9521                                    bool propertyInPrimaryClass);
9522 
9523   /// Process the specified property declaration and create decls for the
9524   /// setters and getters as needed.
9525   /// \param property The property declaration being processed
9526   void ProcessPropertyDecl(ObjCPropertyDecl *property);
9527 
9528 
9529   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9530                                 ObjCPropertyDecl *SuperProperty,
9531                                 const IdentifierInfo *Name,
9532                                 bool OverridingProtocolProperty);
9533 
9534   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9535                                         ObjCInterfaceDecl *ID);
9536 
9537   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9538                    ArrayRef<Decl *> allMethods = None,
9539                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
9540 
9541   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9542                       SourceLocation LParenLoc,
9543                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
9544                       Selector GetterSel, Selector SetterSel,
9545                       tok::ObjCKeywordKind MethodImplKind,
9546                       DeclContext *lexicalDC = nullptr);
9547 
9548   Decl *ActOnPropertyImplDecl(Scope *S,
9549                               SourceLocation AtLoc,
9550                               SourceLocation PropertyLoc,
9551                               bool ImplKind,
9552                               IdentifierInfo *PropertyId,
9553                               IdentifierInfo *PropertyIvar,
9554                               SourceLocation PropertyIvarLoc,
9555                               ObjCPropertyQueryKind QueryKind);
9556 
9557   enum ObjCSpecialMethodKind {
9558     OSMK_None,
9559     OSMK_Alloc,
9560     OSMK_New,
9561     OSMK_Copy,
9562     OSMK_RetainingInit,
9563     OSMK_NonRetainingInit
9564   };
9565 
9566   struct ObjCArgInfo {
9567     IdentifierInfo *Name;
9568     SourceLocation NameLoc;
9569     // The Type is null if no type was specified, and the DeclSpec is invalid
9570     // in this case.
9571     ParsedType Type;
9572     ObjCDeclSpec DeclSpec;
9573 
9574     /// ArgAttrs - Attribute list for this argument.
9575     ParsedAttributesView ArgAttrs;
9576   };
9577 
9578   Decl *ActOnMethodDeclaration(
9579       Scope *S,
9580       SourceLocation BeginLoc, // location of the + or -.
9581       SourceLocation EndLoc,   // location of the ; or {.
9582       tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9583       ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9584       // optional arguments. The number of types/arguments is obtained
9585       // from the Sel.getNumArgs().
9586       ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9587       unsigned CNumArgs, // c-style args
9588       const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9589       bool isVariadic, bool MethodDefinition);
9590 
9591   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9592                                               const ObjCObjectPointerType *OPT,
9593                                               bool IsInstance);
9594   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9595                                            bool IsInstance);
9596 
9597   bool CheckARCMethodDecl(ObjCMethodDecl *method);
9598   bool inferObjCARCLifetime(ValueDecl *decl);
9599 
9600   void deduceOpenCLAddressSpace(ValueDecl *decl);
9601 
9602   ExprResult
9603   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9604                             Expr *BaseExpr,
9605                             SourceLocation OpLoc,
9606                             DeclarationName MemberName,
9607                             SourceLocation MemberLoc,
9608                             SourceLocation SuperLoc, QualType SuperType,
9609                             bool Super);
9610 
9611   ExprResult
9612   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9613                             IdentifierInfo &propertyName,
9614                             SourceLocation receiverNameLoc,
9615                             SourceLocation propertyNameLoc);
9616 
9617   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9618 
9619   /// Describes the kind of message expression indicated by a message
9620   /// send that starts with an identifier.
9621   enum ObjCMessageKind {
9622     /// The message is sent to 'super'.
9623     ObjCSuperMessage,
9624     /// The message is an instance message.
9625     ObjCInstanceMessage,
9626     /// The message is a class message, and the identifier is a type
9627     /// name.
9628     ObjCClassMessage
9629   };
9630 
9631   ObjCMessageKind getObjCMessageKind(Scope *S,
9632                                      IdentifierInfo *Name,
9633                                      SourceLocation NameLoc,
9634                                      bool IsSuper,
9635                                      bool HasTrailingDot,
9636                                      ParsedType &ReceiverType);
9637 
9638   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
9639                                Selector Sel,
9640                                SourceLocation LBracLoc,
9641                                ArrayRef<SourceLocation> SelectorLocs,
9642                                SourceLocation RBracLoc,
9643                                MultiExprArg Args);
9644 
9645   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
9646                                QualType ReceiverType,
9647                                SourceLocation SuperLoc,
9648                                Selector Sel,
9649                                ObjCMethodDecl *Method,
9650                                SourceLocation LBracLoc,
9651                                ArrayRef<SourceLocation> SelectorLocs,
9652                                SourceLocation RBracLoc,
9653                                MultiExprArg Args,
9654                                bool isImplicit = false);
9655 
9656   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
9657                                        bool isSuperReceiver,
9658                                        SourceLocation Loc,
9659                                        Selector Sel,
9660                                        ObjCMethodDecl *Method,
9661                                        MultiExprArg Args);
9662 
9663   ExprResult ActOnClassMessage(Scope *S,
9664                                ParsedType Receiver,
9665                                Selector Sel,
9666                                SourceLocation LBracLoc,
9667                                ArrayRef<SourceLocation> SelectorLocs,
9668                                SourceLocation RBracLoc,
9669                                MultiExprArg Args);
9670 
9671   ExprResult BuildInstanceMessage(Expr *Receiver,
9672                                   QualType ReceiverType,
9673                                   SourceLocation SuperLoc,
9674                                   Selector Sel,
9675                                   ObjCMethodDecl *Method,
9676                                   SourceLocation LBracLoc,
9677                                   ArrayRef<SourceLocation> SelectorLocs,
9678                                   SourceLocation RBracLoc,
9679                                   MultiExprArg Args,
9680                                   bool isImplicit = false);
9681 
9682   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
9683                                           QualType ReceiverType,
9684                                           SourceLocation Loc,
9685                                           Selector Sel,
9686                                           ObjCMethodDecl *Method,
9687                                           MultiExprArg Args);
9688 
9689   ExprResult ActOnInstanceMessage(Scope *S,
9690                                   Expr *Receiver,
9691                                   Selector Sel,
9692                                   SourceLocation LBracLoc,
9693                                   ArrayRef<SourceLocation> SelectorLocs,
9694                                   SourceLocation RBracLoc,
9695                                   MultiExprArg Args);
9696 
9697   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
9698                                   ObjCBridgeCastKind Kind,
9699                                   SourceLocation BridgeKeywordLoc,
9700                                   TypeSourceInfo *TSInfo,
9701                                   Expr *SubExpr);
9702 
9703   ExprResult ActOnObjCBridgedCast(Scope *S,
9704                                   SourceLocation LParenLoc,
9705                                   ObjCBridgeCastKind Kind,
9706                                   SourceLocation BridgeKeywordLoc,
9707                                   ParsedType Type,
9708                                   SourceLocation RParenLoc,
9709                                   Expr *SubExpr);
9710 
9711   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
9712 
9713   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
9714 
9715   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
9716                                      CastKind &Kind);
9717 
9718   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
9719                                         QualType DestType, QualType SrcType,
9720                                         ObjCInterfaceDecl *&RelatedClass,
9721                                         ObjCMethodDecl *&ClassMethod,
9722                                         ObjCMethodDecl *&InstanceMethod,
9723                                         TypedefNameDecl *&TDNDecl,
9724                                         bool CfToNs, bool Diagnose = true);
9725 
9726   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
9727                                          QualType DestType, QualType SrcType,
9728                                          Expr *&SrcExpr, bool Diagnose = true);
9729 
9730   bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
9731                                     bool Diagnose = true);
9732 
9733   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
9734 
9735   /// Check whether the given new method is a valid override of the
9736   /// given overridden method, and set any properties that should be inherited.
9737   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
9738                                const ObjCMethodDecl *Overridden);
9739 
9740   /// Describes the compatibility of a result type with its method.
9741   enum ResultTypeCompatibilityKind {
9742     RTC_Compatible,
9743     RTC_Incompatible,
9744     RTC_Unknown
9745   };
9746 
9747   void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
9748                                       ObjCMethodDecl *overridden);
9749 
9750   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
9751                                 ObjCInterfaceDecl *CurrentClass,
9752                                 ResultTypeCompatibilityKind RTC);
9753 
9754   enum PragmaOptionsAlignKind {
9755     POAK_Native,  // #pragma options align=native
9756     POAK_Natural, // #pragma options align=natural
9757     POAK_Packed,  // #pragma options align=packed
9758     POAK_Power,   // #pragma options align=power
9759     POAK_Mac68k,  // #pragma options align=mac68k
9760     POAK_Reset    // #pragma options align=reset
9761   };
9762 
9763   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
9764   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
9765                                PragmaClangSectionAction Action,
9766                                PragmaClangSectionKind SecKind, StringRef SecName);
9767 
9768   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
9769   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
9770                                SourceLocation PragmaLoc);
9771 
9772   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
9773   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
9774                        StringRef SlotLabel, Expr *Alignment);
9775 
9776   enum class PragmaPackDiagnoseKind {
9777     NonDefaultStateAtInclude,
9778     ChangedStateAtExit
9779   };
9780 
9781   void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
9782                                     SourceLocation IncludeLoc);
9783   void DiagnoseUnterminatedPragmaPack();
9784 
9785   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
9786   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
9787 
9788   /// ActOnPragmaMSComment - Called on well formed
9789   /// \#pragma comment(kind, "arg").
9790   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
9791                             StringRef Arg);
9792 
9793   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
9794   /// pointers_to_members(representation method[, general purpose
9795   /// representation]).
9796   void ActOnPragmaMSPointersToMembers(
9797       LangOptions::PragmaMSPointersToMembersKind Kind,
9798       SourceLocation PragmaLoc);
9799 
9800   /// Called on well formed \#pragma vtordisp().
9801   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
9802                              SourceLocation PragmaLoc,
9803                              MSVtorDispMode Value);
9804 
9805   enum PragmaSectionKind {
9806     PSK_DataSeg,
9807     PSK_BSSSeg,
9808     PSK_ConstSeg,
9809     PSK_CodeSeg,
9810   };
9811 
9812   bool UnifySection(StringRef SectionName,
9813                     int SectionFlags,
9814                     DeclaratorDecl *TheDecl);
9815   bool UnifySection(StringRef SectionName,
9816                     int SectionFlags,
9817                     SourceLocation PragmaSectionLocation);
9818 
9819   /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
9820   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
9821                         PragmaMsStackAction Action,
9822                         llvm::StringRef StackSlotLabel,
9823                         StringLiteral *SegmentName,
9824                         llvm::StringRef PragmaName);
9825 
9826   /// Called on well formed \#pragma section().
9827   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
9828                             int SectionFlags, StringLiteral *SegmentName);
9829 
9830   /// Called on well-formed \#pragma init_seg().
9831   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
9832                             StringLiteral *SegmentName);
9833 
9834   /// Called on #pragma clang __debug dump II
9835   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9836 
9837   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
9838   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
9839                                  StringRef Value);
9840 
9841   /// Are precise floating point semantics currently enabled?
isPreciseFPEnabled()9842   bool isPreciseFPEnabled() {
9843     return !CurFPFeatures.getAllowFPReassociate() &&
9844            !CurFPFeatures.getNoSignedZero() &&
9845            !CurFPFeatures.getAllowReciprocal() &&
9846            !CurFPFeatures.getAllowApproxFunc();
9847   }
9848 
9849   /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
9850   void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
9851                                PragmaFloatControlKind Value);
9852 
9853   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
9854   void ActOnPragmaUnused(const Token &Identifier,
9855                          Scope *curScope,
9856                          SourceLocation PragmaLoc);
9857 
9858   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
9859   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
9860                              SourceLocation PragmaLoc);
9861 
9862   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
9863                                  SourceLocation Loc);
9864   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
9865 
9866   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
9867   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
9868                          SourceLocation PragmaLoc,
9869                          SourceLocation WeakNameLoc);
9870 
9871   /// ActOnPragmaRedefineExtname - Called on well formed
9872   /// \#pragma redefine_extname oldname newname.
9873   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
9874                                   IdentifierInfo* AliasName,
9875                                   SourceLocation PragmaLoc,
9876                                   SourceLocation WeakNameLoc,
9877                                   SourceLocation AliasNameLoc);
9878 
9879   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
9880   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
9881                             IdentifierInfo* AliasName,
9882                             SourceLocation PragmaLoc,
9883                             SourceLocation WeakNameLoc,
9884                             SourceLocation AliasNameLoc);
9885 
9886   /// ActOnPragmaFPContract - Called on well formed
9887   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
9888   /// \#pragma clang fp contract
9889   void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
9890 
9891   /// Called on well formed
9892   /// \#pragma clang fp reassociate
9893   void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
9894 
9895   /// ActOnPragmaFenvAccess - Called on well formed
9896   /// \#pragma STDC FENV_ACCESS
9897   void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
9898 
9899   /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
9900   void ActOnPragmaFPExceptions(SourceLocation Loc,
9901                                LangOptions::FPExceptionModeKind);
9902 
9903   /// Called to set constant rounding mode for floating point operations.
9904   void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
9905 
9906   /// Called to set exception behavior for floating point operations.
9907   void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
9908 
9909   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
9910   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
9911   void AddAlignmentAttributesForRecord(RecordDecl *RD);
9912 
9913   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
9914   void AddMsStructLayoutForRecord(RecordDecl *RD);
9915 
9916   /// FreePackedContext - Deallocate and null out PackContext.
9917   void FreePackedContext();
9918 
9919   /// PushNamespaceVisibilityAttr - Note that we've entered a
9920   /// namespace with a visibility attribute.
9921   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
9922                                    SourceLocation Loc);
9923 
9924   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
9925   /// add an appropriate visibility attribute.
9926   void AddPushedVisibilityAttribute(Decl *RD);
9927 
9928   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
9929   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
9930   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
9931 
9932   /// FreeVisContext - Deallocate and null out VisContext.
9933   void FreeVisContext();
9934 
9935   /// AddCFAuditedAttribute - Check whether we're currently within
9936   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
9937   /// the appropriate attribute.
9938   void AddCFAuditedAttribute(Decl *D);
9939 
9940   void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
9941                                      SourceLocation PragmaLoc,
9942                                      attr::ParsedSubjectMatchRuleSet Rules);
9943   void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
9944                                      const IdentifierInfo *Namespace);
9945 
9946   /// Called on well-formed '\#pragma clang attribute pop'.
9947   void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
9948                                const IdentifierInfo *Namespace);
9949 
9950   /// Adds the attributes that have been specified using the
9951   /// '\#pragma clang attribute push' directives to the given declaration.
9952   void AddPragmaAttributes(Scope *S, Decl *D);
9953 
9954   void DiagnoseUnterminatedPragmaAttribute();
9955 
9956   /// Called on well formed \#pragma clang optimize.
9957   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
9958 
9959   /// Get the location for the currently active "\#pragma clang optimize
9960   /// off". If this location is invalid, then the state of the pragma is "on".
getOptimizeOffPragmaLocation()9961   SourceLocation getOptimizeOffPragmaLocation() const {
9962     return OptimizeOffPragmaLocation;
9963   }
9964 
9965   /// Only called on function definitions; if there is a pragma in scope
9966   /// with the effect of a range-based optnone, consider marking the function
9967   /// with attribute optnone.
9968   void AddRangeBasedOptnone(FunctionDecl *FD);
9969 
9970   /// Adds the 'optnone' attribute to the function declaration if there
9971   /// are no conflicts; Loc represents the location causing the 'optnone'
9972   /// attribute to be added (usually because of a pragma).
9973   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
9974 
9975   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
9976   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9977                       bool IsPackExpansion);
9978   void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
9979                       bool IsPackExpansion);
9980 
9981   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
9982   /// declaration.
9983   void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
9984                             Expr *OE);
9985 
9986   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
9987   /// declaration.
9988   void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
9989                          Expr *ParamExpr);
9990 
9991   /// AddAlignValueAttr - Adds an align_value attribute to a particular
9992   /// declaration.
9993   void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
9994 
9995   /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
9996   void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
9997                          StringRef Annot, MutableArrayRef<Expr *> Args);
9998 
9999   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10000   /// declaration.
10001   void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10002                            Expr *MaxThreads, Expr *MinBlocks);
10003 
10004   /// AddModeAttr - Adds a mode attribute to a particular declaration.
10005   void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10006                    bool InInstantiation = false);
10007 
10008   void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10009                            ParameterABI ABI);
10010 
10011   enum class RetainOwnershipKind {NS, CF, OS};
10012   void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10013                         RetainOwnershipKind K, bool IsTemplateInstantiation);
10014 
10015   /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10016   /// attribute to a particular declaration.
10017   void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10018                                       Expr *Min, Expr *Max);
10019 
10020   /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10021   /// particular declaration.
10022   void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10023                                Expr *Min, Expr *Max);
10024 
10025   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10026 
10027   //===--------------------------------------------------------------------===//
10028   // C++ Coroutines TS
10029   //
10030   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10031                                StringRef Keyword);
10032   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10033   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10034   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10035 
10036   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10037                                       bool IsImplicit = false);
10038   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10039                                         UnresolvedLookupExpr* Lookup);
10040   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10041   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10042                                bool IsImplicit = false);
10043   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10044   bool buildCoroutineParameterMoves(SourceLocation Loc);
10045   VarDecl *buildCoroutinePromise(SourceLocation Loc);
10046   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10047   ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10048                                            SourceLocation FuncLoc);
10049   /// Check that the expression co_await promise.final_suspend() shall not be
10050   /// potentially-throwing.
10051   bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10052 
10053   //===--------------------------------------------------------------------===//
10054   // OpenCL extensions.
10055   //
10056 private:
10057   std::string CurrOpenCLExtension;
10058   /// Extensions required by an OpenCL type.
10059   llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
10060   /// Extensions required by an OpenCL declaration.
10061   llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
10062 public:
getCurrentOpenCLExtension()10063   llvm::StringRef getCurrentOpenCLExtension() const {
10064     return CurrOpenCLExtension;
10065   }
10066 
10067   /// Check if a function declaration \p FD associates with any
10068   /// extensions present in OpenCLDeclExtMap and if so return the
10069   /// extension(s) name(s).
10070   std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
10071 
10072   /// Check if a function type \p FT associates with any
10073   /// extensions present in OpenCLTypeExtMap and if so return the
10074   /// extension(s) name(s).
10075   std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
10076 
10077   /// Find an extension in an appropriate extension map and return its name
10078   template<typename T, typename MapT>
10079   std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
10080 
setCurrentOpenCLExtension(llvm::StringRef Ext)10081   void setCurrentOpenCLExtension(llvm::StringRef Ext) {
10082     CurrOpenCLExtension = std::string(Ext);
10083   }
10084 
10085   /// Set OpenCL extensions for a type which can only be used when these
10086   /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
10087   /// \param Exts A space separated list of OpenCL extensions.
10088   void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
10089 
10090   /// Set OpenCL extensions for a declaration which can only be
10091   /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
10092   /// nothing.
10093   /// \param Exts A space separated list of OpenCL extensions.
10094   void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
10095 
10096   /// Set current OpenCL extensions for a type which can only be used
10097   /// when these OpenCL extensions are enabled. If current OpenCL extension is
10098   /// empty, do nothing.
10099   void setCurrentOpenCLExtensionForType(QualType T);
10100 
10101   /// Set current OpenCL extensions for a declaration which
10102   /// can only be used when these OpenCL extensions are enabled. If current
10103   /// OpenCL extension is empty, do nothing.
10104   void setCurrentOpenCLExtensionForDecl(Decl *FD);
10105 
10106   bool isOpenCLDisabledDecl(Decl *FD);
10107 
10108   /// Check if type \p T corresponding to declaration specifier \p DS
10109   /// is disabled due to required OpenCL extensions being disabled. If so,
10110   /// emit diagnostics.
10111   /// \return true if type is disabled.
10112   bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
10113 
10114   /// Check if declaration \p D used by expression \p E
10115   /// is disabled due to required OpenCL extensions being disabled. If so,
10116   /// emit diagnostics.
10117   /// \return true if type is disabled.
10118   bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
10119 
10120   //===--------------------------------------------------------------------===//
10121   // OpenMP directives and clauses.
10122   //
10123 private:
10124   void *VarDataSharingAttributesStack;
10125   /// Number of nested '#pragma omp declare target' directives.
10126   SmallVector<SourceLocation, 4> DeclareTargetNesting;
10127   /// Initialization of data-sharing attributes stack.
10128   void InitDataSharingAttributesStack();
10129   void DestroyDataSharingAttributesStack();
10130   ExprResult
10131   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10132                                         bool StrictlyPositive = true);
10133   /// Returns OpenMP nesting level for current directive.
10134   unsigned getOpenMPNestingLevel() const;
10135 
10136   /// Adjusts the function scopes index for the target-based regions.
10137   void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10138                                     unsigned Level) const;
10139 
10140   /// Returns the number of scopes associated with the construct on the given
10141   /// OpenMP level.
10142   int getNumberOfConstructScopes(unsigned Level) const;
10143 
10144   /// Push new OpenMP function region for non-capturing function.
10145   void pushOpenMPFunctionRegion();
10146 
10147   /// Pop OpenMP function region for non-capturing function.
10148   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10149 
10150   /// Checks if a type or a declaration is disabled due to the owning extension
10151   /// being disabled, and emits diagnostic messages if it is disabled.
10152   /// \param D type or declaration to be checked.
10153   /// \param DiagLoc source location for the diagnostic message.
10154   /// \param DiagInfo information to be emitted for the diagnostic message.
10155   /// \param SrcRange source range of the declaration.
10156   /// \param Map maps type or declaration to the extensions.
10157   /// \param Selector selects diagnostic message: 0 for type and 1 for
10158   ///        declaration.
10159   /// \return true if the type or declaration is disabled.
10160   template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
10161   bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
10162                                      MapT &Map, unsigned Selector = 0,
10163                                      SourceRange SrcRange = SourceRange());
10164 
10165   /// Helper to keep information about the current `omp begin/end declare
10166   /// variant` nesting.
10167   struct OMPDeclareVariantScope {
10168     /// The associated OpenMP context selector.
10169     OMPTraitInfo *TI;
10170 
10171     /// The associated OpenMP context selector mangling.
10172     std::string NameSuffix;
10173 
10174     OMPDeclareVariantScope(OMPTraitInfo &TI);
10175   };
10176 
10177   /// Return the OMPTraitInfo for the surrounding scope, if any.
getOMPTraitInfoForSurroundingScope()10178   OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10179     return OMPDeclareVariantScopes.empty() ? nullptr
10180                                            : OMPDeclareVariantScopes.back().TI;
10181   }
10182 
10183   /// The current `omp begin/end declare variant` scopes.
10184   SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10185 
10186   /// The declarator \p D defines a function in the scope \p S which is nested
10187   /// in an `omp begin/end declare variant` scope. In this method we create a
10188   /// declaration for \p D and rename \p D according to the OpenMP context
10189   /// selector of the surrounding scope. Return all base functions in \p Bases.
10190   void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10191       Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10192       SmallVectorImpl<FunctionDecl *> &Bases);
10193 
10194   /// Register \p D as specialization of all base functions in \p Bases in the
10195   /// current `omp begin/end declare variant` scope.
10196   void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10197       Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10198 
10199 public:
10200 
10201   /// Can we exit a scope at the moment.
isInOpenMPDeclareVariantScope()10202   bool isInOpenMPDeclareVariantScope() {
10203     return !OMPDeclareVariantScopes.empty();
10204   }
10205 
10206   /// Given the potential call expression \p Call, determine if there is a
10207   /// specialization via the OpenMP declare variant mechanism available. If
10208   /// there is, return the specialized call expression, otherwise return the
10209   /// original \p Call.
10210   ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10211                              SourceLocation LParenLoc, MultiExprArg ArgExprs,
10212                              SourceLocation RParenLoc, Expr *ExecConfig);
10213 
10214   /// Handle a `omp begin declare variant`.
10215   void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10216 
10217   /// Handle a `omp end declare variant`.
10218   void ActOnOpenMPEndDeclareVariant();
10219 
10220   /// Checks if the variant/multiversion functions are compatible.
10221   bool areMultiversionVariantFunctionsCompatible(
10222       const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10223       const PartialDiagnostic &NoProtoDiagID,
10224       const PartialDiagnosticAt &NoteCausedDiagIDAt,
10225       const PartialDiagnosticAt &NoSupportDiagIDAt,
10226       const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10227       bool ConstexprSupported, bool CLinkageMayDiffer);
10228 
10229   /// Function tries to capture lambda's captured variables in the OpenMP region
10230   /// before the original lambda is captured.
10231   void tryCaptureOpenMPLambdas(ValueDecl *V);
10232 
10233   /// Return true if the provided declaration \a VD should be captured by
10234   /// reference.
10235   /// \param Level Relative level of nested OpenMP construct for that the check
10236   /// is performed.
10237   /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10238   bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10239                              unsigned OpenMPCaptureLevel) const;
10240 
10241   /// Check if the specified variable is used in one of the private
10242   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10243   /// constructs.
10244   VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10245                                 unsigned StopAt = 0);
10246   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10247                                    ExprObjectKind OK, SourceLocation Loc);
10248 
10249   /// If the current region is a loop-based region, mark the start of the loop
10250   /// construct.
10251   void startOpenMPLoop();
10252 
10253   /// If the current region is a range loop-based region, mark the start of the
10254   /// loop construct.
10255   void startOpenMPCXXRangeFor();
10256 
10257   /// Check if the specified variable is used in 'private' clause.
10258   /// \param Level Relative level of nested OpenMP construct for that the check
10259   /// is performed.
10260   OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10261                                        unsigned CapLevel) const;
10262 
10263   /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10264   /// for \p FD based on DSA for the provided corresponding captured declaration
10265   /// \p D.
10266   void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10267 
10268   /// Check if the specified variable is captured  by 'target' directive.
10269   /// \param Level Relative level of nested OpenMP construct for that the check
10270   /// is performed.
10271   bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10272                                   unsigned CaptureLevel) const;
10273 
10274   /// Check if the specified global variable must be captured  by outer capture
10275   /// regions.
10276   /// \param Level Relative level of nested OpenMP construct for that
10277   /// the check is performed.
10278   bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10279                                   unsigned CaptureLevel) const;
10280 
10281   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10282                                                     Expr *Op);
10283   /// Called on start of new data sharing attribute block.
10284   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10285                            const DeclarationNameInfo &DirName, Scope *CurScope,
10286                            SourceLocation Loc);
10287   /// Start analysis of clauses.
10288   void StartOpenMPClause(OpenMPClauseKind K);
10289   /// End analysis of clauses.
10290   void EndOpenMPClause();
10291   /// Called on end of data sharing attribute block.
10292   void EndOpenMPDSABlock(Stmt *CurDirective);
10293 
10294   /// Check if the current region is an OpenMP loop region and if it is,
10295   /// mark loop control variable, used in \p Init for loop initialization, as
10296   /// private by default.
10297   /// \param Init First part of the for loop.
10298   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10299 
10300   // OpenMP directives and clauses.
10301   /// Called on correct id-expression from the '#pragma omp
10302   /// threadprivate'.
10303   ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10304                                      const DeclarationNameInfo &Id,
10305                                      OpenMPDirectiveKind Kind);
10306   /// Called on well-formed '#pragma omp threadprivate'.
10307   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10308                                      SourceLocation Loc,
10309                                      ArrayRef<Expr *> VarList);
10310   /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10311   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10312                                                   ArrayRef<Expr *> VarList);
10313   /// Called on well-formed '#pragma omp allocate'.
10314   DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10315                                               ArrayRef<Expr *> VarList,
10316                                               ArrayRef<OMPClause *> Clauses,
10317                                               DeclContext *Owner = nullptr);
10318   /// Called on well-formed '#pragma omp requires'.
10319   DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10320                                               ArrayRef<OMPClause *> ClauseList);
10321   /// Check restrictions on Requires directive
10322   OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10323                                         ArrayRef<OMPClause *> Clauses);
10324   /// Check if the specified type is allowed to be used in 'omp declare
10325   /// reduction' construct.
10326   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10327                                            TypeResult ParsedType);
10328   /// Called on start of '#pragma omp declare reduction'.
10329   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10330       Scope *S, DeclContext *DC, DeclarationName Name,
10331       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10332       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10333   /// Initialize declare reduction construct initializer.
10334   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10335   /// Finish current declare reduction construct initializer.
10336   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10337   /// Initialize declare reduction construct initializer.
10338   /// \return omp_priv variable.
10339   VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10340   /// Finish current declare reduction construct initializer.
10341   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10342                                                  VarDecl *OmpPrivParm);
10343   /// Called at the end of '#pragma omp declare reduction'.
10344   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10345       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10346 
10347   /// Check variable declaration in 'omp declare mapper' construct.
10348   TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10349   /// Check if the specified type is allowed to be used in 'omp declare
10350   /// mapper' construct.
10351   QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10352                                         TypeResult ParsedType);
10353   /// Called on start of '#pragma omp declare mapper'.
10354   DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10355       Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10356       SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10357       Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10358       Decl *PrevDeclInScope = nullptr);
10359   /// Build the mapper variable of '#pragma omp declare mapper'.
10360   ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10361                                                       QualType MapperType,
10362                                                       SourceLocation StartLoc,
10363                                                       DeclarationName VN);
10364   bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10365   const ValueDecl *getOpenMPDeclareMapperVarName() const;
10366 
10367   /// Called on the start of target region i.e. '#pragma omp declare target'.
10368   bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
10369   /// Called at the end of target region i.e. '#pragme omp end declare target'.
10370   void ActOnFinishOpenMPDeclareTargetDirective();
10371   /// Searches for the provided declaration name for OpenMP declare target
10372   /// directive.
10373   NamedDecl *
10374   lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10375                                 const DeclarationNameInfo &Id,
10376                                 NamedDeclSetType &SameDirectiveDecls);
10377   /// Called on correct id-expression from the '#pragma omp declare target'.
10378   void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10379                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
10380                                     OMPDeclareTargetDeclAttr::DevTypeTy DT);
10381   /// Check declaration inside target region.
10382   void
10383   checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10384                                    SourceLocation IdLoc = SourceLocation());
10385   /// Finishes analysis of the deferred functions calls that may be declared as
10386   /// host/nohost during device/host compilation.
10387   void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10388                                      const FunctionDecl *Callee,
10389                                      SourceLocation Loc);
10390   /// Return true inside OpenMP declare target region.
isInOpenMPDeclareTargetContext()10391   bool isInOpenMPDeclareTargetContext() const {
10392     return !DeclareTargetNesting.empty();
10393   }
10394   /// Return true inside OpenMP target region.
10395   bool isInOpenMPTargetExecutionDirective() const;
10396 
10397   /// Return the number of captured regions created for an OpenMP directive.
10398   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10399 
10400   /// Initialization of captured region for OpenMP region.
10401   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10402   /// End of OpenMP region.
10403   ///
10404   /// \param S Statement associated with the current OpenMP region.
10405   /// \param Clauses List of clauses for the current OpenMP region.
10406   ///
10407   /// \returns Statement for finished OpenMP region.
10408   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10409   StmtResult ActOnOpenMPExecutableDirective(
10410       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10411       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10412       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10413   /// Called on well-formed '\#pragma omp parallel' after parsing
10414   /// of the  associated statement.
10415   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10416                                           Stmt *AStmt,
10417                                           SourceLocation StartLoc,
10418                                           SourceLocation EndLoc);
10419   using VarsWithInheritedDSAType =
10420       llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10421   /// Called on well-formed '\#pragma omp simd' after parsing
10422   /// of the associated statement.
10423   StmtResult
10424   ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10425                            SourceLocation StartLoc, SourceLocation EndLoc,
10426                            VarsWithInheritedDSAType &VarsWithImplicitDSA);
10427   /// Called on well-formed '\#pragma omp for' after parsing
10428   /// of the associated statement.
10429   StmtResult
10430   ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10431                           SourceLocation StartLoc, SourceLocation EndLoc,
10432                           VarsWithInheritedDSAType &VarsWithImplicitDSA);
10433   /// Called on well-formed '\#pragma omp for simd' after parsing
10434   /// of the associated statement.
10435   StmtResult
10436   ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10437                               SourceLocation StartLoc, SourceLocation EndLoc,
10438                               VarsWithInheritedDSAType &VarsWithImplicitDSA);
10439   /// Called on well-formed '\#pragma omp sections' after parsing
10440   /// of the associated statement.
10441   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10442                                           Stmt *AStmt, SourceLocation StartLoc,
10443                                           SourceLocation EndLoc);
10444   /// Called on well-formed '\#pragma omp section' after parsing of the
10445   /// associated statement.
10446   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10447                                          SourceLocation EndLoc);
10448   /// Called on well-formed '\#pragma omp single' after parsing of the
10449   /// associated statement.
10450   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10451                                         Stmt *AStmt, SourceLocation StartLoc,
10452                                         SourceLocation EndLoc);
10453   /// Called on well-formed '\#pragma omp master' after parsing of the
10454   /// associated statement.
10455   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10456                                         SourceLocation EndLoc);
10457   /// Called on well-formed '\#pragma omp critical' after parsing of the
10458   /// associated statement.
10459   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10460                                           ArrayRef<OMPClause *> Clauses,
10461                                           Stmt *AStmt, SourceLocation StartLoc,
10462                                           SourceLocation EndLoc);
10463   /// Called on well-formed '\#pragma omp parallel for' after parsing
10464   /// of the  associated statement.
10465   StmtResult ActOnOpenMPParallelForDirective(
10466       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10467       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10468   /// Called on well-formed '\#pragma omp parallel for simd' after
10469   /// parsing of the  associated statement.
10470   StmtResult ActOnOpenMPParallelForSimdDirective(
10471       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10472       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10473   /// Called on well-formed '\#pragma omp parallel master' after
10474   /// parsing of the  associated statement.
10475   StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10476                                                 Stmt *AStmt,
10477                                                 SourceLocation StartLoc,
10478                                                 SourceLocation EndLoc);
10479   /// Called on well-formed '\#pragma omp parallel sections' after
10480   /// parsing of the  associated statement.
10481   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10482                                                   Stmt *AStmt,
10483                                                   SourceLocation StartLoc,
10484                                                   SourceLocation EndLoc);
10485   /// Called on well-formed '\#pragma omp task' after parsing of the
10486   /// associated statement.
10487   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10488                                       Stmt *AStmt, SourceLocation StartLoc,
10489                                       SourceLocation EndLoc);
10490   /// Called on well-formed '\#pragma omp taskyield'.
10491   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10492                                            SourceLocation EndLoc);
10493   /// Called on well-formed '\#pragma omp barrier'.
10494   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10495                                          SourceLocation EndLoc);
10496   /// Called on well-formed '\#pragma omp taskwait'.
10497   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
10498                                           SourceLocation EndLoc);
10499   /// Called on well-formed '\#pragma omp taskgroup'.
10500   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10501                                            Stmt *AStmt, SourceLocation StartLoc,
10502                                            SourceLocation EndLoc);
10503   /// Called on well-formed '\#pragma omp flush'.
10504   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10505                                        SourceLocation StartLoc,
10506                                        SourceLocation EndLoc);
10507   /// Called on well-formed '\#pragma omp depobj'.
10508   StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10509                                         SourceLocation StartLoc,
10510                                         SourceLocation EndLoc);
10511   /// Called on well-formed '\#pragma omp scan'.
10512   StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10513                                       SourceLocation StartLoc,
10514                                       SourceLocation EndLoc);
10515   /// Called on well-formed '\#pragma omp ordered' after parsing of the
10516   /// associated statement.
10517   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10518                                          Stmt *AStmt, SourceLocation StartLoc,
10519                                          SourceLocation EndLoc);
10520   /// Called on well-formed '\#pragma omp atomic' after parsing of the
10521   /// associated statement.
10522   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10523                                         Stmt *AStmt, SourceLocation StartLoc,
10524                                         SourceLocation EndLoc);
10525   /// Called on well-formed '\#pragma omp target' after parsing of the
10526   /// associated statement.
10527   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10528                                         Stmt *AStmt, SourceLocation StartLoc,
10529                                         SourceLocation EndLoc);
10530   /// Called on well-formed '\#pragma omp target data' after parsing of
10531   /// the associated statement.
10532   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10533                                             Stmt *AStmt, SourceLocation StartLoc,
10534                                             SourceLocation EndLoc);
10535   /// Called on well-formed '\#pragma omp target enter data' after
10536   /// parsing of the associated statement.
10537   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10538                                                  SourceLocation StartLoc,
10539                                                  SourceLocation EndLoc,
10540                                                  Stmt *AStmt);
10541   /// Called on well-formed '\#pragma omp target exit data' after
10542   /// parsing of the associated statement.
10543   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10544                                                 SourceLocation StartLoc,
10545                                                 SourceLocation EndLoc,
10546                                                 Stmt *AStmt);
10547   /// Called on well-formed '\#pragma omp target parallel' after
10548   /// parsing of the associated statement.
10549   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10550                                                 Stmt *AStmt,
10551                                                 SourceLocation StartLoc,
10552                                                 SourceLocation EndLoc);
10553   /// Called on well-formed '\#pragma omp target parallel for' after
10554   /// parsing of the  associated statement.
10555   StmtResult ActOnOpenMPTargetParallelForDirective(
10556       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10557       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10558   /// Called on well-formed '\#pragma omp teams' after parsing of the
10559   /// associated statement.
10560   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10561                                        Stmt *AStmt, SourceLocation StartLoc,
10562                                        SourceLocation EndLoc);
10563   /// Called on well-formed '\#pragma omp cancellation point'.
10564   StmtResult
10565   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10566                                         SourceLocation EndLoc,
10567                                         OpenMPDirectiveKind CancelRegion);
10568   /// Called on well-formed '\#pragma omp cancel'.
10569   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10570                                         SourceLocation StartLoc,
10571                                         SourceLocation EndLoc,
10572                                         OpenMPDirectiveKind CancelRegion);
10573   /// Called on well-formed '\#pragma omp taskloop' after parsing of the
10574   /// associated statement.
10575   StmtResult
10576   ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10577                                SourceLocation StartLoc, SourceLocation EndLoc,
10578                                VarsWithInheritedDSAType &VarsWithImplicitDSA);
10579   /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
10580   /// the associated statement.
10581   StmtResult ActOnOpenMPTaskLoopSimdDirective(
10582       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10583       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10584   /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
10585   /// associated statement.
10586   StmtResult ActOnOpenMPMasterTaskLoopDirective(
10587       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10588       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10589   /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
10590   /// the associated statement.
10591   StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
10592       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10593       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10594   /// Called on well-formed '\#pragma omp parallel master taskloop' after
10595   /// parsing of the associated statement.
10596   StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
10597       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10598       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10599   /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
10600   /// parsing of the associated statement.
10601   StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10602       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10603       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10604   /// Called on well-formed '\#pragma omp distribute' after parsing
10605   /// of the associated statement.
10606   StmtResult
10607   ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10608                                  SourceLocation StartLoc, SourceLocation EndLoc,
10609                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10610   /// Called on well-formed '\#pragma omp target update'.
10611   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
10612                                               SourceLocation StartLoc,
10613                                               SourceLocation EndLoc,
10614                                               Stmt *AStmt);
10615   /// Called on well-formed '\#pragma omp distribute parallel for' after
10616   /// parsing of the associated statement.
10617   StmtResult ActOnOpenMPDistributeParallelForDirective(
10618       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10619       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10620   /// Called on well-formed '\#pragma omp distribute parallel for simd'
10621   /// after parsing of the associated statement.
10622   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
10623       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10624       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10625   /// Called on well-formed '\#pragma omp distribute simd' after
10626   /// parsing of the associated statement.
10627   StmtResult ActOnOpenMPDistributeSimdDirective(
10628       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10629       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10630   /// Called on well-formed '\#pragma omp target parallel for simd' after
10631   /// parsing of the associated statement.
10632   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
10633       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10634       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10635   /// Called on well-formed '\#pragma omp target simd' after parsing of
10636   /// the associated statement.
10637   StmtResult
10638   ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10639                                  SourceLocation StartLoc, SourceLocation EndLoc,
10640                                  VarsWithInheritedDSAType &VarsWithImplicitDSA);
10641   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
10642   /// the associated statement.
10643   StmtResult ActOnOpenMPTeamsDistributeDirective(
10644       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10645       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10646   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
10647   /// of the associated statement.
10648   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
10649       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10650       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10651   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
10652   /// after parsing of the associated statement.
10653   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10654       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10655       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10656   /// Called on well-formed '\#pragma omp teams distribute parallel for'
10657   /// after parsing of the associated statement.
10658   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
10659       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10660       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10661   /// Called on well-formed '\#pragma omp target teams' after parsing of the
10662   /// associated statement.
10663   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10664                                              Stmt *AStmt,
10665                                              SourceLocation StartLoc,
10666                                              SourceLocation EndLoc);
10667   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
10668   /// of the associated statement.
10669   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
10670       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10671       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10672   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
10673   /// after parsing of the associated statement.
10674   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10675       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10676       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10677   /// Called on well-formed '\#pragma omp target teams distribute parallel for
10678   /// simd' after parsing of the associated statement.
10679   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10680       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10681       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10682   /// Called on well-formed '\#pragma omp target teams distribute simd' after
10683   /// parsing of the associated statement.
10684   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
10685       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10686       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10687 
10688   /// Checks correctness of linear modifiers.
10689   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10690                                  SourceLocation LinLoc);
10691   /// Checks that the specified declaration matches requirements for the linear
10692   /// decls.
10693   bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
10694                              OpenMPLinearClauseKind LinKind, QualType Type,
10695                              bool IsDeclareSimd = false);
10696 
10697   /// Called on well-formed '\#pragma omp declare simd' after parsing of
10698   /// the associated method/function.
10699   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
10700       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
10701       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
10702       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
10703       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
10704 
10705   /// Checks '\#pragma omp declare variant' variant function and original
10706   /// functions after parsing of the associated method/function.
10707   /// \param DG Function declaration to which declare variant directive is
10708   /// applied to.
10709   /// \param VariantRef Expression that references the variant function, which
10710   /// must be used instead of the original one, specified in \p DG.
10711   /// \param TI The trait info object representing the match clause.
10712   /// \returns None, if the function/variant function are not compatible with
10713   /// the pragma, pair of original function/variant ref expression otherwise.
10714   Optional<std::pair<FunctionDecl *, Expr *>>
10715   checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
10716                                     OMPTraitInfo &TI, SourceRange SR);
10717 
10718   /// Called on well-formed '\#pragma omp declare variant' after parsing of
10719   /// the associated method/function.
10720   /// \param FD Function declaration to which declare variant directive is
10721   /// applied to.
10722   /// \param VariantRef Expression that references the variant function, which
10723   /// must be used instead of the original one, specified in \p DG.
10724   /// \param TI The context traits associated with the function variant.
10725   void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
10726                                           OMPTraitInfo &TI, SourceRange SR);
10727 
10728   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
10729                                          Expr *Expr,
10730                                          SourceLocation StartLoc,
10731                                          SourceLocation LParenLoc,
10732                                          SourceLocation EndLoc);
10733   /// Called on well-formed 'allocator' clause.
10734   OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
10735                                         SourceLocation StartLoc,
10736                                         SourceLocation LParenLoc,
10737                                         SourceLocation EndLoc);
10738   /// Called on well-formed 'if' clause.
10739   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10740                                  Expr *Condition, SourceLocation StartLoc,
10741                                  SourceLocation LParenLoc,
10742                                  SourceLocation NameModifierLoc,
10743                                  SourceLocation ColonLoc,
10744                                  SourceLocation EndLoc);
10745   /// Called on well-formed 'final' clause.
10746   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
10747                                     SourceLocation LParenLoc,
10748                                     SourceLocation EndLoc);
10749   /// Called on well-formed 'num_threads' clause.
10750   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10751                                          SourceLocation StartLoc,
10752                                          SourceLocation LParenLoc,
10753                                          SourceLocation EndLoc);
10754   /// Called on well-formed 'safelen' clause.
10755   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
10756                                       SourceLocation StartLoc,
10757                                       SourceLocation LParenLoc,
10758                                       SourceLocation EndLoc);
10759   /// Called on well-formed 'simdlen' clause.
10760   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
10761                                       SourceLocation LParenLoc,
10762                                       SourceLocation EndLoc);
10763   /// Called on well-formed 'collapse' clause.
10764   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
10765                                        SourceLocation StartLoc,
10766                                        SourceLocation LParenLoc,
10767                                        SourceLocation EndLoc);
10768   /// Called on well-formed 'ordered' clause.
10769   OMPClause *
10770   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
10771                            SourceLocation LParenLoc = SourceLocation(),
10772                            Expr *NumForLoops = nullptr);
10773   /// Called on well-formed 'grainsize' clause.
10774   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
10775                                         SourceLocation LParenLoc,
10776                                         SourceLocation EndLoc);
10777   /// Called on well-formed 'num_tasks' clause.
10778   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
10779                                        SourceLocation LParenLoc,
10780                                        SourceLocation EndLoc);
10781   /// Called on well-formed 'hint' clause.
10782   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10783                                    SourceLocation LParenLoc,
10784                                    SourceLocation EndLoc);
10785   /// Called on well-formed 'detach' clause.
10786   OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
10787                                      SourceLocation LParenLoc,
10788                                      SourceLocation EndLoc);
10789 
10790   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
10791                                      unsigned Argument,
10792                                      SourceLocation ArgumentLoc,
10793                                      SourceLocation StartLoc,
10794                                      SourceLocation LParenLoc,
10795                                      SourceLocation EndLoc);
10796   /// Called on well-formed 'default' clause.
10797   OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
10798                                       SourceLocation KindLoc,
10799                                       SourceLocation StartLoc,
10800                                       SourceLocation LParenLoc,
10801                                       SourceLocation EndLoc);
10802   /// Called on well-formed 'proc_bind' clause.
10803   OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
10804                                        SourceLocation KindLoc,
10805                                        SourceLocation StartLoc,
10806                                        SourceLocation LParenLoc,
10807                                        SourceLocation EndLoc);
10808   /// Called on well-formed 'order' clause.
10809   OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
10810                                     SourceLocation KindLoc,
10811                                     SourceLocation StartLoc,
10812                                     SourceLocation LParenLoc,
10813                                     SourceLocation EndLoc);
10814   /// Called on well-formed 'update' clause.
10815   OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
10816                                      SourceLocation KindLoc,
10817                                      SourceLocation StartLoc,
10818                                      SourceLocation LParenLoc,
10819                                      SourceLocation EndLoc);
10820 
10821   OMPClause *ActOnOpenMPSingleExprWithArgClause(
10822       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
10823       SourceLocation StartLoc, SourceLocation LParenLoc,
10824       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
10825       SourceLocation EndLoc);
10826   /// Called on well-formed 'schedule' clause.
10827   OMPClause *ActOnOpenMPScheduleClause(
10828       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
10829       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10830       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10831       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
10832 
10833   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
10834                                SourceLocation EndLoc);
10835   /// Called on well-formed 'nowait' clause.
10836   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10837                                      SourceLocation EndLoc);
10838   /// Called on well-formed 'untied' clause.
10839   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10840                                      SourceLocation EndLoc);
10841   /// Called on well-formed 'mergeable' clause.
10842   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10843                                         SourceLocation EndLoc);
10844   /// Called on well-formed 'read' clause.
10845   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
10846                                    SourceLocation EndLoc);
10847   /// Called on well-formed 'write' clause.
10848   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
10849                                     SourceLocation EndLoc);
10850   /// Called on well-formed 'update' clause.
10851   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10852                                      SourceLocation EndLoc);
10853   /// Called on well-formed 'capture' clause.
10854   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10855                                       SourceLocation EndLoc);
10856   /// Called on well-formed 'seq_cst' clause.
10857   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10858                                      SourceLocation EndLoc);
10859   /// Called on well-formed 'acq_rel' clause.
10860   OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
10861                                      SourceLocation EndLoc);
10862   /// Called on well-formed 'acquire' clause.
10863   OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
10864                                       SourceLocation EndLoc);
10865   /// Called on well-formed 'release' clause.
10866   OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
10867                                       SourceLocation EndLoc);
10868   /// Called on well-formed 'relaxed' clause.
10869   OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
10870                                       SourceLocation EndLoc);
10871   /// Called on well-formed 'destroy' clause.
10872   OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc,
10873                                       SourceLocation EndLoc);
10874   /// Called on well-formed 'threads' clause.
10875   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10876                                       SourceLocation EndLoc);
10877   /// Called on well-formed 'simd' clause.
10878   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10879                                    SourceLocation EndLoc);
10880   /// Called on well-formed 'nogroup' clause.
10881   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10882                                       SourceLocation EndLoc);
10883   /// Called on well-formed 'unified_address' clause.
10884   OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10885                                              SourceLocation EndLoc);
10886 
10887   /// Called on well-formed 'unified_address' clause.
10888   OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10889                                                   SourceLocation EndLoc);
10890 
10891   /// Called on well-formed 'reverse_offload' clause.
10892   OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10893                                              SourceLocation EndLoc);
10894 
10895   /// Called on well-formed 'dynamic_allocators' clause.
10896   OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10897                                                 SourceLocation EndLoc);
10898 
10899   /// Called on well-formed 'atomic_default_mem_order' clause.
10900   OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
10901       OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
10902       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10903 
10904   OMPClause *ActOnOpenMPVarListClause(
10905       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
10906       const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10907       CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10908       DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
10909       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
10910       ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
10911       SourceLocation ExtraModifierLoc,
10912       ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
10913       ArrayRef<SourceLocation> MotionModifiersLoc);
10914   /// Called on well-formed 'inclusive' clause.
10915   OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
10916                                         SourceLocation StartLoc,
10917                                         SourceLocation LParenLoc,
10918                                         SourceLocation EndLoc);
10919   /// Called on well-formed 'exclusive' clause.
10920   OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
10921                                         SourceLocation StartLoc,
10922                                         SourceLocation LParenLoc,
10923                                         SourceLocation EndLoc);
10924   /// Called on well-formed 'allocate' clause.
10925   OMPClause *
10926   ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
10927                             SourceLocation StartLoc, SourceLocation ColonLoc,
10928                             SourceLocation LParenLoc, SourceLocation EndLoc);
10929   /// Called on well-formed 'private' clause.
10930   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10931                                       SourceLocation StartLoc,
10932                                       SourceLocation LParenLoc,
10933                                       SourceLocation EndLoc);
10934   /// Called on well-formed 'firstprivate' clause.
10935   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10936                                            SourceLocation StartLoc,
10937                                            SourceLocation LParenLoc,
10938                                            SourceLocation EndLoc);
10939   /// Called on well-formed 'lastprivate' clause.
10940   OMPClause *ActOnOpenMPLastprivateClause(
10941       ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
10942       SourceLocation LPKindLoc, SourceLocation ColonLoc,
10943       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
10944   /// Called on well-formed 'shared' clause.
10945   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10946                                      SourceLocation StartLoc,
10947                                      SourceLocation LParenLoc,
10948                                      SourceLocation EndLoc);
10949   /// Called on well-formed 'reduction' clause.
10950   OMPClause *ActOnOpenMPReductionClause(
10951       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
10952       SourceLocation StartLoc, SourceLocation LParenLoc,
10953       SourceLocation ModifierLoc, SourceLocation ColonLoc,
10954       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
10955       const DeclarationNameInfo &ReductionId,
10956       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10957   /// Called on well-formed 'task_reduction' clause.
10958   OMPClause *ActOnOpenMPTaskReductionClause(
10959       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10960       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10961       CXXScopeSpec &ReductionIdScopeSpec,
10962       const DeclarationNameInfo &ReductionId,
10963       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10964   /// Called on well-formed 'in_reduction' clause.
10965   OMPClause *ActOnOpenMPInReductionClause(
10966       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10967       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
10968       CXXScopeSpec &ReductionIdScopeSpec,
10969       const DeclarationNameInfo &ReductionId,
10970       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
10971   /// Called on well-formed 'linear' clause.
10972   OMPClause *
10973   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
10974                           SourceLocation StartLoc, SourceLocation LParenLoc,
10975                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
10976                           SourceLocation ColonLoc, SourceLocation EndLoc);
10977   /// Called on well-formed 'aligned' clause.
10978   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
10979                                       Expr *Alignment,
10980                                       SourceLocation StartLoc,
10981                                       SourceLocation LParenLoc,
10982                                       SourceLocation ColonLoc,
10983                                       SourceLocation EndLoc);
10984   /// Called on well-formed 'copyin' clause.
10985   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10986                                      SourceLocation StartLoc,
10987                                      SourceLocation LParenLoc,
10988                                      SourceLocation EndLoc);
10989   /// Called on well-formed 'copyprivate' clause.
10990   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10991                                           SourceLocation StartLoc,
10992                                           SourceLocation LParenLoc,
10993                                           SourceLocation EndLoc);
10994   /// Called on well-formed 'flush' pseudo clause.
10995   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10996                                     SourceLocation StartLoc,
10997                                     SourceLocation LParenLoc,
10998                                     SourceLocation EndLoc);
10999   /// Called on well-formed 'depobj' pseudo clause.
11000   OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11001                                      SourceLocation LParenLoc,
11002                                      SourceLocation EndLoc);
11003   /// Called on well-formed 'depend' clause.
11004   OMPClause *
11005   ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
11006                           SourceLocation DepLoc, SourceLocation ColonLoc,
11007                           ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11008                           SourceLocation LParenLoc, SourceLocation EndLoc);
11009   /// Called on well-formed 'device' clause.
11010   OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11011                                      Expr *Device, SourceLocation StartLoc,
11012                                      SourceLocation LParenLoc,
11013                                      SourceLocation ModifierLoc,
11014                                      SourceLocation EndLoc);
11015   /// Called on well-formed 'map' clause.
11016   OMPClause *
11017   ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11018                        ArrayRef<SourceLocation> MapTypeModifiersLoc,
11019                        CXXScopeSpec &MapperIdScopeSpec,
11020                        DeclarationNameInfo &MapperId,
11021                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11022                        SourceLocation MapLoc, SourceLocation ColonLoc,
11023                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11024                        ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11025   /// Called on well-formed 'num_teams' clause.
11026   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11027                                        SourceLocation LParenLoc,
11028                                        SourceLocation EndLoc);
11029   /// Called on well-formed 'thread_limit' clause.
11030   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11031                                           SourceLocation StartLoc,
11032                                           SourceLocation LParenLoc,
11033                                           SourceLocation EndLoc);
11034   /// Called on well-formed 'priority' clause.
11035   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11036                                        SourceLocation LParenLoc,
11037                                        SourceLocation EndLoc);
11038   /// Called on well-formed 'dist_schedule' clause.
11039   OMPClause *ActOnOpenMPDistScheduleClause(
11040       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11041       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11042       SourceLocation CommaLoc, SourceLocation EndLoc);
11043   /// Called on well-formed 'defaultmap' clause.
11044   OMPClause *ActOnOpenMPDefaultmapClause(
11045       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11046       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11047       SourceLocation KindLoc, SourceLocation EndLoc);
11048   /// Called on well-formed 'to' clause.
11049   OMPClause *
11050   ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11051                       ArrayRef<SourceLocation> MotionModifiersLoc,
11052                       CXXScopeSpec &MapperIdScopeSpec,
11053                       DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11054                       ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11055                       ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11056   /// Called on well-formed 'from' clause.
11057   OMPClause *
11058   ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11059                         ArrayRef<SourceLocation> MotionModifiersLoc,
11060                         CXXScopeSpec &MapperIdScopeSpec,
11061                         DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11062                         ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11063                         ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11064   /// Called on well-formed 'use_device_ptr' clause.
11065   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11066                                            const OMPVarListLocTy &Locs);
11067   /// Called on well-formed 'use_device_addr' clause.
11068   OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11069                                             const OMPVarListLocTy &Locs);
11070   /// Called on well-formed 'is_device_ptr' clause.
11071   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11072                                           const OMPVarListLocTy &Locs);
11073   /// Called on well-formed 'nontemporal' clause.
11074   OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11075                                           SourceLocation StartLoc,
11076                                           SourceLocation LParenLoc,
11077                                           SourceLocation EndLoc);
11078 
11079   /// Data for list of allocators.
11080   struct UsesAllocatorsData {
11081     /// Allocator.
11082     Expr *Allocator = nullptr;
11083     /// Allocator traits.
11084     Expr *AllocatorTraits = nullptr;
11085     /// Locations of '(' and ')' symbols.
11086     SourceLocation LParenLoc, RParenLoc;
11087   };
11088   /// Called on well-formed 'uses_allocators' clause.
11089   OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11090                                             SourceLocation LParenLoc,
11091                                             SourceLocation EndLoc,
11092                                             ArrayRef<UsesAllocatorsData> Data);
11093   /// Called on well-formed 'affinity' clause.
11094   OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11095                                        SourceLocation LParenLoc,
11096                                        SourceLocation ColonLoc,
11097                                        SourceLocation EndLoc, Expr *Modifier,
11098                                        ArrayRef<Expr *> Locators);
11099 
11100   /// The kind of conversion being performed.
11101   enum CheckedConversionKind {
11102     /// An implicit conversion.
11103     CCK_ImplicitConversion,
11104     /// A C-style cast.
11105     CCK_CStyleCast,
11106     /// A functional-style cast.
11107     CCK_FunctionalCast,
11108     /// A cast other than a C-style cast.
11109     CCK_OtherCast,
11110     /// A conversion for an operand of a builtin overloaded operator.
11111     CCK_ForBuiltinOverloadedOp
11112   };
11113 
isCast(CheckedConversionKind CCK)11114   static bool isCast(CheckedConversionKind CCK) {
11115     return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11116            CCK == CCK_OtherCast;
11117   }
11118 
11119   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11120   /// cast.  If there is already an implicit cast, merge into the existing one.
11121   /// If isLvalue, the result of the cast is an lvalue.
11122   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11123                                ExprValueKind VK = VK_RValue,
11124                                const CXXCastPath *BasePath = nullptr,
11125                                CheckedConversionKind CCK
11126                                   = CCK_ImplicitConversion);
11127 
11128   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11129   /// to the conversion from scalar type ScalarTy to the Boolean type.
11130   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11131 
11132   /// IgnoredValueConversions - Given that an expression's result is
11133   /// syntactically ignored, perform any conversions that are
11134   /// required.
11135   ExprResult IgnoredValueConversions(Expr *E);
11136 
11137   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11138   // functions and arrays to their respective pointers (C99 6.3.2.1).
11139   ExprResult UsualUnaryConversions(Expr *E);
11140 
11141   /// CallExprUnaryConversions - a special case of an unary conversion
11142   /// performed on a function designator of a call expression.
11143   ExprResult CallExprUnaryConversions(Expr *E);
11144 
11145   // DefaultFunctionArrayConversion - converts functions and arrays
11146   // to their respective pointers (C99 6.3.2.1).
11147   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11148 
11149   // DefaultFunctionArrayLvalueConversion - converts functions and
11150   // arrays to their respective pointers and performs the
11151   // lvalue-to-rvalue conversion.
11152   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11153                                                   bool Diagnose = true);
11154 
11155   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11156   // the operand. This function is a no-op if the operand has a function type
11157   // or an array type.
11158   ExprResult DefaultLvalueConversion(Expr *E);
11159 
11160   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11161   // do not have a prototype. Integer promotions are performed on each
11162   // argument, and arguments that have type float are promoted to double.
11163   ExprResult DefaultArgumentPromotion(Expr *E);
11164 
11165   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11166   /// it as an xvalue. In C++98, the result will still be a prvalue, because
11167   /// we don't have xvalues there.
11168   ExprResult TemporaryMaterializationConversion(Expr *E);
11169 
11170   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11171   enum VariadicCallType {
11172     VariadicFunction,
11173     VariadicBlock,
11174     VariadicMethod,
11175     VariadicConstructor,
11176     VariadicDoesNotApply
11177   };
11178 
11179   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11180                                        const FunctionProtoType *Proto,
11181                                        Expr *Fn);
11182 
11183   // Used for determining in which context a type is allowed to be passed to a
11184   // vararg function.
11185   enum VarArgKind {
11186     VAK_Valid,
11187     VAK_ValidInCXX11,
11188     VAK_Undefined,
11189     VAK_MSVCUndefined,
11190     VAK_Invalid
11191   };
11192 
11193   // Determines which VarArgKind fits an expression.
11194   VarArgKind isValidVarArgType(const QualType &Ty);
11195 
11196   /// Check to see if the given expression is a valid argument to a variadic
11197   /// function, issuing a diagnostic if not.
11198   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11199 
11200   /// Check to see if a given expression could have '.c_str()' called on it.
11201   bool hasCStrMethod(const Expr *E);
11202 
11203   /// GatherArgumentsForCall - Collector argument expressions for various
11204   /// form of call prototypes.
11205   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11206                               const FunctionProtoType *Proto,
11207                               unsigned FirstParam, ArrayRef<Expr *> Args,
11208                               SmallVectorImpl<Expr *> &AllArgs,
11209                               VariadicCallType CallType = VariadicDoesNotApply,
11210                               bool AllowExplicit = false,
11211                               bool IsListInitialization = false);
11212 
11213   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11214   // will create a runtime trap if the resulting type is not a POD type.
11215   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11216                                               FunctionDecl *FDecl);
11217 
11218   /// Context in which we're performing a usual arithmetic conversion.
11219   enum ArithConvKind {
11220     /// An arithmetic operation.
11221     ACK_Arithmetic,
11222     /// A bitwise operation.
11223     ACK_BitwiseOp,
11224     /// A comparison.
11225     ACK_Comparison,
11226     /// A conditional (?:) operator.
11227     ACK_Conditional,
11228     /// A compound assignment expression.
11229     ACK_CompAssign,
11230   };
11231 
11232   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11233   // operands and then handles various conversions that are common to binary
11234   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11235   // routine returns the first non-arithmetic type found. The client is
11236   // responsible for emitting appropriate error diagnostics.
11237   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11238                                       SourceLocation Loc, ArithConvKind ACK);
11239 
11240   /// AssignConvertType - All of the 'assignment' semantic checks return this
11241   /// enum to indicate whether the assignment was allowed.  These checks are
11242   /// done for simple assignments, as well as initialization, return from
11243   /// function, argument passing, etc.  The query is phrased in terms of a
11244   /// source and destination type.
11245   enum AssignConvertType {
11246     /// Compatible - the types are compatible according to the standard.
11247     Compatible,
11248 
11249     /// PointerToInt - The assignment converts a pointer to an int, which we
11250     /// accept as an extension.
11251     PointerToInt,
11252 
11253     /// IntToPointer - The assignment converts an int to a pointer, which we
11254     /// accept as an extension.
11255     IntToPointer,
11256 
11257     /// FunctionVoidPointer - The assignment is between a function pointer and
11258     /// void*, which the standard doesn't allow, but we accept as an extension.
11259     FunctionVoidPointer,
11260 
11261     /// IncompatiblePointer - The assignment is between two pointers types that
11262     /// are not compatible, but we accept them as an extension.
11263     IncompatiblePointer,
11264 
11265     /// IncompatibleFunctionPointer - The assignment is between two function
11266     /// pointers types that are not compatible, but we accept them as an
11267     /// extension.
11268     IncompatibleFunctionPointer,
11269 
11270     /// IncompatiblePointerSign - The assignment is between two pointers types
11271     /// which point to integers which have a different sign, but are otherwise
11272     /// identical. This is a subset of the above, but broken out because it's by
11273     /// far the most common case of incompatible pointers.
11274     IncompatiblePointerSign,
11275 
11276     /// CompatiblePointerDiscardsQualifiers - The assignment discards
11277     /// c/v/r qualifiers, which we accept as an extension.
11278     CompatiblePointerDiscardsQualifiers,
11279 
11280     /// IncompatiblePointerDiscardsQualifiers - The assignment
11281     /// discards qualifiers that we don't permit to be discarded,
11282     /// like address spaces.
11283     IncompatiblePointerDiscardsQualifiers,
11284 
11285     /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11286     /// changes address spaces in nested pointer types which is not allowed.
11287     /// For instance, converting __private int ** to __generic int ** is
11288     /// illegal even though __private could be converted to __generic.
11289     IncompatibleNestedPointerAddressSpaceMismatch,
11290 
11291     /// IncompatibleNestedPointerQualifiers - The assignment is between two
11292     /// nested pointer types, and the qualifiers other than the first two
11293     /// levels differ e.g. char ** -> const char **, but we accept them as an
11294     /// extension.
11295     IncompatibleNestedPointerQualifiers,
11296 
11297     /// IncompatibleVectors - The assignment is between two vector types that
11298     /// have the same size, which we accept as an extension.
11299     IncompatibleVectors,
11300 
11301     /// IntToBlockPointer - The assignment converts an int to a block
11302     /// pointer. We disallow this.
11303     IntToBlockPointer,
11304 
11305     /// IncompatibleBlockPointer - The assignment is between two block
11306     /// pointers types that are not compatible.
11307     IncompatibleBlockPointer,
11308 
11309     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11310     /// id type and something else (that is incompatible with it). For example,
11311     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11312     IncompatibleObjCQualifiedId,
11313 
11314     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11315     /// object with __weak qualifier.
11316     IncompatibleObjCWeakRef,
11317 
11318     /// Incompatible - We reject this conversion outright, it is invalid to
11319     /// represent it in the AST.
11320     Incompatible
11321   };
11322 
11323   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11324   /// assignment conversion type specified by ConvTy.  This returns true if the
11325   /// conversion was invalid or false if the conversion was accepted.
11326   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11327                                 SourceLocation Loc,
11328                                 QualType DstType, QualType SrcType,
11329                                 Expr *SrcExpr, AssignmentAction Action,
11330                                 bool *Complained = nullptr);
11331 
11332   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11333   /// enum. If AllowMask is true, then we also allow the complement of a valid
11334   /// value, to be used as a mask.
11335   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11336                          bool AllowMask) const;
11337 
11338   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11339   /// integer not in the range of enum values.
11340   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11341                               Expr *SrcExpr);
11342 
11343   /// CheckAssignmentConstraints - Perform type checking for assignment,
11344   /// argument passing, variable initialization, and function return values.
11345   /// C99 6.5.16.
11346   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11347                                                QualType LHSType,
11348                                                QualType RHSType);
11349 
11350   /// Check assignment constraints and optionally prepare for a conversion of
11351   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11352   /// is true.
11353   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11354                                                ExprResult &RHS,
11355                                                CastKind &Kind,
11356                                                bool ConvertRHS = true);
11357 
11358   /// Check assignment constraints for an assignment of RHS to LHSType.
11359   ///
11360   /// \param LHSType The destination type for the assignment.
11361   /// \param RHS The source expression for the assignment.
11362   /// \param Diagnose If \c true, diagnostics may be produced when checking
11363   ///        for assignability. If a diagnostic is produced, \p RHS will be
11364   ///        set to ExprError(). Note that this function may still return
11365   ///        without producing a diagnostic, even for an invalid assignment.
11366   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11367   ///        in an audited Core Foundation API and does not need to be checked
11368   ///        for ARC retain issues.
11369   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11370   ///        conversions necessary to perform the assignment. If \c false,
11371   ///        \p Diagnose must also be \c false.
11372   AssignConvertType CheckSingleAssignmentConstraints(
11373       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11374       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11375 
11376   // If the lhs type is a transparent union, check whether we
11377   // can initialize the transparent union with the given expression.
11378   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11379                                                              ExprResult &RHS);
11380 
11381   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11382 
11383   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11384 
11385   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11386                                        AssignmentAction Action,
11387                                        bool AllowExplicit = false);
11388   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11389                                        const ImplicitConversionSequence& ICS,
11390                                        AssignmentAction Action,
11391                                        CheckedConversionKind CCK
11392                                           = CCK_ImplicitConversion);
11393   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11394                                        const StandardConversionSequence& SCS,
11395                                        AssignmentAction Action,
11396                                        CheckedConversionKind CCK);
11397 
11398   ExprResult PerformQualificationConversion(
11399       Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
11400       CheckedConversionKind CCK = CCK_ImplicitConversion);
11401 
11402   /// the following "Check" methods will return a valid/converted QualType
11403   /// or a null QualType (indicating an error diagnostic was issued).
11404 
11405   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11406   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11407                            ExprResult &RHS);
11408   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11409                                  ExprResult &RHS);
11410   QualType CheckPointerToMemberOperands( // C++ 5.5
11411     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11412     SourceLocation OpLoc, bool isIndirect);
11413   QualType CheckMultiplyDivideOperands( // C99 6.5.5
11414     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11415     bool IsDivide);
11416   QualType CheckRemainderOperands( // C99 6.5.5
11417     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11418     bool IsCompAssign = false);
11419   QualType CheckAdditionOperands( // C99 6.5.6
11420     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11421     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11422   QualType CheckSubtractionOperands( // C99 6.5.6
11423     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11424     QualType* CompLHSTy = nullptr);
11425   QualType CheckShiftOperands( // C99 6.5.7
11426     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11427     BinaryOperatorKind Opc, bool IsCompAssign = false);
11428   void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11429   QualType CheckCompareOperands( // C99 6.5.8/9
11430       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11431       BinaryOperatorKind Opc);
11432   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11433       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11434       BinaryOperatorKind Opc);
11435   QualType CheckLogicalOperands( // C99 6.5.[13,14]
11436     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11437     BinaryOperatorKind Opc);
11438   // CheckAssignmentOperands is used for both simple and compound assignment.
11439   // For simple assignment, pass both expressions and a null converted type.
11440   // For compound assignment, pass both expressions and the converted type.
11441   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11442     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11443 
11444   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11445                                      UnaryOperatorKind Opcode, Expr *Op);
11446   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11447                                          BinaryOperatorKind Opcode,
11448                                          Expr *LHS, Expr *RHS);
11449   ExprResult checkPseudoObjectRValue(Expr *E);
11450   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11451 
11452   QualType CheckConditionalOperands( // C99 6.5.15
11453     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11454     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11455   QualType CXXCheckConditionalOperands( // C++ 5.16
11456     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11457     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11458   QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11459                                           ExprResult &RHS,
11460                                           SourceLocation QuestionLoc);
11461   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11462                                     bool ConvertArgs = true);
11463   QualType FindCompositePointerType(SourceLocation Loc,
11464                                     ExprResult &E1, ExprResult &E2,
11465                                     bool ConvertArgs = true) {
11466     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
11467     QualType Composite =
11468         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
11469     E1 = E1Tmp;
11470     E2 = E2Tmp;
11471     return Composite;
11472   }
11473 
11474   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
11475                                         SourceLocation QuestionLoc);
11476 
11477   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
11478                                   SourceLocation QuestionLoc);
11479 
11480   void DiagnoseAlwaysNonNullPointer(Expr *E,
11481                                     Expr::NullPointerConstantKind NullType,
11482                                     bool IsEqual, SourceRange Range);
11483 
11484   /// type checking for vector binary operators.
11485   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11486                                SourceLocation Loc, bool IsCompAssign,
11487                                bool AllowBothBool, bool AllowBoolConversion);
11488   QualType GetSignedVectorType(QualType V);
11489   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11490                                       SourceLocation Loc,
11491                                       BinaryOperatorKind Opc);
11492   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11493                                       SourceLocation Loc);
11494 
11495   /// Type checking for matrix binary operators.
11496   QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
11497                                           SourceLocation Loc,
11498                                           bool IsCompAssign);
11499   QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
11500                                        SourceLocation Loc, bool IsCompAssign);
11501 
11502   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
11503   bool isLaxVectorConversion(QualType srcType, QualType destType);
11504 
11505   /// type checking declaration initializers (C99 6.7.8)
11506   bool CheckForConstantInitializer(Expr *e, QualType t);
11507 
11508   // type checking C++ declaration initializers (C++ [dcl.init]).
11509 
11510   /// ReferenceCompareResult - Expresses the result of comparing two
11511   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
11512   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
11513   enum ReferenceCompareResult {
11514     /// Ref_Incompatible - The two types are incompatible, so direct
11515     /// reference binding is not possible.
11516     Ref_Incompatible = 0,
11517     /// Ref_Related - The two types are reference-related, which means
11518     /// that their unqualified forms (T1 and T2) are either the same
11519     /// or T1 is a base class of T2.
11520     Ref_Related,
11521     /// Ref_Compatible - The two types are reference-compatible.
11522     Ref_Compatible
11523   };
11524 
11525   // Fake up a scoped enumeration that still contextually converts to bool.
11526   struct ReferenceConversionsScope {
11527     /// The conversions that would be performed on an lvalue of type T2 when
11528     /// binding a reference of type T1 to it, as determined when evaluating
11529     /// whether T1 is reference-compatible with T2.
11530     enum ReferenceConversions {
11531       Qualification = 0x1,
11532       NestedQualification = 0x2,
11533       Function = 0x4,
11534       DerivedToBase = 0x8,
11535       ObjC = 0x10,
11536       ObjCLifetime = 0x20,
11537 
11538       LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
11539     };
11540   };
11541   using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
11542 
11543   ReferenceCompareResult
11544   CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
11545                                ReferenceConversions *Conv = nullptr);
11546 
11547   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11548                                  Expr *CastExpr, CastKind &CastKind,
11549                                  ExprValueKind &VK, CXXCastPath &Path);
11550 
11551   /// Force an expression with unknown-type to an expression of the
11552   /// given type.
11553   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
11554 
11555   /// Type-check an expression that's being passed to an
11556   /// __unknown_anytype parameter.
11557   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
11558                                 Expr *result, QualType &paramType);
11559 
11560   // CheckVectorCast - check type constraints for vectors.
11561   // Since vectors are an extension, there are no C standard reference for this.
11562   // We allow casting between vectors and integer datatypes of the same size.
11563   // returns true if the cast is invalid
11564   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
11565                        CastKind &Kind);
11566 
11567   /// Prepare `SplattedExpr` for a vector splat operation, adding
11568   /// implicit casts if necessary.
11569   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
11570 
11571   // CheckExtVectorCast - check type constraints for extended vectors.
11572   // Since vectors are an extension, there are no C standard reference for this.
11573   // We allow casting between vectors and integer datatypes of the same size,
11574   // or vectors and the element type of that vector.
11575   // returns the cast expr
11576   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
11577                                 CastKind &Kind);
11578 
11579   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
11580                                         SourceLocation LParenLoc,
11581                                         Expr *CastExpr,
11582                                         SourceLocation RParenLoc);
11583 
11584   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
11585 
11586   /// Checks for invalid conversions and casts between
11587   /// retainable pointers and other pointer kinds for ARC and Weak.
11588   ARCConversionResult CheckObjCConversion(SourceRange castRange,
11589                                           QualType castType, Expr *&op,
11590                                           CheckedConversionKind CCK,
11591                                           bool Diagnose = true,
11592                                           bool DiagnoseCFAudited = false,
11593                                           BinaryOperatorKind Opc = BO_PtrMemD
11594                                           );
11595 
11596   Expr *stripARCUnbridgedCast(Expr *e);
11597   void diagnoseARCUnbridgedCast(Expr *e);
11598 
11599   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
11600                                              QualType ExprType);
11601 
11602   /// checkRetainCycles - Check whether an Objective-C message send
11603   /// might create an obvious retain cycle.
11604   void checkRetainCycles(ObjCMessageExpr *msg);
11605   void checkRetainCycles(Expr *receiver, Expr *argument);
11606   void checkRetainCycles(VarDecl *Var, Expr *Init);
11607 
11608   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
11609   /// to weak/__unsafe_unretained type.
11610   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
11611 
11612   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
11613   /// to weak/__unsafe_unretained expression.
11614   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
11615 
11616   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
11617   /// \param Method - May be null.
11618   /// \param [out] ReturnType - The return type of the send.
11619   /// \return true iff there were any incompatible types.
11620   bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
11621                                  MultiExprArg Args, Selector Sel,
11622                                  ArrayRef<SourceLocation> SelectorLocs,
11623                                  ObjCMethodDecl *Method, bool isClassMessage,
11624                                  bool isSuperMessage, SourceLocation lbrac,
11625                                  SourceLocation rbrac, SourceRange RecRange,
11626                                  QualType &ReturnType, ExprValueKind &VK);
11627 
11628   /// Determine the result of a message send expression based on
11629   /// the type of the receiver, the method expected to receive the message,
11630   /// and the form of the message send.
11631   QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
11632                                     ObjCMethodDecl *Method, bool isClassMessage,
11633                                     bool isSuperMessage);
11634 
11635   /// If the given expression involves a message send to a method
11636   /// with a related result type, emit a note describing what happened.
11637   void EmitRelatedResultTypeNote(const Expr *E);
11638 
11639   /// Given that we had incompatible pointer types in a return
11640   /// statement, check whether we're in a method with a related result
11641   /// type, and if so, emit a note describing what happened.
11642   void EmitRelatedResultTypeNoteForReturn(QualType destType);
11643 
11644   class ConditionResult {
11645     Decl *ConditionVar;
11646     FullExprArg Condition;
11647     bool Invalid;
11648     bool HasKnownValue;
11649     bool KnownValue;
11650 
11651     friend class Sema;
ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)11652     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
11653                     bool IsConstexpr)
11654         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
11655           HasKnownValue(IsConstexpr && Condition.get() &&
11656                         !Condition.get()->isValueDependent()),
11657           KnownValue(HasKnownValue &&
11658                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
ConditionResult(bool Invalid)11659     explicit ConditionResult(bool Invalid)
11660         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
11661           HasKnownValue(false), KnownValue(false) {}
11662 
11663   public:
ConditionResult()11664     ConditionResult() : ConditionResult(false) {}
isInvalid()11665     bool isInvalid() const { return Invalid; }
get()11666     std::pair<VarDecl *, Expr *> get() const {
11667       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
11668                             Condition.get());
11669     }
getKnownValue()11670     llvm::Optional<bool> getKnownValue() const {
11671       if (!HasKnownValue)
11672         return None;
11673       return KnownValue;
11674     }
11675   };
ConditionError()11676   static ConditionResult ConditionError() { return ConditionResult(true); }
11677 
11678   enum class ConditionKind {
11679     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
11680     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
11681     Switch       ///< An integral condition for a 'switch' statement.
11682   };
11683 
11684   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
11685                                  Expr *SubExpr, ConditionKind CK);
11686 
11687   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
11688                                          SourceLocation StmtLoc,
11689                                          ConditionKind CK);
11690 
11691   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
11692 
11693   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
11694                                     SourceLocation StmtLoc,
11695                                     ConditionKind CK);
11696   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11697 
11698   /// CheckBooleanCondition - Diagnose problems involving the use of
11699   /// the given expression as a boolean condition (e.g. in an if
11700   /// statement).  Also performs the standard function and array
11701   /// decays, possibly changing the input variable.
11702   ///
11703   /// \param Loc - A location associated with the condition, e.g. the
11704   /// 'if' keyword.
11705   /// \return true iff there were any errors
11706   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
11707                                    bool IsConstexpr = false);
11708 
11709   /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
11710   /// found in an explicit(bool) specifier.
11711   ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
11712 
11713   /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
11714   /// Returns true if the explicit specifier is now resolved.
11715   bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
11716 
11717   /// DiagnoseAssignmentAsCondition - Given that an expression is
11718   /// being used as a boolean condition, warn if it's an assignment.
11719   void DiagnoseAssignmentAsCondition(Expr *E);
11720 
11721   /// Redundant parentheses over an equality comparison can indicate
11722   /// that the user intended an assignment used as condition.
11723   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
11724 
11725   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
11726   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
11727 
11728   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
11729   /// the specified width and sign.  If an overflow occurs, detect it and emit
11730   /// the specified diagnostic.
11731   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
11732                                           unsigned NewWidth, bool NewSign,
11733                                           SourceLocation Loc, unsigned DiagID);
11734 
11735   /// Checks that the Objective-C declaration is declared in the global scope.
11736   /// Emits an error and marks the declaration as invalid if it's not declared
11737   /// in the global scope.
11738   bool CheckObjCDeclScope(Decl *D);
11739 
11740   /// Abstract base class used for diagnosing integer constant
11741   /// expression violations.
11742   class VerifyICEDiagnoser {
11743   public:
11744     bool Suppress;
11745 
Suppress(Suppress)11746     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
11747 
11748     virtual SemaDiagnosticBuilder
11749     diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
11750     virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
11751                                                  SourceLocation Loc) = 0;
11752     virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
~VerifyICEDiagnoser()11753     virtual ~VerifyICEDiagnoser() {}
11754   };
11755 
11756   enum AllowFoldKind {
11757     NoFold,
11758     AllowFold,
11759   };
11760 
11761   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
11762   /// and reports the appropriate diagnostics. Returns false on success.
11763   /// Can optionally return the value of the expression.
11764   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11765                                              VerifyICEDiagnoser &Diagnoser,
11766                                              AllowFoldKind CanFold = NoFold);
11767   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11768                                              unsigned DiagID,
11769                                              AllowFoldKind CanFold = NoFold);
11770   ExprResult VerifyIntegerConstantExpression(Expr *E,
11771                                              llvm::APSInt *Result = nullptr,
11772                                              AllowFoldKind CanFold = NoFold);
11773   ExprResult VerifyIntegerConstantExpression(Expr *E,
11774                                              AllowFoldKind CanFold = NoFold) {
11775     return VerifyIntegerConstantExpression(E, nullptr, CanFold);
11776   }
11777 
11778   /// VerifyBitField - verifies that a bit field expression is an ICE and has
11779   /// the correct width, and that the field type is valid.
11780   /// Returns false on success.
11781   /// Can optionally return whether the bit-field is of width 0
11782   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
11783                             QualType FieldTy, bool IsMsStruct,
11784                             Expr *BitWidth, bool *ZeroWidth = nullptr);
11785 
11786 private:
11787   unsigned ForceCUDAHostDeviceDepth = 0;
11788 
11789 public:
11790   /// Increments our count of the number of times we've seen a pragma forcing
11791   /// functions to be __host__ __device__.  So long as this count is greater
11792   /// than zero, all functions encountered will be __host__ __device__.
11793   void PushForceCUDAHostDevice();
11794 
11795   /// Decrements our count of the number of times we've seen a pragma forcing
11796   /// functions to be __host__ __device__.  Returns false if the count is 0
11797   /// before incrementing, so you can emit an error.
11798   bool PopForceCUDAHostDevice();
11799 
11800   /// Diagnostics that are emitted only if we discover that the given function
11801   /// must be codegen'ed.  Because handling these correctly adds overhead to
11802   /// compilation, this is currently only enabled for CUDA compilations.
11803   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
11804                  std::vector<PartialDiagnosticAt>>
11805       DeviceDeferredDiags;
11806 
11807   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
11808   /// key in a hashtable, both the FD and location are hashed.
11809   struct FunctionDeclAndLoc {
11810     CanonicalDeclPtr<FunctionDecl> FD;
11811     SourceLocation Loc;
11812   };
11813 
11814   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
11815   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
11816   /// same deferred diag twice.
11817   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
11818 
11819   /// An inverse call graph, mapping known-emitted functions to one of their
11820   /// known-emitted callers (plus the location of the call).
11821   ///
11822   /// Functions that we can tell a priori must be emitted aren't added to this
11823   /// map.
11824   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
11825                  /* Caller = */ FunctionDeclAndLoc>
11826       DeviceKnownEmittedFns;
11827 
11828   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11829   /// context is "used as device code".
11830   ///
11831   /// - If CurContext is a __host__ function, does not emit any diagnostics
11832   ///   unless \p EmitOnBothSides is true.
11833   /// - If CurContext is a __device__ or __global__ function, emits the
11834   ///   diagnostics immediately.
11835   /// - If CurContext is a __host__ __device__ function and we are compiling for
11836   ///   the device, creates a diagnostic which is emitted if and when we realize
11837   ///   that the function will be codegen'ed.
11838   ///
11839   /// Example usage:
11840   ///
11841   ///  // Variable-length arrays are not allowed in CUDA device code.
11842   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
11843   ///    return ExprError();
11844   ///  // Otherwise, continue parsing as normal.
11845   SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
11846                                              unsigned DiagID);
11847 
11848   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11849   /// context is "used as host code".
11850   ///
11851   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
11852   SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
11853 
11854   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11855   /// context is "used as device code".
11856   ///
11857   /// - If CurContext is a `declare target` function or it is known that the
11858   /// function is emitted for the device, emits the diagnostics immediately.
11859   /// - If CurContext is a non-`declare target` function and we are compiling
11860   ///   for the device, creates a diagnostic which is emitted if and when we
11861   ///   realize that the function will be codegen'ed.
11862   ///
11863   /// Example usage:
11864   ///
11865   ///  // Variable-length arrays are not allowed in NVPTX device code.
11866   ///  if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
11867   ///    return ExprError();
11868   ///  // Otherwise, continue parsing as normal.
11869   SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc,
11870                                                unsigned DiagID);
11871 
11872   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
11873   /// context is "used as host code".
11874   ///
11875   /// - If CurContext is a `declare target` function or it is known that the
11876   /// function is emitted for the host, emits the diagnostics immediately.
11877   /// - If CurContext is a non-host function, just ignore it.
11878   ///
11879   /// Example usage:
11880   ///
11881   ///  // Variable-length arrays are not allowed in NVPTX device code.
11882   ///  if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
11883   ///    return ExprError();
11884   ///  // Otherwise, continue parsing as normal.
11885   SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
11886                                              unsigned DiagID);
11887 
11888   SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
targetDiag(SourceLocation Loc,const PartialDiagnostic & PD)11889   SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
11890                                    const PartialDiagnostic &PD) {
11891     return targetDiag(Loc, PD.getDiagID()) << PD;
11892   }
11893 
11894   /// Check if the expression is allowed to be used in expressions for the
11895   /// offloading devices.
11896   void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc);
11897 
11898   enum CUDAFunctionTarget {
11899     CFT_Device,
11900     CFT_Global,
11901     CFT_Host,
11902     CFT_HostDevice,
11903     CFT_InvalidTarget
11904   };
11905 
11906   /// Determines whether the given function is a CUDA device/host/kernel/etc.
11907   /// function.
11908   ///
11909   /// Use this rather than examining the function's attributes yourself -- you
11910   /// will get it wrong.  Returns CFT_Host if D is null.
11911   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
11912                                         bool IgnoreImplicitHDAttr = false);
11913   CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
11914 
11915   /// Gets the CUDA target for the current context.
CurrentCUDATarget()11916   CUDAFunctionTarget CurrentCUDATarget() {
11917     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
11918   }
11919 
11920   static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
11921 
11922   // CUDA function call preference. Must be ordered numerically from
11923   // worst to best.
11924   enum CUDAFunctionPreference {
11925     CFP_Never,      // Invalid caller/callee combination.
11926     CFP_WrongSide,  // Calls from host-device to host or device
11927                     // function that do not match current compilation
11928                     // mode.
11929     CFP_HostDevice, // Any calls to host/device functions.
11930     CFP_SameSide,   // Calls from host-device to host or device
11931                     // function matching current compilation mode.
11932     CFP_Native,     // host-to-host or device-to-device calls.
11933   };
11934 
11935   /// Identifies relative preference of a given Caller/Callee
11936   /// combination, based on their host/device attributes.
11937   /// \param Caller function which needs address of \p Callee.
11938   ///               nullptr in case of global context.
11939   /// \param Callee target function
11940   ///
11941   /// \returns preference value for particular Caller/Callee combination.
11942   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
11943                                                 const FunctionDecl *Callee);
11944 
11945   /// Determines whether Caller may invoke Callee, based on their CUDA
11946   /// host/device attributes.  Returns false if the call is not allowed.
11947   ///
11948   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
11949   /// semantically correct CUDA programs, but only if they're never codegen'ed.
IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)11950   bool IsAllowedCUDACall(const FunctionDecl *Caller,
11951                          const FunctionDecl *Callee) {
11952     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
11953   }
11954 
11955   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
11956   /// depending on FD and the current compilation settings.
11957   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
11958                                    const LookupResult &Previous);
11959 
11960   /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
11961   /// and current compilation settings.
11962   void MaybeAddCUDAConstantAttr(VarDecl *VD);
11963 
11964 public:
11965   /// Check whether we're allowed to call Callee from the current context.
11966   ///
11967   /// - If the call is never allowed in a semantically-correct program
11968   ///   (CFP_Never), emits an error and returns false.
11969   ///
11970   /// - If the call is allowed in semantically-correct programs, but only if
11971   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
11972   ///   be emitted if and when the caller is codegen'ed, and returns true.
11973   ///
11974   ///   Will only create deferred diagnostics for a given SourceLocation once,
11975   ///   so you can safely call this multiple times without generating duplicate
11976   ///   deferred errors.
11977   ///
11978   /// - Otherwise, returns true without emitting any diagnostics.
11979   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
11980 
11981   void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
11982 
11983   /// Set __device__ or __host__ __device__ attributes on the given lambda
11984   /// operator() method.
11985   ///
11986   /// CUDA lambdas by default is host device function unless it has explicit
11987   /// host or device attribute.
11988   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
11989 
11990   /// Finds a function in \p Matches with highest calling priority
11991   /// from \p Caller context and erases all functions with lower
11992   /// calling priority.
11993   void EraseUnwantedCUDAMatches(
11994       const FunctionDecl *Caller,
11995       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
11996 
11997   /// Given a implicit special member, infer its CUDA target from the
11998   /// calls it needs to make to underlying base/field special members.
11999   /// \param ClassDecl the class for which the member is being created.
12000   /// \param CSM the kind of special member.
12001   /// \param MemberDecl the special member itself.
12002   /// \param ConstRHS true if this is a copy operation with a const object on
12003   ///        its RHS.
12004   /// \param Diagnose true if this call should emit diagnostics.
12005   /// \return true if there was an error inferring.
12006   /// The result of this call is implicit CUDA target attribute(s) attached to
12007   /// the member declaration.
12008   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12009                                                CXXSpecialMember CSM,
12010                                                CXXMethodDecl *MemberDecl,
12011                                                bool ConstRHS,
12012                                                bool Diagnose);
12013 
12014   /// \return true if \p CD can be considered empty according to CUDA
12015   /// (E.2.3.1 in CUDA 7.5 Programming guide).
12016   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12017   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12018 
12019   // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12020   // case of error emits appropriate diagnostic and invalidates \p Var.
12021   //
12022   // \details CUDA allows only empty constructors as initializers for global
12023   // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12024   // __shared__ variables whether they are local or not (they all are implicitly
12025   // static in CUDA). One exception is that CUDA allows constant initializers
12026   // for __constant__ and __device__ variables.
12027   void checkAllowedCUDAInitializer(VarDecl *VD);
12028 
12029   /// Check whether NewFD is a valid overload for CUDA. Emits
12030   /// diagnostics and invalidates NewFD if not.
12031   void checkCUDATargetOverload(FunctionDecl *NewFD,
12032                                const LookupResult &Previous);
12033   /// Copies target attributes from the template TD to the function FD.
12034   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12035 
12036   /// Returns the name of the launch configuration function.  This is the name
12037   /// of the function that will be called to configure kernel call, with the
12038   /// parameters specified via <<<>>>.
12039   std::string getCudaConfigureFuncName() const;
12040 
12041   /// \name Code completion
12042   //@{
12043   /// Describes the context in which code completion occurs.
12044   enum ParserCompletionContext {
12045     /// Code completion occurs at top-level or namespace context.
12046     PCC_Namespace,
12047     /// Code completion occurs within a class, struct, or union.
12048     PCC_Class,
12049     /// Code completion occurs within an Objective-C interface, protocol,
12050     /// or category.
12051     PCC_ObjCInterface,
12052     /// Code completion occurs within an Objective-C implementation or
12053     /// category implementation
12054     PCC_ObjCImplementation,
12055     /// Code completion occurs within the list of instance variables
12056     /// in an Objective-C interface, protocol, category, or implementation.
12057     PCC_ObjCInstanceVariableList,
12058     /// Code completion occurs following one or more template
12059     /// headers.
12060     PCC_Template,
12061     /// Code completion occurs following one or more template
12062     /// headers within a class.
12063     PCC_MemberTemplate,
12064     /// Code completion occurs within an expression.
12065     PCC_Expression,
12066     /// Code completion occurs within a statement, which may
12067     /// also be an expression or a declaration.
12068     PCC_Statement,
12069     /// Code completion occurs at the beginning of the
12070     /// initialization statement (or expression) in a for loop.
12071     PCC_ForInit,
12072     /// Code completion occurs within the condition of an if,
12073     /// while, switch, or for statement.
12074     PCC_Condition,
12075     /// Code completion occurs within the body of a function on a
12076     /// recovery path, where we do not have a specific handle on our position
12077     /// in the grammar.
12078     PCC_RecoveryInFunction,
12079     /// Code completion occurs where only a type is permitted.
12080     PCC_Type,
12081     /// Code completion occurs in a parenthesized expression, which
12082     /// might also be a type cast.
12083     PCC_ParenthesizedExpression,
12084     /// Code completion occurs within a sequence of declaration
12085     /// specifiers within a function, method, or block.
12086     PCC_LocalDeclarationSpecifiers
12087   };
12088 
12089   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12090   void CodeCompleteOrdinaryName(Scope *S,
12091                                 ParserCompletionContext CompletionContext);
12092   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12093                             bool AllowNonIdentifiers,
12094                             bool AllowNestedNameSpecifiers);
12095 
12096   struct CodeCompleteExpressionData;
12097   void CodeCompleteExpression(Scope *S,
12098                               const CodeCompleteExpressionData &Data);
12099   void CodeCompleteExpression(Scope *S, QualType PreferredType,
12100                               bool IsParenthesized = false);
12101   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12102                                        SourceLocation OpLoc, bool IsArrow,
12103                                        bool IsBaseExprStatement,
12104                                        QualType PreferredType);
12105   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12106                                      QualType PreferredType);
12107   void CodeCompleteTag(Scope *S, unsigned TagSpec);
12108   void CodeCompleteTypeQualifiers(DeclSpec &DS);
12109   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12110                                       const VirtSpecifiers *VS = nullptr);
12111   void CodeCompleteBracketDeclarator(Scope *S);
12112   void CodeCompleteCase(Scope *S);
12113   /// Reports signatures for a call to CodeCompleteConsumer and returns the
12114   /// preferred type for the current argument. Returned type can be null.
12115   QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
12116                                     SourceLocation OpenParLoc);
12117   QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
12118                                            SourceLocation Loc,
12119                                            ArrayRef<Expr *> Args,
12120                                            SourceLocation OpenParLoc);
12121   QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
12122                                               CXXScopeSpec SS,
12123                                               ParsedType TemplateTypeTy,
12124                                               ArrayRef<Expr *> ArgExprs,
12125                                               IdentifierInfo *II,
12126                                               SourceLocation OpenParLoc);
12127   void CodeCompleteInitializer(Scope *S, Decl *D);
12128   /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12129   /// expressions in the initializer list seen so far and \p D is the current
12130   /// Designation being parsed.
12131   void CodeCompleteDesignator(const QualType BaseType,
12132                               llvm::ArrayRef<Expr *> InitExprs,
12133                               const Designation &D);
12134   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12135 
12136   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12137                                bool IsUsingDeclaration, QualType BaseType,
12138                                QualType PreferredType);
12139   void CodeCompleteUsing(Scope *S);
12140   void CodeCompleteUsingDirective(Scope *S);
12141   void CodeCompleteNamespaceDecl(Scope *S);
12142   void CodeCompleteNamespaceAliasDecl(Scope *S);
12143   void CodeCompleteOperatorName(Scope *S);
12144   void CodeCompleteConstructorInitializer(
12145                                 Decl *Constructor,
12146                                 ArrayRef<CXXCtorInitializer *> Initializers);
12147 
12148   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12149                                     bool AfterAmpersand);
12150   void CodeCompleteAfterFunctionEquals(Declarator &D);
12151 
12152   void CodeCompleteObjCAtDirective(Scope *S);
12153   void CodeCompleteObjCAtVisibility(Scope *S);
12154   void CodeCompleteObjCAtStatement(Scope *S);
12155   void CodeCompleteObjCAtExpression(Scope *S);
12156   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12157   void CodeCompleteObjCPropertyGetter(Scope *S);
12158   void CodeCompleteObjCPropertySetter(Scope *S);
12159   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12160                                    bool IsParameter);
12161   void CodeCompleteObjCMessageReceiver(Scope *S);
12162   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12163                                     ArrayRef<IdentifierInfo *> SelIdents,
12164                                     bool AtArgumentExpression);
12165   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12166                                     ArrayRef<IdentifierInfo *> SelIdents,
12167                                     bool AtArgumentExpression,
12168                                     bool IsSuper = false);
12169   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12170                                        ArrayRef<IdentifierInfo *> SelIdents,
12171                                        bool AtArgumentExpression,
12172                                        ObjCInterfaceDecl *Super = nullptr);
12173   void CodeCompleteObjCForCollection(Scope *S,
12174                                      DeclGroupPtrTy IterationVar);
12175   void CodeCompleteObjCSelector(Scope *S,
12176                                 ArrayRef<IdentifierInfo *> SelIdents);
12177   void CodeCompleteObjCProtocolReferences(
12178                                          ArrayRef<IdentifierLocPair> Protocols);
12179   void CodeCompleteObjCProtocolDecl(Scope *S);
12180   void CodeCompleteObjCInterfaceDecl(Scope *S);
12181   void CodeCompleteObjCSuperclass(Scope *S,
12182                                   IdentifierInfo *ClassName,
12183                                   SourceLocation ClassNameLoc);
12184   void CodeCompleteObjCImplementationDecl(Scope *S);
12185   void CodeCompleteObjCInterfaceCategory(Scope *S,
12186                                          IdentifierInfo *ClassName,
12187                                          SourceLocation ClassNameLoc);
12188   void CodeCompleteObjCImplementationCategory(Scope *S,
12189                                               IdentifierInfo *ClassName,
12190                                               SourceLocation ClassNameLoc);
12191   void CodeCompleteObjCPropertyDefinition(Scope *S);
12192   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12193                                               IdentifierInfo *PropertyName);
12194   void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12195                                   ParsedType ReturnType);
12196   void CodeCompleteObjCMethodDeclSelector(Scope *S,
12197                                           bool IsInstanceMethod,
12198                                           bool AtParameterName,
12199                                           ParsedType ReturnType,
12200                                           ArrayRef<IdentifierInfo *> SelIdents);
12201   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12202                                             SourceLocation ClassNameLoc,
12203                                             bool IsBaseExprStatement);
12204   void CodeCompletePreprocessorDirective(bool InConditional);
12205   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12206   void CodeCompletePreprocessorMacroName(bool IsDefinition);
12207   void CodeCompletePreprocessorExpression();
12208   void CodeCompletePreprocessorMacroArgument(Scope *S,
12209                                              IdentifierInfo *Macro,
12210                                              MacroInfo *MacroInfo,
12211                                              unsigned Argument);
12212   void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12213   void CodeCompleteNaturalLanguage();
12214   void CodeCompleteAvailabilityPlatformName();
12215   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12216                                    CodeCompletionTUInfo &CCTUInfo,
12217                   SmallVectorImpl<CodeCompletionResult> &Results);
12218   //@}
12219 
12220   //===--------------------------------------------------------------------===//
12221   // Extra semantic analysis beyond the C type system
12222 
12223 public:
12224   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12225                                                 unsigned ByteNo) const;
12226 
12227 private:
12228   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12229                         const ArraySubscriptExpr *ASE=nullptr,
12230                         bool AllowOnePastEnd=true, bool IndexNegated=false);
12231   void CheckArrayAccess(const Expr *E);
12232   // Used to grab the relevant information from a FormatAttr and a
12233   // FunctionDeclaration.
12234   struct FormatStringInfo {
12235     unsigned FormatIdx;
12236     unsigned FirstDataArg;
12237     bool HasVAListArg;
12238   };
12239 
12240   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12241                                   FormatStringInfo *FSI);
12242   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12243                          const FunctionProtoType *Proto);
12244   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12245                            ArrayRef<const Expr *> Args);
12246   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12247                         const FunctionProtoType *Proto);
12248   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12249   void CheckConstructorCall(FunctionDecl *FDecl,
12250                             ArrayRef<const Expr *> Args,
12251                             const FunctionProtoType *Proto,
12252                             SourceLocation Loc);
12253 
12254   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12255                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
12256                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12257                  VariadicCallType CallType);
12258 
12259   bool CheckObjCString(Expr *Arg);
12260   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12261 
12262   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12263                                       unsigned BuiltinID, CallExpr *TheCall);
12264 
12265   bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12266                                   CallExpr *TheCall);
12267 
12268   void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12269 
12270   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12271                                     unsigned MaxWidth);
12272   bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12273                                     CallExpr *TheCall);
12274   bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12275   bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12276   bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12277                                    CallExpr *TheCall);
12278   bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12279                                     bool WantCDE);
12280   bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12281                                    CallExpr *TheCall);
12282 
12283   bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12284                                        CallExpr *TheCall);
12285   bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12286   bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12287   bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12288   bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12289                                     CallExpr *TheCall);
12290   bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12291                            CallExpr *TheCall);
12292   bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12293   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12294   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12295   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12296   bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12297   bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12298                                          ArrayRef<int> ArgNums);
12299   bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12300   bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12301                                             ArrayRef<int> ArgNums);
12302   bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12303                                    CallExpr *TheCall);
12304   bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12305                                    CallExpr *TheCall);
12306   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12307 
12308   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12309   bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12310   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12311   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12312   bool SemaBuiltinComplex(CallExpr *TheCall);
12313   bool SemaBuiltinVSX(CallExpr *TheCall);
12314   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12315 
12316 public:
12317   // Used by C++ template instantiation.
12318   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12319   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12320                                    SourceLocation BuiltinLoc,
12321                                    SourceLocation RParenLoc);
12322 
12323 private:
12324   bool SemaBuiltinPrefetch(CallExpr *TheCall);
12325   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12326   bool SemaBuiltinAssume(CallExpr *TheCall);
12327   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12328   bool SemaBuiltinLongjmp(CallExpr *TheCall);
12329   bool SemaBuiltinSetjmp(CallExpr *TheCall);
12330   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12331   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12332   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12333                                      AtomicExpr::AtomicOp Op);
12334   ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12335                                                     bool IsDelete);
12336   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12337                               llvm::APSInt &Result);
12338   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12339                                    int High, bool RangeIsError = true);
12340   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12341                                       unsigned Multiple);
12342   bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12343   bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12344                                          unsigned ArgBits);
12345   bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12346                                                unsigned ArgBits);
12347   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12348                                 int ArgNum, unsigned ExpectedFieldNum,
12349                                 bool AllowName);
12350   bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12351   bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc);
12352 
12353   bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
12354 
12355   // Matrix builtin handling.
12356   ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12357                                         ExprResult CallResult);
12358   ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12359                                               ExprResult CallResult);
12360   ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12361                                                ExprResult CallResult);
12362 
12363 public:
12364   enum FormatStringType {
12365     FST_Scanf,
12366     FST_Printf,
12367     FST_NSString,
12368     FST_Strftime,
12369     FST_Strfmon,
12370     FST_Kprintf,
12371     FST_FreeBSDKPrintf,
12372     FST_OSTrace,
12373     FST_OSLog,
12374     FST_Unknown
12375   };
12376   static FormatStringType GetFormatStringType(const FormatAttr *Format);
12377 
12378   bool FormatStringHasSArg(const StringLiteral *FExpr);
12379 
12380   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12381 
12382 private:
12383   bool CheckFormatArguments(const FormatAttr *Format,
12384                             ArrayRef<const Expr *> Args,
12385                             bool IsCXXMember,
12386                             VariadicCallType CallType,
12387                             SourceLocation Loc, SourceRange Range,
12388                             llvm::SmallBitVector &CheckedVarArgs);
12389   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12390                             bool HasVAListArg, unsigned format_idx,
12391                             unsigned firstDataArg, FormatStringType Type,
12392                             VariadicCallType CallType,
12393                             SourceLocation Loc, SourceRange range,
12394                             llvm::SmallBitVector &CheckedVarArgs);
12395 
12396   void CheckAbsoluteValueFunction(const CallExpr *Call,
12397                                   const FunctionDecl *FDecl);
12398 
12399   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12400 
12401   void CheckMemaccessArguments(const CallExpr *Call,
12402                                unsigned BId,
12403                                IdentifierInfo *FnName);
12404 
12405   void CheckStrlcpycatArguments(const CallExpr *Call,
12406                                 IdentifierInfo *FnName);
12407 
12408   void CheckStrncatArguments(const CallExpr *Call,
12409                              IdentifierInfo *FnName);
12410 
12411   void CheckFreeArguments(const CallExpr *E);
12412 
12413   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
12414                           SourceLocation ReturnLoc,
12415                           bool isObjCMethod = false,
12416                           const AttrVec *Attrs = nullptr,
12417                           const FunctionDecl *FD = nullptr);
12418 
12419 public:
12420   void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
12421 
12422 private:
12423   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
12424   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
12425   void CheckForIntOverflow(Expr *E);
12426   void CheckUnsequencedOperations(const Expr *E);
12427 
12428   /// Perform semantic checks on a completed expression. This will either
12429   /// be a full-expression or a default argument expression.
12430   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
12431                           bool IsConstexpr = false);
12432 
12433   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
12434                                    Expr *Init);
12435 
12436   /// Check if there is a field shadowing.
12437   void CheckShadowInheritedFields(const SourceLocation &Loc,
12438                                   DeclarationName FieldName,
12439                                   const CXXRecordDecl *RD,
12440                                   bool DeclIsField = true);
12441 
12442   /// Check if the given expression contains 'break' or 'continue'
12443   /// statement that produces control flow different from GCC.
12444   void CheckBreakContinueBinding(Expr *E);
12445 
12446   /// Check whether receiver is mutable ObjC container which
12447   /// attempts to add itself into the container
12448   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
12449 
12450   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
12451   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
12452                                  bool DeleteWasArrayForm);
12453 public:
12454   /// Register a magic integral constant to be used as a type tag.
12455   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12456                                   uint64_t MagicValue, QualType Type,
12457                                   bool LayoutCompatible, bool MustBeNull);
12458 
12459   struct TypeTagData {
TypeTagDataTypeTagData12460     TypeTagData() {}
12461 
TypeTagDataTypeTagData12462     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
12463         Type(Type), LayoutCompatible(LayoutCompatible),
12464         MustBeNull(MustBeNull)
12465     {}
12466 
12467     QualType Type;
12468 
12469     /// If true, \c Type should be compared with other expression's types for
12470     /// layout-compatibility.
12471     unsigned LayoutCompatible : 1;
12472     unsigned MustBeNull : 1;
12473   };
12474 
12475   /// A pair of ArgumentKind identifier and magic value.  This uniquely
12476   /// identifies the magic value.
12477   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
12478 
12479 private:
12480   /// A map from magic value to type information.
12481   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
12482       TypeTagForDatatypeMagicValues;
12483 
12484   /// Peform checks on a call of a function with argument_with_type_tag
12485   /// or pointer_with_type_tag attributes.
12486   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12487                                 const ArrayRef<const Expr *> ExprArgs,
12488                                 SourceLocation CallSiteLoc);
12489 
12490   /// Check if we are taking the address of a packed field
12491   /// as this may be a problem if the pointer value is dereferenced.
12492   void CheckAddressOfPackedMember(Expr *rhs);
12493 
12494   /// The parser's current scope.
12495   ///
12496   /// The parser maintains this state here.
12497   Scope *CurScope;
12498 
12499   mutable IdentifierInfo *Ident_super;
12500   mutable IdentifierInfo *Ident___float128;
12501 
12502   /// Nullability type specifiers.
12503   IdentifierInfo *Ident__Nonnull = nullptr;
12504   IdentifierInfo *Ident__Nullable = nullptr;
12505   IdentifierInfo *Ident__Null_unspecified = nullptr;
12506 
12507   IdentifierInfo *Ident_NSError = nullptr;
12508 
12509   /// The handler for the FileChanged preprocessor events.
12510   ///
12511   /// Used for diagnostics that implement custom semantic analysis for #include
12512   /// directives, like -Wpragma-pack.
12513   sema::SemaPPCallbacks *SemaPPCallbackHandler;
12514 
12515 protected:
12516   friend class Parser;
12517   friend class InitializationSequence;
12518   friend class ASTReader;
12519   friend class ASTDeclReader;
12520   friend class ASTWriter;
12521 
12522 public:
12523   /// Retrieve the keyword associated
12524   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
12525 
12526   /// The struct behind the CFErrorRef pointer.
12527   RecordDecl *CFError = nullptr;
12528   bool isCFError(RecordDecl *D);
12529 
12530   /// Retrieve the identifier "NSError".
12531   IdentifierInfo *getNSErrorIdent();
12532 
12533   /// Retrieve the parser's current scope.
12534   ///
12535   /// This routine must only be used when it is certain that semantic analysis
12536   /// and the parser are in precisely the same context, which is not the case
12537   /// when, e.g., we are performing any kind of template instantiation.
12538   /// Therefore, the only safe places to use this scope are in the parser
12539   /// itself and in routines directly invoked from the parser and *never* from
12540   /// template substitution or instantiation.
getCurScope()12541   Scope *getCurScope() const { return CurScope; }
12542 
incrementMSManglingNumber()12543   void incrementMSManglingNumber() const {
12544     return CurScope->incrementMSManglingNumber();
12545   }
12546 
12547   IdentifierInfo *getSuperIdentifier() const;
12548   IdentifierInfo *getFloat128Identifier() const;
12549 
12550   Decl *getObjCDeclContext() const;
12551 
getCurLexicalContext()12552   DeclContext *getCurLexicalContext() const {
12553     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
12554   }
12555 
getCurObjCLexicalContext()12556   const DeclContext *getCurObjCLexicalContext() const {
12557     const DeclContext *DC = getCurLexicalContext();
12558     // A category implicitly has the attribute of the interface.
12559     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
12560       DC = CatD->getClassInterface();
12561     return DC;
12562   }
12563 
12564   /// Determine the number of levels of enclosing template parameters. This is
12565   /// only usable while parsing. Note that this does not include dependent
12566   /// contexts in which no template parameters have yet been declared, such as
12567   /// in a terse function template or generic lambda before the first 'auto' is
12568   /// encountered.
12569   unsigned getTemplateDepth(Scope *S) const;
12570 
12571   /// To be used for checking whether the arguments being passed to
12572   /// function exceeds the number of parameters expected for it.
12573   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
12574                                bool PartialOverloading = false) {
12575     // We check whether we're just after a comma in code-completion.
12576     if (NumArgs > 0 && PartialOverloading)
12577       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
12578     return NumArgs > NumParams;
12579   }
12580 
12581   // Emitting members of dllexported classes is delayed until the class
12582   // (including field initializers) is fully parsed.
12583   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
12584   SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
12585 
12586 private:
12587   int ParsingClassDepth = 0;
12588 
12589   class SavePendingParsedClassStateRAII {
12590   public:
SavePendingParsedClassStateRAII(Sema & S)12591     SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
12592 
~SavePendingParsedClassStateRAII()12593     ~SavePendingParsedClassStateRAII() {
12594       assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
12595              "there shouldn't be any pending delayed exception spec checks");
12596       assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
12597              "there shouldn't be any pending delayed exception spec checks");
12598       swapSavedState();
12599     }
12600 
12601   private:
12602     Sema &S;
12603     decltype(DelayedOverridingExceptionSpecChecks)
12604         SavedOverridingExceptionSpecChecks;
12605     decltype(DelayedEquivalentExceptionSpecChecks)
12606         SavedEquivalentExceptionSpecChecks;
12607 
swapSavedState()12608     void swapSavedState() {
12609       SavedOverridingExceptionSpecChecks.swap(
12610           S.DelayedOverridingExceptionSpecChecks);
12611       SavedEquivalentExceptionSpecChecks.swap(
12612           S.DelayedEquivalentExceptionSpecChecks);
12613     }
12614   };
12615 
12616   /// Helper class that collects misaligned member designations and
12617   /// their location info for delayed diagnostics.
12618   struct MisalignedMember {
12619     Expr *E;
12620     RecordDecl *RD;
12621     ValueDecl *MD;
12622     CharUnits Alignment;
12623 
MisalignedMemberMisalignedMember12624     MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMemberMisalignedMember12625     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
12626                      CharUnits Alignment)
12627         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
MisalignedMemberMisalignedMember12628     explicit MisalignedMember(Expr *E)
12629         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
12630 
12631     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
12632   };
12633   /// Small set of gathered accesses to potentially misaligned members
12634   /// due to the packed attribute.
12635   SmallVector<MisalignedMember, 4> MisalignedMembers;
12636 
12637   /// Adds an expression to the set of gathered misaligned members.
12638   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12639                                      CharUnits Alignment);
12640 
12641 public:
12642   /// Diagnoses the current set of gathered accesses. This typically
12643   /// happens at full expression level. The set is cleared after emitting the
12644   /// diagnostics.
12645   void DiagnoseMisalignedMembers();
12646 
12647   /// This function checks if the expression is in the sef of potentially
12648   /// misaligned members and it is converted to some pointer type T with lower
12649   /// or equal alignment requirements. If so it removes it. This is used when
12650   /// we do not want to diagnose such misaligned access (e.g. in conversions to
12651   /// void*).
12652   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
12653 
12654   /// This function calls Action when it determines that E designates a
12655   /// misaligned member due to the packed attribute. This is used to emit
12656   /// local diagnostics like in reference binding.
12657   void RefersToMemberWithReducedAlignment(
12658       Expr *E,
12659       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12660           Action);
12661 
12662   /// Describes the reason a calling convention specification was ignored, used
12663   /// for diagnostics.
12664   enum class CallingConventionIgnoredReason {
12665     ForThisTarget = 0,
12666     VariadicFunction,
12667     ConstructorDestructor,
12668     BuiltinFunction
12669   };
12670   /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12671   /// context is "used as device code".
12672   ///
12673   /// - If CurLexicalContext is a kernel function or it is known that the
12674   ///   function will be emitted for the device, emits the diagnostics
12675   ///   immediately.
12676   /// - If CurLexicalContext is a function and we are compiling
12677   ///   for the device, but we don't know that this function will be codegen'ed
12678   ///   for devive yet, creates a diagnostic which is emitted if and when we
12679   ///   realize that the function will be codegen'ed.
12680   ///
12681   /// Example usage:
12682   ///
12683   /// Diagnose __float128 type usage only from SYCL device code if the current
12684   /// target doesn't support it
12685   /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
12686   ///     S.getLangOpts().SYCLIsDevice)
12687   ///   SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
12688   SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
12689                                              unsigned DiagID);
12690 
12691   /// Check whether we're allowed to call Callee from the current context.
12692   ///
12693   /// - If the call is never allowed in a semantically-correct program
12694   ///   emits an error and returns false.
12695   ///
12696   /// - If the call is allowed in semantically-correct programs, but only if
12697   ///   it's never codegen'ed, creates a deferred diagnostic to be emitted if
12698   ///   and when the caller is codegen'ed, and returns true.
12699   ///
12700   /// - Otherwise, returns true without emitting any diagnostics.
12701   ///
12702   /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
12703   /// codegen'ed yet.
12704   bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
12705 };
12706 
12707 /// RAII object that enters a new expression evaluation context.
12708 class EnterExpressionEvaluationContext {
12709   Sema &Actions;
12710   bool Entered = true;
12711 
12712 public:
12713   EnterExpressionEvaluationContext(
12714       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12715       Decl *LambdaContextDecl = nullptr,
12716       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12717           Sema::ExpressionEvaluationContextRecord::EK_Other,
12718       bool ShouldEnter = true)
Actions(Actions)12719       : Actions(Actions), Entered(ShouldEnter) {
12720     if (Entered)
12721       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
12722                                               ExprContext);
12723   }
12724   EnterExpressionEvaluationContext(
12725       Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
12726       Sema::ReuseLambdaContextDecl_t,
12727       Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
12728           Sema::ExpressionEvaluationContextRecord::EK_Other)
Actions(Actions)12729       : Actions(Actions) {
12730     Actions.PushExpressionEvaluationContext(
12731         NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
12732   }
12733 
12734   enum InitListTag { InitList };
12735   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
12736                                    bool ShouldEnter = true)
Actions(Actions)12737       : Actions(Actions), Entered(false) {
12738     // In C++11 onwards, narrowing checks are performed on the contents of
12739     // braced-init-lists, even when they occur within unevaluated operands.
12740     // Therefore we still need to instantiate constexpr functions used in such
12741     // a context.
12742     if (ShouldEnter && Actions.isUnevaluatedContext() &&
12743         Actions.getLangOpts().CPlusPlus11) {
12744       Actions.PushExpressionEvaluationContext(
12745           Sema::ExpressionEvaluationContext::UnevaluatedList);
12746       Entered = true;
12747     }
12748   }
12749 
~EnterExpressionEvaluationContext()12750   ~EnterExpressionEvaluationContext() {
12751     if (Entered)
12752       Actions.PopExpressionEvaluationContext();
12753   }
12754 };
12755 
12756 DeductionFailureInfo
12757 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
12758                          sema::TemplateDeductionInfo &Info);
12759 
12760 /// Contains a late templated function.
12761 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
12762 struct LateParsedTemplate {
12763   CachedTokens Toks;
12764   /// The template function declaration to be late parsed.
12765   Decl *D;
12766 };
12767 } // end namespace clang
12768 
12769 namespace llvm {
12770 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
12771 // SourceLocation.
12772 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
12773   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
12774   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
12775 
12776   static FunctionDeclAndLoc getEmptyKey() {
12777     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
12778   }
12779 
12780   static FunctionDeclAndLoc getTombstoneKey() {
12781     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
12782   }
12783 
12784   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
12785     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
12786                         FDL.Loc.getHashValue());
12787   }
12788 
12789   static bool isEqual(const FunctionDeclAndLoc &LHS,
12790                       const FunctionDeclAndLoc &RHS) {
12791     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
12792   }
12793 };
12794 } // namespace llvm
12795 
12796 #endif
12797