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