1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the Sema class, which performs semantic analysis and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SEMA_H
16 #define LLVM_CLANG_SEMA_SEMA_H
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Availability.h"
20 #include "clang/AST/DeclarationName.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExternalASTSource.h"
25 #include "clang/AST/LocInfoType.h"
26 #include "clang/AST/MangleNumberingContext.h"
27 #include "clang/AST/NSAPI.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/AST/TypeOrdering.h"
32 #include "clang/Basic/ExpressionTraits.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/Module.h"
35 #include "clang/Basic/OpenMPKinds.h"
36 #include "clang/Basic/PragmaKinds.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TemplateKinds.h"
39 #include "clang/Basic/TypeTraits.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/CleanupInfo.h"
42 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/ExternalSemaSource.h"
44 #include "clang/Sema/IdentifierResolver.h"
45 #include "clang/Sema/ObjCMethodList.h"
46 #include "clang/Sema/Ownership.h"
47 #include "clang/Sema/Scope.h"
48 #include "clang/Sema/ScopeInfo.h"
49 #include "clang/Sema/TypoCorrection.h"
50 #include "clang/Sema/Weak.h"
51 #include "llvm/ADT/ArrayRef.h"
52 #include "llvm/ADT/Optional.h"
53 #include "llvm/ADT/SetVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/TinyPtrVector.h"
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
67 class InlineAsmIdentifierInfo;
74 class ASTMutationListener;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
107 class DeclAccessPair;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
116 class EnumConstantDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
134 class LocalInstantiationScope;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
139 class MultiLevelTemplateArgumentList;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
167 class StandardConversionSequence;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
175 class TemplateParameterList;
176 class TemplatePartialOrderingContext;
177 class TemplateTemplateParmDecl;
181 class TypedefNameDecl;
183 class TypoCorrectionConsumer;
185 class UnresolvedLookupExpr;
186 class UnresolvedMemberExpr;
187 class UnresolvedSetImpl;
188 class UnresolvedSetIterator;
190 class UsingShadowDecl;
193 class VarTemplateSpecializationDecl;
194 class VisibilityAttr;
195 class VisibleDeclConsumer;
196 class IndirectFieldDecl;
197 struct DeductionFailureInfo;
198 class TemplateSpecCandidateSet;
201 class AccessedEntity;
202 class BlockScopeInfo;
203 class CapturedRegionScopeInfo;
204 class CapturingScopeInfo;
205 class CompoundScopeInfo;
206 class DelayedDiagnostic;
207 class DelayedDiagnosticPool;
208 class FunctionScopeInfo;
209 class LambdaScopeInfo;
210 class PossiblyUnreachableDiag;
211 class TemplateDeductionInfo;
214 namespace threadSafety {
216 void threadSafetyCleanup(BeforeSet* Cache);
219 // FIXME: No way to easily map from TemplateTypeParmTypes to
220 // TemplateTypeParmDecls, so we have this horrible PointerUnion.
221 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
222 SourceLocation> UnexpandedParameterPack;
224 /// Describes whether we've seen any nullability information for the given
226 struct FileNullability {
227 /// The first pointer declarator (of any pointer kind) in the file that does
228 /// not have a corresponding nullability annotation.
229 SourceLocation PointerLoc;
231 /// Which kind of pointer declarator we saw.
234 /// Whether we saw any type nullability annotations in the given file.
235 bool SawTypeNullability = false;
238 /// A mapping from file IDs to a record of whether we've seen nullability
239 /// information in that file.
240 class FileNullabilityMap {
241 /// A mapping from file IDs to the nullability information for each file ID.
242 llvm::DenseMap<FileID, FileNullability> Map;
244 /// A single-element cache based on the file ID.
247 FileNullability Nullability;
251 FileNullability &operator[](FileID file) {
252 // Check the single-element cache.
253 if (file == Cache.File)
254 return Cache.Nullability;
256 // It's not in the single-element cache; flush the cache if we have one.
257 if (!Cache.File.isInvalid()) {
258 Map[Cache.File] = Cache.Nullability;
261 // Pull this entry into the cache.
263 Cache.Nullability = Map[file];
264 return Cache.Nullability;
268 /// Sema - This implements semantic analysis and AST building for C.
270 Sema(const Sema &) = delete;
271 void operator=(const Sema &) = delete;
273 ///\brief Source of additional semantic information.
274 ExternalSemaSource *ExternalSource;
276 ///\brief Whether Sema has generated a multiplexer and has to delete it.
277 bool isMultiplexExternalSource;
279 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
281 bool isVisibleSlow(const NamedDecl *D);
283 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
284 const NamedDecl *New) {
285 // We are about to link these. It is now safe to compute the linkage of
286 // the new decl. If the new decl has external linkage, we will
287 // link it with the hidden decl (which also has external linkage) and
288 // it will keep having external linkage. If it has internal linkage, we
289 // will not link it. Since it has no previous decls, it will remain
290 // with internal linkage.
291 return isVisible(Old) || New->isExternallyVisible();
293 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
296 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
297 typedef OpaquePtr<TemplateName> TemplateTy;
298 typedef OpaquePtr<QualType> TypeTy;
300 OpenCLOptions OpenCLFeatures;
301 FPOptions FPFeatures;
303 const LangOptions &LangOpts;
306 ASTConsumer &Consumer;
307 DiagnosticsEngine &Diags;
308 SourceManager &SourceMgr;
310 /// \brief Flag indicating whether or not to collect detailed statistics.
313 /// \brief Code-completion consumer.
314 CodeCompleteConsumer *CodeCompleter;
316 /// CurContext - This is the current declaration context of parsing.
317 DeclContext *CurContext;
319 /// \brief Generally null except when we temporarily switch decl contexts,
320 /// like in \see ActOnObjCTemporaryExitContainerContext.
321 DeclContext *OriginalLexicalContext;
323 /// VAListTagName - The declaration name corresponding to __va_list_tag.
324 /// This is used as part of a hack to omit that class from ADL results.
325 DeclarationName VAListTagName;
327 bool MSStructPragmaOn; // True when \#pragma ms_struct on
329 /// \brief Controls member pointer representation format under the MS ABI.
330 LangOptions::PragmaMSPointersToMembersKind
331 MSPointerToMemberRepresentationMethod;
333 /// Stack of active SEH __finally scopes. Can be empty.
334 SmallVector<Scope*, 2> CurrentSEHFinally;
336 /// \brief Source location for newly created implicit MSInheritanceAttrs
337 SourceLocation ImplicitMSInheritanceAttrLoc;
339 enum PragmaMsStackAction {
340 PSK_Reset = 0x0, // #pragma ()
341 PSK_Set = 0x1, // #pragma (value)
342 PSK_Push = 0x2, // #pragma (push[, id])
343 PSK_Pop = 0x4, // #pragma (pop[, id])
344 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
345 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
346 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
349 template<typename ValueType>
352 llvm::StringRef StackSlotLabel;
354 SourceLocation PragmaLocation;
355 Slot(llvm::StringRef StackSlotLabel,
357 SourceLocation PragmaLocation)
358 : StackSlotLabel(StackSlotLabel), Value(Value),
359 PragmaLocation(PragmaLocation) {}
361 void Act(SourceLocation PragmaLocation,
362 PragmaMsStackAction Action,
363 llvm::StringRef StackSlotLabel,
366 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
367 // method body to restore the stacks on exit, so it works like this:
370 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
372 // #pragma <name>(pop, InternalPragmaSlot)
375 // It works even with #pragma vtordisp, although MSVC doesn't support
376 // #pragma vtordisp(push [, id], n)
379 // Push / pop a named sentinel slot.
380 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
381 assert((Action == PSK_Push || Action == PSK_Pop) &&
382 "Can only push / pop #pragma stack sentinels!");
383 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
387 explicit PragmaStack(const ValueType &Default)
388 : DefaultValue(Default), CurrentValue(Default) {}
390 SmallVector<Slot, 2> Stack;
391 ValueType DefaultValue; // Value used for PSK_Reset action.
392 ValueType CurrentValue;
393 SourceLocation CurrentPragmaLocation;
395 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
396 // we shouldn't do so if they're in a module).
398 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
399 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
401 /// 0: Suppress all vtordisps
402 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
404 /// 2: Always insert vtordisps to support RTTI on partially constructed
406 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
408 // Sentinel to represent when the stack is set to mac68k alignment.
409 static const unsigned kMac68kAlignmentSentinel = ~0U;
410 PragmaStack<unsigned> PackStack;
412 PragmaStack<StringLiteral *> DataSegStack;
413 PragmaStack<StringLiteral *> BSSSegStack;
414 PragmaStack<StringLiteral *> ConstSegStack;
415 PragmaStack<StringLiteral *> CodeSegStack;
417 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
418 // Actions should be performed only if we enter / exit a C++ method body.
419 class PragmaStackSentinelRAII {
421 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
422 ~PragmaStackSentinelRAII();
430 /// A mapping that describes the nullability we've seen in each header file.
431 FileNullabilityMap NullabilityMap;
433 /// Last section used with #pragma init_seg.
434 StringLiteral *CurInitSeg;
435 SourceLocation CurInitSegLoc;
437 /// VisContext - Manages the stack for \#pragma GCC visibility.
438 void *VisContext; // Really a "PragmaVisStack*"
440 /// \brief This represents the stack of attributes that were pushed by
441 /// \#pragma clang attribute.
442 struct PragmaAttributeEntry {
444 AttributeList *Attribute;
445 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
448 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
450 /// \brief The declaration that is currently receiving an attribute from the
451 /// #pragma attribute stack.
452 const Decl *PragmaAttributeCurrentTargetDecl;
454 /// \brief This represents the last location of a "#pragma clang optimize off"
455 /// directive if such a directive has not been closed by an "on" yet. If
456 /// optimizations are currently "on", this is set to an invalid location.
457 SourceLocation OptimizeOffPragmaLocation;
459 /// \brief Flag indicating if Sema is building a recovery call expression.
461 /// This flag is used to avoid building recovery call expressions
462 /// if Sema is already doing so, which would cause infinite recursions.
463 bool IsBuildingRecoveryCallExpr;
465 /// Used to control the generation of ExprWithCleanups.
468 /// ExprCleanupObjects - This is the stack of objects requiring
469 /// cleanup that are created by the current full expression. The
470 /// element type here is ExprWithCleanups::Object.
471 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
473 /// \brief Store a list of either DeclRefExprs or MemberExprs
474 /// that contain a reference to a variable (constant) that may or may not
475 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
476 /// and discarded value conversions have been applied to all subexpressions
477 /// of the enclosing full expression. This is cleared at the end of each
479 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
481 /// \brief Stack containing information about each of the nested
482 /// function, block, and method scopes that are currently active.
484 /// This array is never empty. Clients should ignore the first
485 /// element, which is used to cache a single FunctionScopeInfo
486 /// that's used to parse every top-level function.
487 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
489 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
490 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
493 /// ExtVectorDecls - This is a list all the extended vector types. This allows
494 /// us to associate a raw vector type with one of the ext_vector type names.
495 /// This is only necessary for issuing pretty diagnostics.
496 ExtVectorDeclsType ExtVectorDecls;
498 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
499 std::unique_ptr<CXXFieldCollector> FieldCollector;
501 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
503 /// \brief Set containing all declared private fields that are not used.
504 NamedDeclSetType UnusedPrivateFields;
506 /// \brief Set containing all typedefs that are likely unused.
507 llvm::SmallSetVector<const TypedefNameDecl *, 4>
508 UnusedLocalTypedefNameCandidates;
510 /// \brief Delete-expressions to be analyzed at the end of translation unit
512 /// This list contains class members, and locations of delete-expressions
513 /// that could not be proven as to whether they mismatch with new-expression
514 /// used in initializer of the field.
515 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
516 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
517 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
519 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
521 /// PureVirtualClassDiagSet - a set of class declarations which we have
522 /// emitted a list of pure virtual functions. Used to prevent emitting the
523 /// same list more than once.
524 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
526 /// ParsingInitForAutoVars - a set of declarations with auto types for which
527 /// we are currently parsing the initializer.
528 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
530 /// \brief Look for a locally scoped extern "C" declaration by the given name.
531 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
533 typedef LazyVector<VarDecl *, ExternalSemaSource,
534 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
535 TentativeDefinitionsType;
537 /// \brief All the tentative definitions encountered in the TU.
538 TentativeDefinitionsType TentativeDefinitions;
540 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
541 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
542 UnusedFileScopedDeclsType;
544 /// \brief The set of file scoped decls seen so far that have not been used
545 /// and must warn if not used. Only contains the first declaration.
546 UnusedFileScopedDeclsType UnusedFileScopedDecls;
548 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
549 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
550 DelegatingCtorDeclsType;
552 /// \brief All the delegating constructors seen so far in the file, used for
553 /// cycle detection at the end of the TU.
554 DelegatingCtorDeclsType DelegatingCtorDecls;
556 /// \brief All the overriding functions seen during a class definition
557 /// that had their exception spec checks delayed, plus the overridden
559 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
560 DelayedExceptionSpecChecks;
562 /// \brief All the members seen during a class definition which were both
563 /// explicitly defaulted and had explicitly-specified exception
564 /// specifications, along with the function type containing their
565 /// user-specified exception specification. Those exception specifications
566 /// were overridden with the default specifications, but we still need to
567 /// check whether they are compatible with the default specification, and
568 /// we can't do that until the nesting set of class definitions is complete.
569 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
570 DelayedDefaultedMemberExceptionSpecs;
572 typedef llvm::MapVector<const FunctionDecl *,
573 std::unique_ptr<LateParsedTemplate>>
574 LateParsedTemplateMapT;
575 LateParsedTemplateMapT LateParsedTemplateMap;
577 /// \brief Callback to the parser to parse templated functions when needed.
578 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
579 typedef void LateTemplateParserCleanupCB(void *P);
580 LateTemplateParserCB *LateTemplateParser;
581 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
584 void SetLateTemplateParser(LateTemplateParserCB *LTP,
585 LateTemplateParserCleanupCB *LTPCleanup,
587 LateTemplateParser = LTP;
588 LateTemplateParserCleanup = LTPCleanup;
592 class DelayedDiagnostics;
594 class DelayedDiagnosticsState {
595 sema::DelayedDiagnosticPool *SavedPool;
596 friend class Sema::DelayedDiagnostics;
598 typedef DelayedDiagnosticsState ParsingDeclState;
599 typedef DelayedDiagnosticsState ProcessingContextState;
601 /// A class which encapsulates the logic for delaying diagnostics
602 /// during parsing and other processing.
603 class DelayedDiagnostics {
604 /// \brief The current pool of diagnostics into which delayed
605 /// diagnostics should go.
606 sema::DelayedDiagnosticPool *CurPool;
609 DelayedDiagnostics() : CurPool(nullptr) {}
611 /// Adds a delayed diagnostic.
612 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
614 /// Determines whether diagnostics should be delayed.
615 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
617 /// Returns the current delayed-diagnostics pool.
618 sema::DelayedDiagnosticPool *getCurrentPool() const {
622 /// Enter a new scope. Access and deprecation diagnostics will be
623 /// collected in this pool.
624 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
625 DelayedDiagnosticsState state;
626 state.SavedPool = CurPool;
631 /// Leave a delayed-diagnostic state that was previously pushed.
632 /// Do not emit any of the diagnostics. This is performed as part
633 /// of the bookkeeping of popping a pool "properly".
634 void popWithoutEmitting(DelayedDiagnosticsState state) {
635 CurPool = state.SavedPool;
638 /// Enter a new scope where access and deprecation diagnostics are
640 DelayedDiagnosticsState pushUndelayed() {
641 DelayedDiagnosticsState state;
642 state.SavedPool = CurPool;
647 /// Undo a previous pushUndelayed().
648 void popUndelayed(DelayedDiagnosticsState state) {
649 assert(CurPool == nullptr);
650 CurPool = state.SavedPool;
652 } DelayedDiagnostics;
654 /// A RAII object to temporarily push a declaration context.
658 DeclContext *SavedContext;
659 ProcessingContextState SavedContextState;
660 QualType SavedCXXThisTypeOverride;
663 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
664 : S(S), SavedContext(S.CurContext),
665 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
666 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
668 assert(ContextToPush && "pushing null context");
669 S.CurContext = ContextToPush;
671 S.CXXThisTypeOverride = QualType();
675 if (!SavedContext) return;
676 S.CurContext = SavedContext;
677 S.DelayedDiagnostics.popUndelayed(SavedContextState);
678 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
679 SavedContext = nullptr;
687 /// \brief RAII object to handle the state changes required to synthesize
689 class SynthesizedFunctionScope {
691 Sema::ContextRAII SavedContext;
694 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
695 : S(S), SavedContext(S, DC)
697 S.PushFunctionScope();
698 S.PushExpressionEvaluationContext(
699 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
702 ~SynthesizedFunctionScope() {
703 S.PopExpressionEvaluationContext();
704 S.PopFunctionScopeInfo();
708 /// WeakUndeclaredIdentifiers - Identifiers contained in
709 /// \#pragma weak before declared. rare. may alias another
710 /// identifier, declared or undeclared
711 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
713 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
714 /// \#pragma redefine_extname before declared. Used in Solaris system headers
715 /// to define functions that occur in multiple standards to call the version
716 /// in the currently selected standard.
717 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
720 /// \brief Load weak undeclared identifiers from the external source.
721 void LoadExternalWeakUndeclaredIdentifiers();
723 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
724 /// \#pragma weak during processing of other Decls.
725 /// I couldn't figure out a clean way to generate these in-line, so
726 /// we store them here and handle separately -- which is a hack.
727 /// It would be best to refactor this.
728 SmallVector<Decl*,2> WeakTopLevelDecl;
730 IdentifierResolver IdResolver;
732 /// Translation Unit Scope - useful to Objective-C actions that need
733 /// to lookup file scope declarations in the "ordinary" C decl namespace.
734 /// For example, user-defined classes, built-in "id" type, etc.
737 /// \brief The C++ "std" namespace, where the standard library resides.
738 LazyDeclPtr StdNamespace;
740 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
741 /// standard library.
742 LazyDeclPtr StdBadAlloc;
744 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
745 /// standard library.
746 LazyDeclPtr StdAlignValT;
748 /// \brief The C++ "std::experimental" namespace, where the experimental parts
749 /// of the standard library resides.
750 NamespaceDecl *StdExperimentalNamespaceCache;
752 /// \brief The C++ "std::initializer_list" template, which is defined in
753 /// \<initializer_list>.
754 ClassTemplateDecl *StdInitializerList;
756 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
757 RecordDecl *CXXTypeInfoDecl;
759 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
760 RecordDecl *MSVCGuidDecl;
762 /// \brief Caches identifiers/selectors for NSFoundation APIs.
763 std::unique_ptr<NSAPI> NSAPIObj;
765 /// \brief The declaration of the Objective-C NSNumber class.
766 ObjCInterfaceDecl *NSNumberDecl;
768 /// \brief The declaration of the Objective-C NSValue class.
769 ObjCInterfaceDecl *NSValueDecl;
771 /// \brief Pointer to NSNumber type (NSNumber *).
772 QualType NSNumberPointer;
774 /// \brief Pointer to NSValue type (NSValue *).
775 QualType NSValuePointer;
777 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
778 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
780 /// \brief The declaration of the Objective-C NSString class.
781 ObjCInterfaceDecl *NSStringDecl;
783 /// \brief Pointer to NSString type (NSString *).
784 QualType NSStringPointer;
786 /// \brief The declaration of the stringWithUTF8String: method.
787 ObjCMethodDecl *StringWithUTF8StringMethod;
789 /// \brief The declaration of the valueWithBytes:objCType: method.
790 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
792 /// \brief The declaration of the Objective-C NSArray class.
793 ObjCInterfaceDecl *NSArrayDecl;
795 /// \brief The declaration of the arrayWithObjects:count: method.
796 ObjCMethodDecl *ArrayWithObjectsMethod;
798 /// \brief The declaration of the Objective-C NSDictionary class.
799 ObjCInterfaceDecl *NSDictionaryDecl;
801 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
802 ObjCMethodDecl *DictionaryWithObjectsMethod;
804 /// \brief id<NSCopying> type.
805 QualType QIDNSCopying;
807 /// \brief will hold 'respondsToSelector:'
808 Selector RespondsToSelectorSel;
810 /// A flag to remember whether the implicit forms of operator new and delete
811 /// have been declared.
812 bool GlobalNewDeleteDeclared;
814 /// A flag to indicate that we're in a context that permits abstract
815 /// references to fields. This is really a
816 bool AllowAbstractFieldReference;
818 /// \brief Describes how the expressions currently being parsed are
819 /// evaluated at run-time, if at all.
820 enum class ExpressionEvaluationContext {
821 /// \brief The current expression and its subexpressions occur within an
822 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
823 /// \c sizeof, where the type of the expression may be significant but
824 /// no code will be generated to evaluate the value of the expression at
828 /// \brief The current expression occurs within a braced-init-list within
829 /// an unevaluated operand. This is mostly like a regular unevaluated
830 /// context, except that we still instantiate constexpr functions that are
831 /// referenced here so that we can perform narrowing checks correctly.
834 /// \brief The current expression occurs within a discarded statement.
835 /// This behaves largely similarly to an unevaluated operand in preventing
836 /// definitions from being required, but not in other ways.
839 /// \brief The current expression occurs within an unevaluated
840 /// operand that unconditionally permits abstract references to
841 /// fields, such as a SIZE operator in MS-style inline assembly.
844 /// \brief The current context is "potentially evaluated" in C++11 terms,
845 /// but the expression is evaluated at compile-time (like the values of
846 /// cases in a switch statement).
849 /// \brief The current expression is potentially evaluated at run time,
850 /// which means that code may be generated to evaluate the value of the
851 /// expression at run time.
852 PotentiallyEvaluated,
854 /// \brief The current expression is potentially evaluated, but any
855 /// declarations referenced inside that expression are only used if
856 /// in fact the current expression is used.
858 /// This value is used when parsing default function arguments, for which
859 /// we would like to provide diagnostics (e.g., passing non-POD arguments
860 /// through varargs) but do not want to mark declarations as "referenced"
861 /// until the default argument is used.
862 PotentiallyEvaluatedIfUsed
865 /// \brief Data structure used to record current or nested
866 /// expression evaluation contexts.
867 struct ExpressionEvaluationContextRecord {
868 /// \brief The expression evaluation context.
869 ExpressionEvaluationContext Context;
871 /// \brief Whether the enclosing context needed a cleanup.
872 CleanupInfo ParentCleanup;
874 /// \brief Whether we are in a decltype expression.
877 /// \brief The number of active cleanup objects when we entered
878 /// this expression evaluation context.
879 unsigned NumCleanupObjects;
881 /// \brief The number of typos encountered during this expression evaluation
882 /// context (i.e. the number of TypoExprs created).
885 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
887 /// \brief The lambdas that are present within this context, if it
888 /// is indeed an unevaluated context.
889 SmallVector<LambdaExpr *, 2> Lambdas;
891 /// \brief The declaration that provides context for lambda expressions
892 /// and block literals if the normal declaration context does not
893 /// suffice, e.g., in a default function argument.
894 Decl *ManglingContextDecl;
896 /// \brief The context information used to mangle lambda expressions
897 /// and block literals within this context.
899 /// This mangling information is allocated lazily, since most contexts
900 /// do not have lambda expressions or block literals.
901 std::unique_ptr<MangleNumberingContext> MangleNumbering;
903 /// \brief If we are processing a decltype type, a set of call expressions
904 /// for which we have deferred checking the completeness of the return type.
905 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
907 /// \brief If we are processing a decltype type, a set of temporary binding
908 /// expressions for which we have deferred checking the destructor.
909 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
911 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
912 unsigned NumCleanupObjects,
913 CleanupInfo ParentCleanup,
914 Decl *ManglingContextDecl,
916 : Context(Context), ParentCleanup(ParentCleanup),
917 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
919 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
921 /// \brief Retrieve the mangling numbering context, used to consistently
922 /// number constructs like lambdas for mangling.
923 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
925 bool isUnevaluated() const {
926 return Context == ExpressionEvaluationContext::Unevaluated ||
927 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
928 Context == ExpressionEvaluationContext::UnevaluatedList;
930 bool isConstantEvaluated() const {
931 return Context == ExpressionEvaluationContext::ConstantEvaluated;
935 /// A stack of expression evaluation contexts.
936 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
938 /// \brief Compute the mangling number context for a lambda expression or
941 /// \param DC - The DeclContext containing the lambda expression or
943 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
944 /// associated with the context, if relevant.
945 MangleNumberingContext *getCurrentMangleNumberContext(
946 const DeclContext *DC,
947 Decl *&ManglingContextDecl);
950 /// SpecialMemberOverloadResult - The overloading result for a special member
953 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
954 /// integer are used to determine whether overload resolution succeeded.
955 class SpecialMemberOverloadResult {
964 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
967 SpecialMemberOverloadResult() : Pair() {}
968 SpecialMemberOverloadResult(CXXMethodDecl *MD)
969 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
971 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
972 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
974 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
975 void setKind(Kind K) { Pair.setInt(K); }
978 class SpecialMemberOverloadResultEntry
979 : public llvm::FastFoldingSetNode,
980 public SpecialMemberOverloadResult {
982 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
983 : FastFoldingSetNode(ID)
987 /// \brief A cache of special member function overload resolution results
989 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
991 /// \brief A cache of the flags available in enumerations with the flag_bits
993 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
995 /// \brief The kind of translation unit we are processing.
997 /// When we're processing a complete translation unit, Sema will perform
998 /// end-of-translation-unit semantic tasks (such as creating
999 /// initializers for tentative definitions in C) once parsing has
1000 /// completed. Modules and precompiled headers perform different kinds of
1002 TranslationUnitKind TUKind;
1004 llvm::BumpPtrAllocator BumpAlloc;
1006 /// \brief The number of SFINAE diagnostics that have been trapped.
1007 unsigned NumSFINAEErrors;
1009 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1010 UnparsedDefaultArgInstantiationsMap;
1012 /// \brief A mapping from parameters with unparsed default arguments to the
1013 /// set of instantiations of each parameter.
1015 /// This mapping is a temporary data structure used when parsing
1016 /// nested class templates or nested classes of class templates,
1017 /// where we might end up instantiating an inner class before the
1018 /// default arguments of its methods have been parsed.
1019 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1021 // Contains the locations of the beginning of unparsed default
1022 // argument locations.
1023 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1025 /// UndefinedInternals - all the used, undefined objects which require a
1026 /// definition in this translation unit.
1027 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1029 /// Obtain a sorted list of functions that are undefined but ODR-used.
1030 void getUndefinedButUsed(
1031 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1033 /// Retrieves list of suspicious delete-expressions that will be checked at
1034 /// the end of translation unit.
1035 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1036 getMismatchingDeleteExpressions() const;
1038 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1039 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1041 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1042 /// We need to maintain a list, since selectors can have differing signatures
1043 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1044 /// of selectors are "overloaded").
1045 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1046 /// methods inside categories with a particular selector.
1047 GlobalMethodPool MethodPool;
1049 /// Method selectors used in a \@selector expression. Used for implementation
1051 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1053 /// Kinds of C++ special members.
1054 enum CXXSpecialMember {
1055 CXXDefaultConstructor,
1064 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1066 /// The C++ special members which we are currently in the process of
1067 /// declaring. If this process recursively triggers the declaration of the
1068 /// same special member, we should act as if it is not yet declared.
1069 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1071 void ReadMethodPool(Selector Sel);
1072 void updateOutOfDateSelector(Selector Sel);
1074 /// Private Helper predicate to check for 'self'.
1075 bool isSelfExpr(Expr *RExpr);
1076 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1078 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1079 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1080 /// should not be used elsewhere.
1081 void EmitCurrentDiagnostic(unsigned DiagID);
1083 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1085 class FPContractStateRAII {
1087 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1088 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1092 FPOptions OldFPFeaturesState;
1095 void addImplicitTypedef(StringRef Name, QualType T);
1098 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1099 TranslationUnitKind TUKind = TU_Complete,
1100 CodeCompleteConsumer *CompletionConsumer = nullptr);
1103 /// \brief Perform initialization that occurs after the parser has been
1104 /// initialized but before it parses anything.
1107 const LangOptions &getLangOpts() const { return LangOpts; }
1108 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1109 FPOptions &getFPOptions() { return FPFeatures; }
1111 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1112 SourceManager &getSourceManager() const { return SourceMgr; }
1113 Preprocessor &getPreprocessor() const { return PP; }
1114 ASTContext &getASTContext() const { return Context; }
1115 ASTConsumer &getASTConsumer() const { return Consumer; }
1116 ASTMutationListener *getASTMutationListener() const;
1117 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1119 ///\brief Registers an external source. If an external source already exists,
1120 /// creates a multiplex external source and appends to it.
1122 ///\param[in] E - A non-null external sema source.
1124 void addExternalSource(ExternalSemaSource *E);
1126 void PrintStats() const;
1128 /// \brief Helper class that creates diagnostics with optional
1129 /// template instantiation stacks.
1131 /// This class provides a wrapper around the basic DiagnosticBuilder
1132 /// class that emits diagnostics. SemaDiagnosticBuilder is
1133 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1134 /// does) and, if the diagnostic comes from inside a template
1135 /// instantiation, printing the template instantiation stack as
1137 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1142 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1143 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1145 // This is a cunning lie. DiagnosticBuilder actually performs move
1146 // construction in its copy constructor (but due to varied uses, it's not
1147 // possible to conveniently express this as actual move construction). So
1148 // the default copy ctor here is fine, because the base class disables the
1149 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1150 // in that case anwyay.
1151 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1153 ~SemaDiagnosticBuilder() {
1154 // If we aren't active, there is nothing to do.
1155 if (!isActive()) return;
1157 // Otherwise, we need to emit the diagnostic. First flush the underlying
1158 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1159 // won't emit the diagnostic in its own destructor.
1161 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1162 // do its own needless checks to see if the diagnostic needs to be
1163 // emitted. However, because we take care to ensure that the builder
1164 // objects never escape, a sufficiently smart compiler will be able to
1165 // eliminate that code.
1169 // Dispatch to Sema to emit the diagnostic.
1170 SemaRef.EmitCurrentDiagnostic(DiagID);
1173 /// Teach operator<< to produce an object of the correct type.
1174 template<typename T>
1175 friend const SemaDiagnosticBuilder &operator<<(
1176 const SemaDiagnosticBuilder &Diag, const T &Value) {
1177 const DiagnosticBuilder &BaseDiag = Diag;
1183 /// \brief Emit a diagnostic.
1184 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1185 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1186 return SemaDiagnosticBuilder(DB, *this, DiagID);
1189 /// \brief Emit a partial diagnostic.
1190 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1192 /// \brief Build a partial diagnostic.
1193 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1195 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1197 /// \brief Get a string to suggest for zero-initialization of a type.
1199 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1200 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1202 /// \brief Calls \c Lexer::getLocForEndOfToken()
1203 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1205 /// \brief Retrieve the module loader associated with the preprocessor.
1206 ModuleLoader &getModuleLoader() const;
1208 void emitAndClearUnusedLocalTypedefWarnings();
1210 void ActOnEndOfTranslationUnit();
1212 void CheckDelegatingCtorCycles();
1214 Scope *getScopeForContext(DeclContext *Ctx);
1216 void PushFunctionScope();
1217 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1218 sema::LambdaScopeInfo *PushLambdaScope();
1220 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1221 /// is during Parsing. Currently it is used to pass on the depth
1222 /// when parsing generic lambda 'auto' parameters.
1223 void RecordParsingTemplateParameterDepth(unsigned Depth);
1225 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1227 CapturedRegionKind K);
1229 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1230 const Decl *D = nullptr,
1231 const BlockExpr *blkExpr = nullptr);
1233 sema::FunctionScopeInfo *getCurFunction() const {
1234 return FunctionScopes.back();
1237 sema::FunctionScopeInfo *getEnclosingFunction() const {
1238 if (FunctionScopes.empty())
1241 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1242 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1244 return FunctionScopes[e];
1249 template <typename ExprT>
1250 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1251 if (!isUnevaluatedContext())
1252 getCurFunction()->recordUseOfWeak(E, IsRead);
1255 void PushCompoundScope();
1256 void PopCompoundScope();
1258 sema::CompoundScopeInfo &getCurCompoundScope() const;
1260 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1262 /// \brief Retrieve the current block, if any.
1263 sema::BlockScopeInfo *getCurBlock();
1265 /// Retrieve the current lambda scope info, if any.
1266 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1267 /// lambda scope info ignoring all inner capturing scopes that are not
1269 sema::LambdaScopeInfo *
1270 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1272 /// \brief Retrieve the current generic lambda info, if any.
1273 sema::LambdaScopeInfo *getCurGenericLambda();
1275 /// \brief Retrieve the current captured region, if any.
1276 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1278 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1279 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1281 void ActOnComment(SourceRange Comment);
1283 //===--------------------------------------------------------------------===//
1284 // Type Analysis / Processing: SemaType.cpp.
1287 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1288 const DeclSpec *DS = nullptr);
1289 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1290 const DeclSpec *DS = nullptr);
1291 QualType BuildPointerType(QualType T,
1292 SourceLocation Loc, DeclarationName Entity);
1293 QualType BuildReferenceType(QualType T, bool LValueRef,
1294 SourceLocation Loc, DeclarationName Entity);
1295 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1296 Expr *ArraySize, unsigned Quals,
1297 SourceRange Brackets, DeclarationName Entity);
1298 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1299 SourceLocation AttrLoc);
1301 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1303 /// \brief Build a function type.
1305 /// This routine checks the function type according to C++ rules and
1306 /// under the assumption that the result type and parameter types have
1307 /// just been instantiated from a template. It therefore duplicates
1308 /// some of the behavior of GetTypeForDeclarator, but in a much
1309 /// simpler form that is only suitable for this narrow use case.
1311 /// \param T The return type of the function.
1313 /// \param ParamTypes The parameter types of the function. This array
1314 /// will be modified to account for adjustments to the types of the
1315 /// function parameters.
1317 /// \param Loc The location of the entity whose type involves this
1318 /// function type or, if there is no such entity, the location of the
1319 /// type that will have function type.
1321 /// \param Entity The name of the entity that involves the function
1324 /// \param EPI Extra information about the function type. Usually this will
1325 /// be taken from an existing function with the same prototype.
1327 /// \returns A suitable function type, if there are no errors. The
1328 /// unqualified type will always be a FunctionProtoType.
1329 /// Otherwise, returns a NULL type.
1330 QualType BuildFunctionType(QualType T,
1331 MutableArrayRef<QualType> ParamTypes,
1332 SourceLocation Loc, DeclarationName Entity,
1333 const FunctionProtoType::ExtProtoInfo &EPI);
1335 QualType BuildMemberPointerType(QualType T, QualType Class,
1337 DeclarationName Entity);
1338 QualType BuildBlockPointerType(QualType T,
1339 SourceLocation Loc, DeclarationName Entity);
1340 QualType BuildParenType(QualType T);
1341 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1342 QualType BuildReadPipeType(QualType T,
1343 SourceLocation Loc);
1344 QualType BuildWritePipeType(QualType T,
1345 SourceLocation Loc);
1347 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1348 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1349 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1350 TypeSourceInfo *ReturnTypeInfo);
1352 /// \brief Package the given type and TSI into a ParsedType.
1353 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1354 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1355 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1356 static QualType GetTypeFromParser(ParsedType Ty,
1357 TypeSourceInfo **TInfo = nullptr);
1358 CanThrowResult canThrow(const Expr *E);
1359 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1360 const FunctionProtoType *FPT);
1361 void UpdateExceptionSpec(FunctionDecl *FD,
1362 const FunctionProtoType::ExceptionSpecInfo &ESI);
1363 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1364 bool CheckDistantExceptionSpec(QualType T);
1365 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1366 bool CheckEquivalentExceptionSpec(
1367 const FunctionProtoType *Old, SourceLocation OldLoc,
1368 const FunctionProtoType *New, SourceLocation NewLoc);
1369 bool CheckEquivalentExceptionSpec(
1370 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1371 const FunctionProtoType *Old, SourceLocation OldLoc,
1372 const FunctionProtoType *New, SourceLocation NewLoc);
1373 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1374 const PartialDiagnostic &NestedDiagID,
1375 const PartialDiagnostic &NoteID,
1376 const FunctionProtoType *Superset,
1377 SourceLocation SuperLoc,
1378 const FunctionProtoType *Subset,
1379 SourceLocation SubLoc);
1380 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1381 const PartialDiagnostic &NoteID,
1382 const FunctionProtoType *Target,
1383 SourceLocation TargetLoc,
1384 const FunctionProtoType *Source,
1385 SourceLocation SourceLoc);
1387 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1389 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1390 /// in an Objective-C message declaration. Return the appropriate type.
1391 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1393 /// \brief Abstract class used to diagnose incomplete types.
1394 struct TypeDiagnoser {
1397 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1398 virtual ~TypeDiagnoser() {}
1401 static int getPrintable(int I) { return I; }
1402 static unsigned getPrintable(unsigned I) { return I; }
1403 static bool getPrintable(bool B) { return B; }
1404 static const char * getPrintable(const char *S) { return S; }
1405 static StringRef getPrintable(StringRef S) { return S; }
1406 static const std::string &getPrintable(const std::string &S) { return S; }
1407 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1410 static DeclarationName getPrintable(DeclarationName N) { return N; }
1411 static QualType getPrintable(QualType T) { return T; }
1412 static SourceRange getPrintable(SourceRange R) { return R; }
1413 static SourceRange getPrintable(SourceLocation L) { return L; }
1414 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1415 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1417 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1419 std::tuple<const Ts &...> Args;
1421 template <std::size_t... Is>
1422 void emit(const SemaDiagnosticBuilder &DB,
1423 llvm::index_sequence<Is...>) const {
1424 // Apply all tuple elements to the builder in order.
1425 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1430 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1431 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1432 assert(DiagID != 0 && "no diagnostic for type diagnoser");
1435 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1436 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1437 emit(DB, llvm::index_sequence_for<Ts...>());
1443 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1444 TypeDiagnoser *Diagnoser);
1446 struct ModuleScope {
1447 clang::Module *Module;
1448 VisibleModuleSet OuterVisibleModules;
1450 /// The modules we're currently parsing.
1451 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1453 VisibleModuleSet VisibleModules;
1455 Module *CachedFakeTopLevelModule;
1458 /// \brief Get the module owning an entity.
1459 Module *getOwningModule(Decl *Entity);
1461 /// \brief Make a merged definition of an existing hidden definition \p ND
1462 /// visible at the specified location.
1463 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1465 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1467 /// Determine whether a declaration is visible to name lookup.
1468 bool isVisible(const NamedDecl *D) {
1469 return !D->isHidden() || isVisibleSlow(D);
1472 /// Determine whether any declaration of an entity is visible.
1474 hasVisibleDeclaration(const NamedDecl *D,
1475 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1476 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1478 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1479 llvm::SmallVectorImpl<Module *> *Modules);
1481 bool hasVisibleMergedDefinition(NamedDecl *Def);
1483 /// Determine if \p D has a visible definition. If not, suggest a declaration
1484 /// that should be made visible to expose the definition.
1485 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1486 bool OnlyNeedComplete = false);
1487 bool hasVisibleDefinition(const NamedDecl *D) {
1489 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1492 /// Determine if the template parameter \p D has a visible default argument.
1494 hasVisibleDefaultArgument(const NamedDecl *D,
1495 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1497 /// Determine if there is a visible declaration of \p D that is a member
1498 /// specialization declaration (as opposed to an instantiated declaration).
1499 bool hasVisibleMemberSpecialization(
1500 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1502 /// Determine if \p A and \p B are equivalent internal linkage declarations
1503 /// from different modules, and thus an ambiguity error can be downgraded to
1504 /// an extension warning.
1505 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1506 const NamedDecl *B);
1507 void diagnoseEquivalentInternalLinkageDeclarations(
1508 SourceLocation Loc, const NamedDecl *D,
1509 ArrayRef<const NamedDecl *> Equiv);
1511 bool isCompleteType(SourceLocation Loc, QualType T) {
1512 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1514 bool RequireCompleteType(SourceLocation Loc, QualType T,
1515 TypeDiagnoser &Diagnoser);
1516 bool RequireCompleteType(SourceLocation Loc, QualType T,
1519 template <typename... Ts>
1520 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1521 const Ts &...Args) {
1522 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1523 return RequireCompleteType(Loc, T, Diagnoser);
1526 void completeExprArrayBound(Expr *E);
1527 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1528 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1530 template <typename... Ts>
1531 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1532 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1533 return RequireCompleteExprType(E, Diagnoser);
1536 bool RequireLiteralType(SourceLocation Loc, QualType T,
1537 TypeDiagnoser &Diagnoser);
1538 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1540 template <typename... Ts>
1541 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1542 const Ts &...Args) {
1543 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1544 return RequireLiteralType(Loc, T, Diagnoser);
1547 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1548 const CXXScopeSpec &SS, QualType T);
1550 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1551 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1552 /// context, such as when building a type for decltype(auto).
1553 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1554 bool AsUnevaluated = true);
1555 QualType BuildUnaryTransformType(QualType BaseType,
1556 UnaryTransformType::UTTKind UKind,
1557 SourceLocation Loc);
1559 //===--------------------------------------------------------------------===//
1560 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1563 struct SkipBodyInfo {
1564 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1566 NamedDecl *Previous;
1569 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1571 void DiagnoseUseOfUnimplementedSelectors();
1573 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1575 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1576 Scope *S, CXXScopeSpec *SS = nullptr,
1577 bool isClassName = false, bool HasTrailingDot = false,
1578 ParsedType ObjectType = nullptr,
1579 bool IsCtorOrDtorName = false,
1580 bool WantNontrivialTypeSourceInfo = false,
1581 bool IsClassTemplateDeductionContext = true,
1582 IdentifierInfo **CorrectedII = nullptr);
1583 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1584 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1585 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1586 SourceLocation IILoc,
1589 ParsedType &SuggestedType,
1590 bool AllowClassTemplates = false);
1592 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1593 /// type name has failed in a dependent context. In these situations, we
1594 /// automatically form a DependentTypeName that will retry lookup in a related
1595 /// scope during instantiation.
1596 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1597 SourceLocation NameLoc,
1598 bool IsTemplateTypeArg);
1600 /// \brief Describes the result of the name lookup and resolution performed
1601 /// by \c ClassifyName().
1602 enum NameClassificationKind {
1608 NC_NestedNameSpecifier,
1614 class NameClassification {
1615 NameClassificationKind Kind;
1617 TemplateName Template;
1619 const IdentifierInfo *Keyword;
1621 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1624 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1626 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1628 NameClassification(const IdentifierInfo *Keyword)
1629 : Kind(NC_Keyword), Keyword(Keyword) { }
1631 static NameClassification Error() {
1632 return NameClassification(NC_Error);
1635 static NameClassification Unknown() {
1636 return NameClassification(NC_Unknown);
1639 static NameClassification NestedNameSpecifier() {
1640 return NameClassification(NC_NestedNameSpecifier);
1643 static NameClassification TypeTemplate(TemplateName Name) {
1644 NameClassification Result(NC_TypeTemplate);
1645 Result.Template = Name;
1649 static NameClassification VarTemplate(TemplateName Name) {
1650 NameClassification Result(NC_VarTemplate);
1651 Result.Template = Name;
1655 static NameClassification FunctionTemplate(TemplateName Name) {
1656 NameClassification Result(NC_FunctionTemplate);
1657 Result.Template = Name;
1661 NameClassificationKind getKind() const { return Kind; }
1663 ParsedType getType() const {
1664 assert(Kind == NC_Type);
1668 ExprResult getExpression() const {
1669 assert(Kind == NC_Expression);
1673 TemplateName getTemplateName() const {
1674 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1675 Kind == NC_VarTemplate);
1679 TemplateNameKind getTemplateNameKind() const {
1681 case NC_TypeTemplate:
1682 return TNK_Type_template;
1683 case NC_FunctionTemplate:
1684 return TNK_Function_template;
1685 case NC_VarTemplate:
1686 return TNK_Var_template;
1688 llvm_unreachable("unsupported name classification.");
1693 /// \brief Perform name lookup on the given name, classifying it based on
1694 /// the results of name lookup and the following token.
1696 /// This routine is used by the parser to resolve identifiers and help direct
1697 /// parsing. When the identifier cannot be found, this routine will attempt
1698 /// to correct the typo and classify based on the resulting name.
1700 /// \param S The scope in which we're performing name lookup.
1702 /// \param SS The nested-name-specifier that precedes the name.
1704 /// \param Name The identifier. If typo correction finds an alternative name,
1705 /// this pointer parameter will be updated accordingly.
1707 /// \param NameLoc The location of the identifier.
1709 /// \param NextToken The token following the identifier. Used to help
1710 /// disambiguate the name.
1712 /// \param IsAddressOfOperand True if this name is the operand of a unary
1713 /// address of ('&') expression, assuming it is classified as an
1716 /// \param CCC The correction callback, if typo correction is desired.
1718 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1719 SourceLocation NameLoc, const Token &NextToken,
1720 bool IsAddressOfOperand,
1721 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1723 /// Describes the detailed kind of a template name. Used in diagnostics.
1724 enum class TemplateNameKindForDiagnostics {
1729 TemplateTemplateParam,
1732 TemplateNameKindForDiagnostics
1733 getTemplateNameKindForDiagnostics(TemplateName Name);
1735 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1737 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1738 MultiTemplateParamsArg TemplateParameterLists);
1739 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1740 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1741 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1742 DeclarationName Name,
1743 SourceLocation Loc);
1745 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1746 SourceLocation FallbackLoc,
1747 SourceLocation ConstQualLoc = SourceLocation(),
1748 SourceLocation VolatileQualLoc = SourceLocation(),
1749 SourceLocation RestrictQualLoc = SourceLocation(),
1750 SourceLocation AtomicQualLoc = SourceLocation(),
1751 SourceLocation UnalignedQualLoc = SourceLocation());
1753 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1754 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1755 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1756 const LookupResult &R);
1757 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1758 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1759 const LookupResult &R);
1760 void CheckShadow(Scope *S, VarDecl *D);
1762 /// Warn if 'E', which is an expression that is about to be modified, refers
1763 /// to a shadowing declaration.
1764 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1766 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1769 /// Map of current shadowing declarations to shadowed declarations. Warn if
1770 /// it looks like the user is trying to modify the shadowing declaration.
1771 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1774 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1775 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1776 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1777 TypedefNameDecl *NewTD);
1778 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1779 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1780 TypeSourceInfo *TInfo,
1781 LookupResult &Previous);
1782 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1783 LookupResult &Previous, bool &Redeclaration);
1784 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1785 TypeSourceInfo *TInfo,
1786 LookupResult &Previous,
1787 MultiTemplateParamsArg TemplateParamLists,
1789 ArrayRef<BindingDecl *> Bindings = None);
1791 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1792 MultiTemplateParamsArg TemplateParamLists);
1793 // Returns true if the variable declaration is a redeclaration
1794 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1795 void CheckVariableDeclarationType(VarDecl *NewVD);
1796 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1798 void CheckCompleteVariableDeclaration(VarDecl *VD);
1799 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1800 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1802 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1803 TypeSourceInfo *TInfo,
1804 LookupResult &Previous,
1805 MultiTemplateParamsArg TemplateParamLists,
1807 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1809 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1810 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1812 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1813 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1814 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1815 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1816 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1817 // Returns true if the function declaration is a redeclaration
1818 bool CheckFunctionDeclaration(Scope *S,
1819 FunctionDecl *NewFD, LookupResult &Previous,
1820 bool IsMemberSpecialization);
1821 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1822 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1823 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1824 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1825 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1828 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1829 SourceLocation NameLoc, IdentifierInfo *Name,
1830 QualType T, TypeSourceInfo *TSInfo,
1832 void ActOnParamDefaultArgument(Decl *param,
1833 SourceLocation EqualLoc,
1835 void ActOnParamUnparsedDefaultArgument(Decl *param,
1836 SourceLocation EqualLoc,
1837 SourceLocation ArgLoc);
1838 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1839 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1840 SourceLocation EqualLoc);
1842 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1843 void ActOnUninitializedDecl(Decl *dcl);
1844 void ActOnInitializerError(Decl *Dcl);
1846 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1847 void ActOnCXXForRangeDecl(Decl *D);
1848 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1849 IdentifierInfo *Ident,
1850 ParsedAttributes &Attrs,
1851 SourceLocation AttrEnd);
1852 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1853 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1854 void FinalizeDeclaration(Decl *D);
1855 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1856 ArrayRef<Decl *> Group);
1857 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1859 /// Should be called on all declarations that might have attached
1860 /// documentation comments.
1861 void ActOnDocumentableDecl(Decl *D);
1862 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1864 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1865 SourceLocation LocAfterDecls);
1866 void CheckForFunctionRedefinition(
1867 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1868 SkipBodyInfo *SkipBody = nullptr);
1869 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1870 MultiTemplateParamsArg TemplateParamLists,
1871 SkipBodyInfo *SkipBody = nullptr);
1872 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1873 SkipBodyInfo *SkipBody = nullptr);
1874 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1875 bool isObjCMethodDecl(Decl *D) {
1876 return D && isa<ObjCMethodDecl>(D);
1879 /// \brief Determine whether we can delay parsing the body of a function or
1880 /// function template until it is used, assuming we don't care about emitting
1881 /// code for that function.
1883 /// This will be \c false if we may need the body of the function in the
1884 /// middle of parsing an expression (where it's impractical to switch to
1885 /// parsing a different function), for instance, if it's constexpr in C++11
1886 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1887 bool canDelayFunctionBody(const Declarator &D);
1889 /// \brief Determine whether we can skip parsing the body of a function
1890 /// definition, assuming we don't care about analyzing its body or emitting
1891 /// code for that function.
1893 /// This will be \c false only if we may need the body of the function in
1894 /// order to parse the rest of the program (for instance, if it is
1895 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1896 bool canSkipFunctionBody(Decl *D);
1898 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1899 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1900 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1901 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1902 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1904 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1905 /// attribute for which parsing is delayed.
1906 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1908 /// \brief Diagnose any unused parameters in the given sequence of
1909 /// ParmVarDecl pointers.
1910 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1912 /// \brief Diagnose whether the size of parameters or return value of a
1913 /// function or obj-c method definition is pass-by-value and larger than a
1914 /// specified threshold.
1916 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1917 QualType ReturnTy, NamedDecl *D);
1919 void DiagnoseInvalidJumps(Stmt *Body);
1920 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1921 SourceLocation AsmLoc,
1922 SourceLocation RParenLoc);
1924 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1925 Decl *ActOnEmptyDeclaration(Scope *S,
1926 AttributeList *AttrList,
1927 SourceLocation SemiLoc);
1929 enum class ModuleDeclKind {
1930 Module, ///< 'module X;'
1931 Partition, ///< 'module partition X;'
1932 Implementation, ///< 'module implementation X;'
1935 /// The parser has processed a module-declaration that begins the definition
1936 /// of a module interface or implementation.
1937 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
1938 SourceLocation ModuleLoc, ModuleDeclKind MDK,
1941 /// \brief The parser has processed a module import declaration.
1943 /// \param AtLoc The location of the '@' symbol, if any.
1945 /// \param ImportLoc The location of the 'import' keyword.
1947 /// \param Path The module access path.
1948 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1951 /// \brief The parser has processed a module import translated from a
1952 /// #include or similar preprocessing directive.
1953 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1954 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1956 /// \brief The parsed has entered a submodule.
1957 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1958 /// \brief The parser has left a submodule.
1959 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1961 /// \brief Create an implicit import of the given module at the given
1962 /// source location, for error recovery, if possible.
1964 /// This routine is typically used when an entity found by name lookup
1965 /// is actually hidden within a module that we know about but the user
1966 /// has forgotten to import.
1967 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1970 /// Kinds of missing import. Note, the values of these enumerators correspond
1971 /// to %select values in diagnostics.
1972 enum class MissingImportKind {
1976 ExplicitSpecialization,
1977 PartialSpecialization
1980 /// \brief Diagnose that the specified declaration needs to be visible but
1981 /// isn't, and suggest a module import that would resolve the problem.
1982 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1983 MissingImportKind MIK, bool Recover = true);
1984 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1985 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1986 MissingImportKind MIK, bool Recover);
1988 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
1989 SourceLocation LBraceLoc);
1990 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
1991 SourceLocation RBraceLoc);
1993 /// \brief We've found a use of a templated declaration that would trigger an
1994 /// implicit instantiation. Check that any relevant explicit specializations
1995 /// and partial specializations are visible, and diagnose if not.
1996 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1998 /// \brief We've found a use of a template specialization that would select a
1999 /// partial specialization. Check that the partial specialization is visible,
2000 /// and diagnose if not.
2001 void checkPartialSpecializationVisibility(SourceLocation Loc,
2004 /// \brief Retrieve a suitable printing policy.
2005 PrintingPolicy getPrintingPolicy() const {
2006 return getPrintingPolicy(Context, PP);
2009 /// \brief Retrieve a suitable printing policy.
2010 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2011 const Preprocessor &PP);
2014 void ActOnPopScope(SourceLocation Loc, Scope *S);
2015 void ActOnTranslationUnitScope(Scope *S);
2017 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2018 RecordDecl *&AnonRecord);
2019 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2020 MultiTemplateParamsArg TemplateParams,
2021 bool IsExplicitInstantiation,
2022 RecordDecl *&AnonRecord);
2024 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2027 const PrintingPolicy &Policy);
2029 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2030 RecordDecl *Record);
2032 /// Common ways to introduce type names without a tag for use in diagnostics.
2033 /// Keep in sync with err_tag_reference_non_tag.
2042 NTK_TypeAliasTemplate,
2043 NTK_TemplateTemplateArgument,
2046 /// Given a non-tag type declaration, returns an enum useful for indicating
2047 /// what kind of non-tag type this is.
2048 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2050 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2051 TagTypeKind NewTag, bool isDefinition,
2052 SourceLocation NewTagLoc,
2053 const IdentifierInfo *Name);
2056 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2057 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2058 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2059 TUK_Friend // Friend declaration: 'friend struct foo;'
2062 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2063 SourceLocation KWLoc, CXXScopeSpec &SS,
2064 IdentifierInfo *Name, SourceLocation NameLoc,
2065 AttributeList *Attr, AccessSpecifier AS,
2066 SourceLocation ModulePrivateLoc,
2067 MultiTemplateParamsArg TemplateParameterLists,
2068 bool &OwnedDecl, bool &IsDependent,
2069 SourceLocation ScopedEnumKWLoc,
2070 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2071 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2073 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2074 unsigned TagSpec, SourceLocation TagLoc,
2076 IdentifierInfo *Name, SourceLocation NameLoc,
2077 AttributeList *Attr,
2078 MultiTemplateParamsArg TempParamLists);
2080 TypeResult ActOnDependentTag(Scope *S,
2083 const CXXScopeSpec &SS,
2084 IdentifierInfo *Name,
2085 SourceLocation TagLoc,
2086 SourceLocation NameLoc);
2088 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2089 IdentifierInfo *ClassName,
2090 SmallVectorImpl<Decl *> &Decls);
2091 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2092 Declarator &D, Expr *BitfieldWidth);
2094 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2095 Declarator &D, Expr *BitfieldWidth,
2096 InClassInitStyle InitStyle,
2097 AccessSpecifier AS);
2098 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2099 SourceLocation DeclStart,
2100 Declarator &D, Expr *BitfieldWidth,
2101 InClassInitStyle InitStyle,
2103 AttributeList *MSPropertyAttr);
2105 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2106 TypeSourceInfo *TInfo,
2107 RecordDecl *Record, SourceLocation Loc,
2108 bool Mutable, Expr *BitfieldWidth,
2109 InClassInitStyle InitStyle,
2110 SourceLocation TSSL,
2111 AccessSpecifier AS, NamedDecl *PrevDecl,
2112 Declarator *D = nullptr);
2114 bool CheckNontrivialField(FieldDecl *FD);
2115 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2116 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2117 bool Diagnose = false);
2118 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2119 void ActOnLastBitfield(SourceLocation DeclStart,
2120 SmallVectorImpl<Decl *> &AllIvarDecls);
2121 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2122 Declarator &D, Expr *BitfieldWidth,
2123 tok::ObjCKeywordKind visibility);
2125 // This is used for both record definitions and ObjC interface declarations.
2126 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2127 ArrayRef<Decl *> Fields,
2128 SourceLocation LBrac, SourceLocation RBrac,
2129 AttributeList *AttrList);
2131 /// ActOnTagStartDefinition - Invoked when we have entered the
2132 /// scope of a tag's definition (e.g., for an enumeration, class,
2133 /// struct, or union).
2134 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2136 typedef void *SkippedDefinitionContext;
2138 /// \brief Invoked when we enter a tag definition that we're skipping.
2139 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2141 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2143 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2144 /// C++ record definition's base-specifiers clause and are starting its
2145 /// member declarations.
2146 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2147 SourceLocation FinalLoc,
2148 bool IsFinalSpelledSealed,
2149 SourceLocation LBraceLoc);
2151 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2152 /// the definition of a tag (enumeration, class, struct, or union).
2153 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2154 SourceRange BraceRange);
2156 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2158 void ActOnObjCContainerFinishDefinition();
2160 /// \brief Invoked when we must temporarily exit the objective-c container
2161 /// scope for parsing/looking-up C constructs.
2163 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2164 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2165 void ActOnObjCReenterContainerContext(DeclContext *DC);
2167 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2168 /// error parsing the definition of a tag.
2169 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2171 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2172 EnumConstantDecl *LastEnumConst,
2173 SourceLocation IdLoc,
2176 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2177 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2178 QualType EnumUnderlyingTy,
2179 bool EnumUnderlyingIsImplicit,
2180 const EnumDecl *Prev);
2182 /// Determine whether the body of an anonymous enumeration should be skipped.
2183 /// \param II The name of the first enumerator.
2184 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2185 SourceLocation IILoc);
2187 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2188 SourceLocation IdLoc, IdentifierInfo *Id,
2189 AttributeList *Attrs,
2190 SourceLocation EqualLoc, Expr *Val);
2191 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2193 ArrayRef<Decl *> Elements,
2194 Scope *S, AttributeList *Attr);
2196 DeclContext *getContainingDC(DeclContext *DC);
2198 /// Set the current declaration context until it gets popped.
2199 void PushDeclContext(Scope *S, DeclContext *DC);
2200 void PopDeclContext();
2202 /// EnterDeclaratorContext - Used when we must lookup names in the context
2203 /// of a declarator's nested name specifier.
2204 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2205 void ExitDeclaratorContext(Scope *S);
2207 /// Push the parameters of D, which must be a function, into scope.
2208 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2209 void ActOnExitFunctionContext();
2211 DeclContext *getFunctionLevelDeclContext();
2213 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2214 /// to the function decl for the function being parsed. If we're currently
2215 /// in a 'block', this returns the containing context.
2216 FunctionDecl *getCurFunctionDecl();
2218 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2219 /// the method decl for the method being parsed. If we're currently
2220 /// in a 'block', this returns the containing context.
2221 ObjCMethodDecl *getCurMethodDecl();
2223 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2224 /// or C function we're in, otherwise return null. If we're currently
2225 /// in a 'block', this returns the containing context.
2226 NamedDecl *getCurFunctionOrMethodDecl();
2228 /// Add this decl to the scope shadowed decl chains.
2229 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2231 /// \brief Make the given externally-produced declaration visible at the
2232 /// top level scope.
2234 /// \param D The externally-produced declaration to push.
2236 /// \param Name The name of the externally-produced declaration.
2237 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2239 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2240 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2241 /// true if 'D' belongs to the given declaration context.
2243 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2244 /// enclosing namespace set of the context, rather than contained
2245 /// directly within it.
2246 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2247 bool AllowInlineNamespace = false);
2249 /// Finds the scope corresponding to the given decl context, if it
2250 /// happens to be an enclosing scope. Otherwise return NULL.
2251 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2253 /// Subroutines of ActOnDeclarator().
2254 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2255 TypeSourceInfo *TInfo);
2256 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2258 /// \brief Describes the kind of merge to perform for availability
2259 /// attributes (including "deprecated", "unavailable", and "availability").
2260 enum AvailabilityMergeKind {
2261 /// \brief Don't merge availability attributes at all.
2263 /// \brief Merge availability attributes for a redeclaration, which requires
2266 /// \brief Merge availability attributes for an override, which requires
2267 /// an exact match or a weakening of constraints.
2269 /// \brief Merge availability attributes for an implementation of
2270 /// a protocol requirement.
2271 AMK_ProtocolImplementation,
2274 /// Attribute merging methods. Return true if a new attribute was added.
2275 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2276 IdentifierInfo *Platform,
2278 VersionTuple Introduced,
2279 VersionTuple Deprecated,
2280 VersionTuple Obsoleted,
2283 bool IsStrict, StringRef Replacement,
2284 AvailabilityMergeKind AMK,
2285 unsigned AttrSpellingListIndex);
2286 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2287 TypeVisibilityAttr::VisibilityType Vis,
2288 unsigned AttrSpellingListIndex);
2289 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2290 VisibilityAttr::VisibilityType Vis,
2291 unsigned AttrSpellingListIndex);
2292 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2293 unsigned AttrSpellingListIndex, StringRef Uuid);
2294 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2295 unsigned AttrSpellingListIndex);
2296 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2297 unsigned AttrSpellingListIndex);
2299 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2300 unsigned AttrSpellingListIndex,
2301 MSInheritanceAttr::Spelling SemanticSpelling);
2302 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2303 IdentifierInfo *Format, int FormatIdx,
2304 int FirstArg, unsigned AttrSpellingListIndex);
2305 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2306 unsigned AttrSpellingListIndex);
2307 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2308 IdentifierInfo *Ident,
2309 unsigned AttrSpellingListIndex);
2310 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2311 unsigned AttrSpellingListIndex);
2312 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2313 unsigned AttrSpellingListIndex);
2314 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2315 IdentifierInfo *Ident,
2316 unsigned AttrSpellingListIndex);
2317 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2318 unsigned AttrSpellingListIndex);
2320 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2321 AvailabilityMergeKind AMK = AMK_Redeclaration);
2322 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2323 LookupResult &OldDecls);
2324 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2325 bool MergeTypeWithOld);
2326 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2327 Scope *S, bool MergeTypeWithOld);
2328 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2329 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2330 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2331 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2332 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2333 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2335 // AssignmentAction - This is used by all the assignment diagnostic functions
2336 // to represent what is actually causing the operation
2337 enum AssignmentAction {
2345 AA_Passing_CFAudited
2348 /// C++ Overloading.
2350 /// This is a legitimate overload: the existing declarations are
2351 /// functions or function templates with different signatures.
2354 /// This is not an overload because the signature exactly matches
2355 /// an existing declaration.
2358 /// This is not an overload because the lookup results contain a
2362 OverloadKind CheckOverload(Scope *S,
2364 const LookupResult &OldDecls,
2365 NamedDecl *&OldDecl,
2366 bool IsForUsingDecl);
2367 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2368 bool ConsiderCudaAttrs = true);
2370 /// \brief Checks availability of the function depending on the current
2371 /// function context.Inside an unavailable function,unavailability is ignored.
2373 /// \returns true if \p FD is unavailable and current context is inside
2374 /// an available function, false otherwise.
2375 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2377 ImplicitConversionSequence
2378 TryImplicitConversion(Expr *From, QualType ToType,
2379 bool SuppressUserConversions,
2381 bool InOverloadResolution,
2383 bool AllowObjCWritebackConversion);
2385 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2386 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2387 bool IsComplexPromotion(QualType FromType, QualType ToType);
2388 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2389 bool InOverloadResolution,
2390 QualType& ConvertedType, bool &IncompatibleObjC);
2391 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2392 QualType& ConvertedType, bool &IncompatibleObjC);
2393 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2394 QualType &ConvertedType);
2395 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2396 QualType& ConvertedType);
2397 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2398 const FunctionProtoType *NewType,
2399 unsigned *ArgPos = nullptr);
2400 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2401 QualType FromType, QualType ToType);
2403 void maybeExtendBlockObject(ExprResult &E);
2404 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2405 bool CheckPointerConversion(Expr *From, QualType ToType,
2407 CXXCastPath& BasePath,
2408 bool IgnoreBaseAccess,
2409 bool Diagnose = true);
2410 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2411 bool InOverloadResolution,
2412 QualType &ConvertedType);
2413 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2415 CXXCastPath &BasePath,
2416 bool IgnoreBaseAccess);
2417 bool IsQualificationConversion(QualType FromType, QualType ToType,
2418 bool CStyle, bool &ObjCLifetimeConversion);
2419 bool IsFunctionConversion(QualType FromType, QualType ToType,
2420 QualType &ResultTy);
2421 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2422 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2424 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2425 const VarDecl *NRVOCandidate,
2426 QualType ResultType,
2428 bool AllowNRVO = true);
2430 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2432 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2433 SourceLocation EqualLoc,
2435 bool TopLevelOfInitList = false,
2436 bool AllowExplicit = false);
2437 ExprResult PerformObjectArgumentInitialization(Expr *From,
2438 NestedNameSpecifier *Qualifier,
2439 NamedDecl *FoundDecl,
2440 CXXMethodDecl *Method);
2442 ExprResult PerformContextuallyConvertToBool(Expr *From);
2443 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2445 /// Contexts in which a converted constant expression is required.
2447 CCEK_CaseValue, ///< Expression in a case label.
2448 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2449 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2450 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2451 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2453 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2454 llvm::APSInt &Value, CCEKind CCE);
2455 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2456 APValue &Value, CCEKind CCE);
2458 /// \brief Abstract base class used to perform a contextual implicit
2459 /// conversion from an expression to any type passing a filter.
2460 class ContextualImplicitConverter {
2463 bool SuppressConversion;
2465 ContextualImplicitConverter(bool Suppress = false,
2466 bool SuppressConversion = false)
2467 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2469 /// \brief Determine whether the specified type is a valid destination type
2470 /// for this conversion.
2471 virtual bool match(QualType T) = 0;
2473 /// \brief Emits a diagnostic complaining that the expression does not have
2474 /// integral or enumeration type.
2475 virtual SemaDiagnosticBuilder
2476 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2478 /// \brief Emits a diagnostic when the expression has incomplete class type.
2479 virtual SemaDiagnosticBuilder
2480 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2482 /// \brief Emits a diagnostic when the only matching conversion function
2484 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2485 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2487 /// \brief Emits a note for the explicit conversion function.
2488 virtual SemaDiagnosticBuilder
2489 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2491 /// \brief Emits a diagnostic when there are multiple possible conversion
2493 virtual SemaDiagnosticBuilder
2494 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2496 /// \brief Emits a note for one of the candidate conversions.
2497 virtual SemaDiagnosticBuilder
2498 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2500 /// \brief Emits a diagnostic when we picked a conversion function
2501 /// (for cases when we are not allowed to pick a conversion function).
2502 virtual SemaDiagnosticBuilder diagnoseConversion(
2503 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2505 virtual ~ContextualImplicitConverter() {}
2508 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2509 bool AllowScopedEnumerations;
2512 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2513 bool Suppress, bool SuppressConversion)
2514 : ContextualImplicitConverter(Suppress, SuppressConversion),
2515 AllowScopedEnumerations(AllowScopedEnumerations) {}
2517 /// Match an integral or (possibly scoped) enumeration type.
2518 bool match(QualType T) override;
2520 SemaDiagnosticBuilder
2521 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2522 return diagnoseNotInt(S, Loc, T);
2525 /// \brief Emits a diagnostic complaining that the expression does not have
2526 /// integral or enumeration type.
2527 virtual SemaDiagnosticBuilder
2528 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2531 /// Perform a contextual implicit conversion.
2532 ExprResult PerformContextualImplicitConversion(
2533 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2536 enum ObjCSubscriptKind {
2541 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2543 // Note that LK_String is intentionally after the other literals, as
2544 // this is used for diagnostics logic.
2545 enum ObjCLiteralKind {
2554 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2556 ExprResult PerformObjectMemberConversion(Expr *From,
2557 NestedNameSpecifier *Qualifier,
2558 NamedDecl *FoundDecl,
2561 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2562 // TODO: make this is a typesafe union.
2563 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2564 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2566 void AddOverloadCandidate(FunctionDecl *Function,
2567 DeclAccessPair FoundDecl,
2568 ArrayRef<Expr *> Args,
2569 OverloadCandidateSet &CandidateSet,
2570 bool SuppressUserConversions = false,
2571 bool PartialOverloading = false,
2572 bool AllowExplicit = false,
2573 ConversionSequenceList EarlyConversions = None);
2574 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2575 ArrayRef<Expr *> Args,
2576 OverloadCandidateSet &CandidateSet,
2577 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2578 bool SuppressUserConversions = false,
2579 bool PartialOverloading = false);
2580 void AddMethodCandidate(DeclAccessPair FoundDecl,
2581 QualType ObjectType,
2582 Expr::Classification ObjectClassification,
2583 ArrayRef<Expr *> Args,
2584 OverloadCandidateSet& CandidateSet,
2585 bool SuppressUserConversion = false);
2586 void AddMethodCandidate(CXXMethodDecl *Method,
2587 DeclAccessPair FoundDecl,
2588 CXXRecordDecl *ActingContext, QualType ObjectType,
2589 Expr::Classification ObjectClassification,
2590 ArrayRef<Expr *> Args,
2591 OverloadCandidateSet& CandidateSet,
2592 bool SuppressUserConversions = false,
2593 bool PartialOverloading = false,
2594 ConversionSequenceList EarlyConversions = None);
2595 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2596 DeclAccessPair FoundDecl,
2597 CXXRecordDecl *ActingContext,
2598 TemplateArgumentListInfo *ExplicitTemplateArgs,
2599 QualType ObjectType,
2600 Expr::Classification ObjectClassification,
2601 ArrayRef<Expr *> Args,
2602 OverloadCandidateSet& CandidateSet,
2603 bool SuppressUserConversions = false,
2604 bool PartialOverloading = false);
2605 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2606 DeclAccessPair FoundDecl,
2607 TemplateArgumentListInfo *ExplicitTemplateArgs,
2608 ArrayRef<Expr *> Args,
2609 OverloadCandidateSet& CandidateSet,
2610 bool SuppressUserConversions = false,
2611 bool PartialOverloading = false);
2612 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2613 ArrayRef<QualType> ParamTypes,
2614 ArrayRef<Expr *> Args,
2615 OverloadCandidateSet &CandidateSet,
2616 ConversionSequenceList &Conversions,
2617 bool SuppressUserConversions,
2618 CXXRecordDecl *ActingContext = nullptr,
2619 QualType ObjectType = QualType(),
2620 Expr::Classification
2621 ObjectClassification = {});
2622 void AddConversionCandidate(CXXConversionDecl *Conversion,
2623 DeclAccessPair FoundDecl,
2624 CXXRecordDecl *ActingContext,
2625 Expr *From, QualType ToType,
2626 OverloadCandidateSet& CandidateSet,
2627 bool AllowObjCConversionOnExplicit);
2628 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2629 DeclAccessPair FoundDecl,
2630 CXXRecordDecl *ActingContext,
2631 Expr *From, QualType ToType,
2632 OverloadCandidateSet &CandidateSet,
2633 bool AllowObjCConversionOnExplicit);
2634 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2635 DeclAccessPair FoundDecl,
2636 CXXRecordDecl *ActingContext,
2637 const FunctionProtoType *Proto,
2638 Expr *Object, ArrayRef<Expr *> Args,
2639 OverloadCandidateSet& CandidateSet);
2640 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2641 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2642 OverloadCandidateSet& CandidateSet,
2643 SourceRange OpRange = SourceRange());
2644 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2645 ArrayRef<Expr *> Args,
2646 OverloadCandidateSet& CandidateSet,
2647 bool IsAssignmentOperator = false,
2648 unsigned NumContextualBoolArguments = 0);
2649 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2650 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2651 OverloadCandidateSet& CandidateSet);
2652 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2654 ArrayRef<Expr *> Args,
2655 TemplateArgumentListInfo *ExplicitTemplateArgs,
2656 OverloadCandidateSet& CandidateSet,
2657 bool PartialOverloading = false);
2659 // Emit as a 'note' the specific overload candidate
2660 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2661 QualType DestType = QualType(),
2662 bool TakingAddress = false);
2664 // Emit as a series of 'note's all template and non-templates identified by
2665 // the expression Expr
2666 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2667 bool TakingAddress = false);
2669 /// Check the enable_if expressions on the given function. Returns the first
2670 /// failing attribute, or NULL if they were all successful.
2671 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2672 bool MissingImplicitThis = false);
2674 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2675 /// non-ArgDependent DiagnoseIfAttrs.
2677 /// Argument-dependent diagnose_if attributes should be checked each time a
2678 /// function is used as a direct callee of a function call.
2680 /// Returns true if any errors were emitted.
2681 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2682 const Expr *ThisArg,
2683 ArrayRef<const Expr *> Args,
2684 SourceLocation Loc);
2686 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2687 /// ArgDependent DiagnoseIfAttrs.
2689 /// Argument-independent diagnose_if attributes should be checked on every use
2692 /// Returns true if any errors were emitted.
2693 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2694 SourceLocation Loc);
2696 /// Returns whether the given function's address can be taken or not,
2697 /// optionally emitting a diagnostic if the address can't be taken.
2699 /// Returns false if taking the address of the function is illegal.
2700 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2701 bool Complain = false,
2702 SourceLocation Loc = SourceLocation());
2704 // [PossiblyAFunctionType] --> [Return]
2705 // NonFunctionType --> NonFunctionType
2707 // R (*)(A) --> R (A)
2708 // R (&)(A) --> R (A)
2709 // R (S::*)(A) --> R (A)
2710 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2713 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2714 QualType TargetType,
2716 DeclAccessPair &Found,
2717 bool *pHadMultipleCandidates = nullptr);
2720 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2721 DeclAccessPair &FoundResult);
2723 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2726 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2727 bool Complain = false,
2728 DeclAccessPair *Found = nullptr);
2730 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2731 ExprResult &SrcExpr,
2732 bool DoFunctionPointerConverion = false,
2733 bool Complain = false,
2734 SourceRange OpRangeForComplaining = SourceRange(),
2735 QualType DestTypeForComplaining = QualType(),
2736 unsigned DiagIDForComplaining = 0);
2739 Expr *FixOverloadedFunctionReference(Expr *E,
2740 DeclAccessPair FoundDecl,
2742 ExprResult FixOverloadedFunctionReference(ExprResult,
2743 DeclAccessPair FoundDecl,
2746 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2747 ArrayRef<Expr *> Args,
2748 OverloadCandidateSet &CandidateSet,
2749 bool PartialOverloading = false);
2751 // An enum used to represent the different possible results of building a
2752 // range-based for loop.
2753 enum ForRangeStatus {
2755 FRS_NoViableFunction,
2756 FRS_DiagnosticIssued
2759 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2760 SourceLocation RangeLoc,
2761 const DeclarationNameInfo &NameInfo,
2762 LookupResult &MemberLookup,
2763 OverloadCandidateSet *CandidateSet,
2764 Expr *Range, ExprResult *CallExpr);
2766 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2767 UnresolvedLookupExpr *ULE,
2768 SourceLocation LParenLoc,
2770 SourceLocation RParenLoc,
2772 bool AllowTypoCorrection=true,
2773 bool CalleesAddressIsTaken=false);
2775 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2776 MultiExprArg Args, SourceLocation RParenLoc,
2777 OverloadCandidateSet *CandidateSet,
2778 ExprResult *Result);
2780 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2781 UnaryOperatorKind Opc,
2782 const UnresolvedSetImpl &Fns,
2785 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2786 BinaryOperatorKind Opc,
2787 const UnresolvedSetImpl &Fns,
2788 Expr *LHS, Expr *RHS);
2790 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2791 SourceLocation RLoc,
2792 Expr *Base,Expr *Idx);
2795 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2796 SourceLocation LParenLoc,
2798 SourceLocation RParenLoc);
2800 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2802 SourceLocation RParenLoc);
2804 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2805 SourceLocation OpLoc,
2806 bool *NoArrowOperatorFound = nullptr);
2808 /// CheckCallReturnType - Checks that a call expression's return type is
2809 /// complete. Returns true on failure. The location passed in is the location
2810 /// that best represents the call.
2811 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2812 CallExpr *CE, FunctionDecl *FD);
2814 /// Helpers for dealing with blocks and functions.
2815 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2816 bool CheckParameterNames);
2817 void CheckCXXDefaultArguments(FunctionDecl *FD);
2818 void CheckExtraCXXDefaultArguments(Declarator &D);
2819 Scope *getNonFieldDeclScope(Scope *S);
2821 /// \name Name lookup
2823 /// These routines provide name lookup that is used during semantic
2824 /// analysis to resolve the various kinds of names (identifiers,
2825 /// overloaded operator names, constructor names, etc.) into zero or
2826 /// more declarations within a particular scope. The major entry
2827 /// points are LookupName, which performs unqualified name lookup,
2828 /// and LookupQualifiedName, which performs qualified name lookup.
2830 /// All name lookup is performed based on some specific criteria,
2831 /// which specify what names will be visible to name lookup and how
2832 /// far name lookup should work. These criteria are important both
2833 /// for capturing language semantics (certain lookups will ignore
2834 /// certain names, for example) and for performance, since name
2835 /// lookup is often a bottleneck in the compilation of C++. Name
2836 /// lookup criteria is specified via the LookupCriteria enumeration.
2838 /// The results of name lookup can vary based on the kind of name
2839 /// lookup performed, the current language, and the translation
2840 /// unit. In C, for example, name lookup will either return nothing
2841 /// (no entity found) or a single declaration. In C++, name lookup
2842 /// can additionally refer to a set of overloaded functions or
2843 /// result in an ambiguity. All of the possible results of name
2844 /// lookup are captured by the LookupResult class, which provides
2845 /// the ability to distinguish among them.
2848 /// @brief Describes the kind of name lookup to perform.
2849 enum LookupNameKind {
2850 /// Ordinary name lookup, which finds ordinary names (functions,
2851 /// variables, typedefs, etc.) in C and most kinds of names
2852 /// (functions, variables, members, types, etc.) in C++.
2853 LookupOrdinaryName = 0,
2854 /// Tag name lookup, which finds the names of enums, classes,
2855 /// structs, and unions.
2857 /// Label name lookup.
2859 /// Member name lookup, which finds the names of
2860 /// class/struct/union members.
2862 /// Look up of an operator name (e.g., operator+) for use with
2863 /// operator overloading. This lookup is similar to ordinary name
2864 /// lookup, but will ignore any declarations that are class members.
2866 /// Look up of a name that precedes the '::' scope resolution
2867 /// operator in C++. This lookup completely ignores operator, object,
2868 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2869 LookupNestedNameSpecifierName,
2870 /// Look up a namespace name within a C++ using directive or
2871 /// namespace alias definition, ignoring non-namespace names (C++
2872 /// [basic.lookup.udir]p1).
2873 LookupNamespaceName,
2874 /// Look up all declarations in a scope with the given name,
2875 /// including resolved using declarations. This is appropriate
2876 /// for checking redeclarations for a using declaration.
2877 LookupUsingDeclName,
2878 /// Look up an ordinary name that is going to be redeclared as a
2879 /// name with linkage. This lookup ignores any declarations that
2880 /// are outside of the current scope unless they have linkage. See
2881 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2882 LookupRedeclarationWithLinkage,
2883 /// Look up a friend of a local class. This lookup does not look
2884 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2885 LookupLocalFriendName,
2886 /// Look up the name of an Objective-C protocol.
2887 LookupObjCProtocolName,
2888 /// Look up implicit 'self' parameter of an objective-c method.
2889 LookupObjCImplicitSelfParam,
2890 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2891 LookupOMPReductionName,
2892 /// \brief Look up any declaration with any name.
2896 /// \brief Specifies whether (or how) name lookup is being performed for a
2897 /// redeclaration (vs. a reference).
2898 enum RedeclarationKind {
2899 /// \brief The lookup is a reference to this name that is not for the
2900 /// purpose of redeclaring the name.
2901 NotForRedeclaration = 0,
2902 /// \brief The lookup results will be used for redeclaration of a name,
2903 /// if an entity by that name already exists.
2907 /// \brief The possible outcomes of name lookup for a literal operator.
2908 enum LiteralOperatorLookupResult {
2909 /// \brief The lookup resulted in an error.
2911 /// \brief The lookup found a single 'cooked' literal operator, which
2912 /// expects a normal literal to be built and passed to it.
2914 /// \brief The lookup found a single 'raw' literal operator, which expects
2915 /// a string literal containing the spelling of the literal token.
2917 /// \brief The lookup found an overload set of literal operator templates,
2918 /// which expect the characters of the spelling of the literal token to be
2919 /// passed as a non-type template argument pack.
2921 /// \brief The lookup found an overload set of literal operator templates,
2922 /// which expect the character type and characters of the spelling of the
2923 /// string literal token to be passed as template arguments.
2927 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2928 CXXSpecialMember SM,
2935 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2936 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2937 TypoRecoveryCallback;
2940 bool CppLookupName(LookupResult &R, Scope *S);
2942 struct TypoExprState {
2943 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2944 TypoDiagnosticGenerator DiagHandler;
2945 TypoRecoveryCallback RecoveryHandler;
2947 TypoExprState(TypoExprState &&other) noexcept;
2948 TypoExprState &operator=(TypoExprState &&other) noexcept;
2951 /// \brief The set of unhandled TypoExprs and their associated state.
2952 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2954 /// \brief Creates a new TypoExpr AST node.
2955 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2956 TypoDiagnosticGenerator TDG,
2957 TypoRecoveryCallback TRC);
2959 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2961 // The boolean value will be true to indicate that the namespace was loaded
2962 // from an AST/PCH file, or false otherwise.
2963 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2965 /// \brief Whether we have already loaded known namespaces from an extenal
2967 bool LoadedExternalKnownNamespaces;
2969 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2970 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2971 /// should be skipped entirely.
2972 std::unique_ptr<TypoCorrectionConsumer>
2973 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2974 Sema::LookupNameKind LookupKind, Scope *S,
2976 std::unique_ptr<CorrectionCandidateCallback> CCC,
2977 DeclContext *MemberContext, bool EnteringContext,
2978 const ObjCObjectPointerType *OPT,
2979 bool ErrorRecovery);
2982 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2984 /// \brief Clears the state of the given TypoExpr.
2985 void clearDelayedTypo(TypoExpr *TE);
2987 /// \brief Look up a name, looking for a single declaration. Return
2988 /// null if the results were absent, ambiguous, or overloaded.
2990 /// It is preferable to use the elaborated form and explicitly handle
2991 /// ambiguity and overloaded.
2992 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2994 LookupNameKind NameKind,
2995 RedeclarationKind Redecl
2996 = NotForRedeclaration);
2997 bool LookupName(LookupResult &R, Scope *S,
2998 bool AllowBuiltinCreation = false);
2999 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3000 bool InUnqualifiedLookup = false);
3001 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3003 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3004 bool AllowBuiltinCreation = false,
3005 bool EnteringContext = false);
3006 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3007 RedeclarationKind Redecl
3008 = NotForRedeclaration);
3009 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3011 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3012 QualType T1, QualType T2,
3013 UnresolvedSetImpl &Functions);
3015 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3016 SourceLocation GnuLabelLoc = SourceLocation());
3018 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3019 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3020 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3022 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3023 bool RValueThis, unsigned ThisQuals);
3024 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3026 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3027 bool RValueThis, unsigned ThisQuals);
3028 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3030 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3031 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3032 ArrayRef<QualType> ArgTys,
3035 bool AllowStringTemplate);
3036 bool isKnownName(StringRef name);
3038 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3039 ArrayRef<Expr *> Args, ADLResult &Functions);
3041 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3042 VisibleDeclConsumer &Consumer,
3043 bool IncludeGlobalScope = true);
3044 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3045 VisibleDeclConsumer &Consumer,
3046 bool IncludeGlobalScope = true);
3048 enum CorrectTypoKind {
3049 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3050 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3053 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3054 Sema::LookupNameKind LookupKind,
3055 Scope *S, CXXScopeSpec *SS,
3056 std::unique_ptr<CorrectionCandidateCallback> CCC,
3057 CorrectTypoKind Mode,
3058 DeclContext *MemberContext = nullptr,
3059 bool EnteringContext = false,
3060 const ObjCObjectPointerType *OPT = nullptr,
3061 bool RecordFailure = true);
3063 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3064 Sema::LookupNameKind LookupKind, Scope *S,
3066 std::unique_ptr<CorrectionCandidateCallback> CCC,
3067 TypoDiagnosticGenerator TDG,
3068 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3069 DeclContext *MemberContext = nullptr,
3070 bool EnteringContext = false,
3071 const ObjCObjectPointerType *OPT = nullptr);
3073 /// \brief Process any TypoExprs in the given Expr and its children,
3074 /// generating diagnostics as appropriate and returning a new Expr if there
3075 /// were typos that were all successfully corrected and ExprError if one or
3076 /// more typos could not be corrected.
3078 /// \param E The Expr to check for TypoExprs.
3080 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3083 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3084 /// it is an acceptable/usable result from a single combination of typo
3085 /// corrections. As long as the filter returns ExprError, different
3086 /// combinations of corrections will be tried until all are exhausted.
3088 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3089 llvm::function_ref<ExprResult(Expr *)> Filter =
3090 [](Expr *E) -> ExprResult { return E; });
3093 CorrectDelayedTyposInExpr(Expr *E,
3094 llvm::function_ref<ExprResult(Expr *)> Filter) {
3095 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3099 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3100 llvm::function_ref<ExprResult(Expr *)> Filter =
3101 [](Expr *E) -> ExprResult { return E; }) {
3102 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3106 CorrectDelayedTyposInExpr(ExprResult ER,
3107 llvm::function_ref<ExprResult(Expr *)> Filter) {
3108 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3111 void diagnoseTypo(const TypoCorrection &Correction,
3112 const PartialDiagnostic &TypoDiag,
3113 bool ErrorRecovery = true);
3115 void diagnoseTypo(const TypoCorrection &Correction,
3116 const PartialDiagnostic &TypoDiag,
3117 const PartialDiagnostic &PrevNote,
3118 bool ErrorRecovery = true);
3120 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3121 ArrayRef<Expr *> Args,
3122 AssociatedNamespaceSet &AssociatedNamespaces,
3123 AssociatedClassSet &AssociatedClasses);
3125 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3126 bool ConsiderLinkage, bool AllowInlineNamespace);
3128 void DiagnoseAmbiguousLookup(LookupResult &Result);
3131 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3132 SourceLocation IdLoc,
3133 bool TypoCorrection = false);
3134 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3135 Scope *S, bool ForRedeclaration,
3136 SourceLocation Loc);
3137 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3139 void AddKnownFunctionAttributes(FunctionDecl *FD);
3141 // More parsing and symbol table subroutines.
3143 void ProcessPragmaWeak(Scope *S, Decl *D);
3144 // Decl attributes - this routine is the top level dispatcher.
3145 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3146 // Helper for delayed proccessing of attributes.
3147 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3148 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3149 bool IncludeCXX11Attributes = true);
3150 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3151 const AttributeList *AttrList);
3153 void checkUnusedDeclAttributes(Declarator &D);
3155 /// Determine if type T is a valid subject for a nonnull and similar
3156 /// attributes. By default, we look through references (the behavior used by
3157 /// nonnull), but if the second parameter is true, then we treat a reference
3159 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3161 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3162 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3163 const FunctionDecl *FD = nullptr);
3164 bool CheckNoReturnAttr(const AttributeList &attr);
3165 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3166 unsigned ArgNum, StringRef &Str,
3167 SourceLocation *ArgLocation = nullptr);
3168 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3169 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3170 bool checkMSInheritanceAttrOnDefinition(
3171 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3172 MSInheritanceAttr::Spelling SemanticSpelling);
3174 void CheckAlignasUnderalignment(Decl *D);
3176 /// Adjust the calling convention of a method to be the ABI default if it
3177 /// wasn't specified explicitly. This handles method types formed from
3178 /// function type typedefs and typename template arguments.
3179 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3180 SourceLocation Loc);
3182 // Check if there is an explicit attribute, but only look through parens.
3183 // The intent is to look for an attribute on the current declarator, but not
3184 // one that came from a typedef.
3185 bool hasExplicitCallingConv(QualType &T);
3187 /// Get the outermost AttributedType node that sets a calling convention.
3188 /// Valid types should not have multiple attributes with different CCs.
3189 const AttributedType *getCallingConvAttributedType(QualType T) const;
3191 /// Check whether a nullability type specifier can be added to the given
3194 /// \param type The type to which the nullability specifier will be
3195 /// added. On success, this type will be updated appropriately.
3197 /// \param nullability The nullability specifier to add.
3199 /// \param nullabilityLoc The location of the nullability specifier.
3201 /// \param isContextSensitive Whether this nullability specifier was
3202 /// written as a context-sensitive keyword (in an Objective-C
3203 /// method) or an Objective-C property attribute, rather than as an
3204 /// underscored type specifier.
3206 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3207 /// array type (e.g., because it will decay to a pointer).
3209 /// \returns true if nullability cannot be applied, false otherwise.
3210 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3211 SourceLocation nullabilityLoc,
3212 bool isContextSensitive,
3213 bool allowArrayTypes);
3215 /// \brief Stmt attributes - this routine is the top level dispatcher.
3216 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3219 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3220 ObjCMethodDecl *MethodDecl,
3221 bool IsProtocolMethodDecl);
3223 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3224 ObjCMethodDecl *Overridden,
3225 bool IsProtocolMethodDecl);
3227 /// WarnExactTypedMethods - This routine issues a warning if method
3228 /// implementation declaration matches exactly that of its declaration.
3229 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3230 ObjCMethodDecl *MethodDecl,
3231 bool IsProtocolMethodDecl);
3233 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3235 /// CheckImplementationIvars - This routine checks if the instance variables
3236 /// listed in the implelementation match those listed in the interface.
3237 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3238 ObjCIvarDecl **Fields, unsigned nIvars,
3239 SourceLocation Loc);
3241 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3242 /// remains unimplemented in the class or category \@implementation.
3243 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3244 ObjCContainerDecl* IDecl,
3245 bool IncompleteImpl = false);
3247 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3248 /// which must be implemented by this implementation.
3249 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3250 ObjCContainerDecl *CDecl,
3251 bool SynthesizeProperties);
3253 /// Diagnose any null-resettable synthesized setters.
3254 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3256 /// DefaultSynthesizeProperties - This routine default synthesizes all
3257 /// properties which must be synthesized in the class's \@implementation.
3258 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3259 ObjCInterfaceDecl *IDecl);
3260 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3262 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3263 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3264 /// declared in class 'IFace'.
3265 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3266 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3268 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3269 /// backs the property is not used in the property's accessor.
3270 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3271 const ObjCImplementationDecl *ImplD);
3273 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3274 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3275 /// It also returns ivar's property on success.
3276 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3277 const ObjCPropertyDecl *&PDecl) const;
3279 /// Called by ActOnProperty to handle \@property declarations in
3280 /// class extensions.
3281 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3282 SourceLocation AtLoc,
3283 SourceLocation LParenLoc,
3284 FieldDeclarator &FD,
3286 SourceLocation GetterNameLoc,
3288 SourceLocation SetterNameLoc,
3289 const bool isReadWrite,
3290 unsigned &Attributes,
3291 const unsigned AttributesAsWritten,
3293 TypeSourceInfo *TSI,
3294 tok::ObjCKeywordKind MethodImplKind);
3296 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3297 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3298 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3299 ObjCContainerDecl *CDecl,
3300 SourceLocation AtLoc,
3301 SourceLocation LParenLoc,
3302 FieldDeclarator &FD,
3304 SourceLocation GetterNameLoc,
3306 SourceLocation SetterNameLoc,
3307 const bool isReadWrite,
3308 const unsigned Attributes,
3309 const unsigned AttributesAsWritten,
3311 TypeSourceInfo *TSI,
3312 tok::ObjCKeywordKind MethodImplKind,
3313 DeclContext *lexicalDC = nullptr);
3315 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3316 /// warning) when atomic property has one but not the other user-declared
3317 /// setter or getter.
3318 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3319 ObjCInterfaceDecl* IDecl);
3321 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3323 void DiagnoseMissingDesignatedInitOverrides(
3324 const ObjCImplementationDecl *ImplD,
3325 const ObjCInterfaceDecl *IFD);
3327 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3329 enum MethodMatchStrategy {
3334 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3335 /// true, or false, accordingly.
3336 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3337 const ObjCMethodDecl *PrevMethod,
3338 MethodMatchStrategy strategy = MMS_strict);
3340 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3341 /// or protocol against those declared in their implementations.
3342 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3343 const SelectorSet &ClsMap,
3344 SelectorSet &InsMapSeen,
3345 SelectorSet &ClsMapSeen,
3346 ObjCImplDecl* IMPDecl,
3347 ObjCContainerDecl* IDecl,
3348 bool &IncompleteImpl,
3349 bool ImmediateClass,
3350 bool WarnCategoryMethodImpl=false);
3352 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3353 /// category matches with those implemented in its primary class and
3354 /// warns each time an exact match is found.
3355 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3357 /// \brief Add the given method to the list of globally-known methods.
3358 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3361 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3362 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3363 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3365 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3366 /// optionally warns if there are multiple signatures.
3367 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3368 bool receiverIdOrClass,
3372 /// \brief - Returns instance or factory methods in global method pool for
3373 /// given selector. It checks the desired kind first, if none is found, and
3374 /// parameter checkTheOther is set, it then checks the other kind. If no such
3375 /// method or only one method is found, function returns false; otherwise, it
3378 CollectMultipleMethodsInGlobalPool(Selector Sel,
3379 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3380 bool InstanceFirst, bool CheckTheOther,
3381 const ObjCObjectType *TypeBound = nullptr);
3384 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3385 SourceRange R, bool receiverIdOrClass,
3386 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3389 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3390 Selector Sel, SourceRange R,
3391 bool receiverIdOrClass);
3394 /// \brief - Returns a selector which best matches given argument list or
3395 /// nullptr if none could be found
3396 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3398 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3401 /// \brief Record the typo correction failure and return an empty correction.
3402 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3403 bool RecordFailure = true) {
3405 TypoCorrectionFailures[Typo].insert(TypoLoc);
3406 return TypoCorrection();
3410 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3411 /// unit are added to a global pool. This allows us to efficiently associate
3412 /// a selector with a method declaraation for purposes of typechecking
3413 /// messages sent to "id" (where the class of the object is unknown).
3414 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3415 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3418 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3419 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3420 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3423 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3425 void AddAnyMethodToGlobalPool(Decl *D);
3427 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3428 /// there are multiple signatures.
3429 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3430 bool receiverIdOrClass=false) {
3431 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3435 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3436 /// there are multiple signatures.
3437 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3438 bool receiverIdOrClass=false) {
3439 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3443 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3444 QualType ObjectType=QualType());
3445 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3447 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3449 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3451 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3452 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3454 //===--------------------------------------------------------------------===//
3455 // Statement Parsing Callbacks: SemaStmt.cpp.
3459 FullExprArg() : E(nullptr) { }
3460 FullExprArg(Sema &actions) : E(nullptr) { }
3462 ExprResult release() {
3466 Expr *get() const { return E; }
3468 Expr *operator->() {
3473 // FIXME: No need to make the entire Sema class a friend when it's just
3474 // Sema::MakeFullExpr that needs access to the constructor below.
3477 explicit FullExprArg(Expr *expr) : E(expr) {}
3482 FullExprArg MakeFullExpr(Expr *Arg) {
3483 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3485 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3486 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3488 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3490 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3491 /*DiscardedValue*/ true);
3492 return FullExprArg(FE.get());
3495 StmtResult ActOnExprStmt(ExprResult Arg);
3496 StmtResult ActOnExprStmtError();
3498 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3499 bool HasLeadingEmptyMacro = false);
3501 void ActOnStartOfCompoundStmt();
3502 void ActOnFinishOfCompoundStmt();
3503 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3504 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3506 /// \brief A RAII object to enter scope of a compound statement.
3507 class CompoundScopeRAII {
3509 CompoundScopeRAII(Sema &S): S(S) {
3510 S.ActOnStartOfCompoundStmt();
3513 ~CompoundScopeRAII() {
3514 S.ActOnFinishOfCompoundStmt();
3521 /// An RAII helper that pops function a function scope on exit.
3522 struct FunctionScopeRAII {
3525 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3526 ~FunctionScopeRAII() {
3528 S.PopFunctionScopeInfo();
3530 void disable() { Active = false; }
3533 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3534 SourceLocation StartLoc,
3535 SourceLocation EndLoc);
3536 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3537 StmtResult ActOnForEachLValueExpr(Expr *E);
3538 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3539 SourceLocation DotDotDotLoc, Expr *RHSVal,
3540 SourceLocation ColonLoc);
3541 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3543 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3544 SourceLocation ColonLoc,
3545 Stmt *SubStmt, Scope *CurScope);
3546 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3547 SourceLocation ColonLoc, Stmt *SubStmt);
3549 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3550 ArrayRef<const Attr*> Attrs,
3553 class ConditionResult;
3554 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3556 ConditionResult Cond, Stmt *ThenVal,
3557 SourceLocation ElseLoc, Stmt *ElseVal);
3558 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3560 ConditionResult Cond, Stmt *ThenVal,
3561 SourceLocation ElseLoc, Stmt *ElseVal);
3562 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3564 ConditionResult Cond);
3565 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3566 Stmt *Switch, Stmt *Body);
3567 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3569 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3570 SourceLocation WhileLoc, SourceLocation CondLParen,
3571 Expr *Cond, SourceLocation CondRParen);
3573 StmtResult ActOnForStmt(SourceLocation ForLoc,
3574 SourceLocation LParenLoc,
3576 ConditionResult Second,
3578 SourceLocation RParenLoc,
3580 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3582 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3583 Stmt *First, Expr *collection,
3584 SourceLocation RParenLoc);
3585 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3587 enum BuildForRangeKind {
3588 /// Initial building of a for-range statement.
3590 /// Instantiation or recovery rebuild of a for-range statement. Don't
3591 /// attempt any typo-correction.
3593 /// Determining whether a for-range statement could be built. Avoid any
3594 /// unnecessary or irreversible actions.
3598 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3599 SourceLocation CoawaitLoc,
3601 SourceLocation ColonLoc, Expr *Collection,
3602 SourceLocation RParenLoc,
3603 BuildForRangeKind Kind);
3604 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3605 SourceLocation CoawaitLoc,
3606 SourceLocation ColonLoc,
3607 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3608 Expr *Cond, Expr *Inc,
3610 SourceLocation RParenLoc,
3611 BuildForRangeKind Kind);
3612 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3614 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3615 SourceLocation LabelLoc,
3616 LabelDecl *TheDecl);
3617 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3618 SourceLocation StarLoc,
3620 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3621 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3623 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3624 CapturedRegionKind Kind, unsigned NumParams);
3625 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3626 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3627 CapturedRegionKind Kind,
3628 ArrayRef<CapturedParamNameType> Params);
3629 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3630 void ActOnCapturedRegionError();
3631 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3633 unsigned NumParams);
3634 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3635 bool AllowParamOrMoveConstructible);
3636 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3637 bool AllowParamOrMoveConstructible);
3639 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3641 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3642 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3644 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3645 bool IsVolatile, unsigned NumOutputs,
3646 unsigned NumInputs, IdentifierInfo **Names,
3647 MultiExprArg Constraints, MultiExprArg Exprs,
3648 Expr *AsmString, MultiExprArg Clobbers,
3649 SourceLocation RParenLoc);
3651 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3652 SourceLocation TemplateKWLoc,
3654 llvm::InlineAsmIdentifierInfo &Info,
3655 bool IsUnevaluatedContext);
3656 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3657 unsigned &Offset, SourceLocation AsmLoc);
3658 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3659 llvm::InlineAsmIdentifierInfo &Info,
3660 SourceLocation AsmLoc);
3661 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3662 ArrayRef<Token> AsmToks,
3663 StringRef AsmString,
3664 unsigned NumOutputs, unsigned NumInputs,
3665 ArrayRef<StringRef> Constraints,
3666 ArrayRef<StringRef> Clobbers,
3667 ArrayRef<Expr*> Exprs,
3668 SourceLocation EndLoc);
3669 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3670 SourceLocation Location,
3673 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3674 SourceLocation StartLoc,
3675 SourceLocation IdLoc, IdentifierInfo *Id,
3676 bool Invalid = false);
3678 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3680 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3681 Decl *Parm, Stmt *Body);
3683 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3685 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3686 MultiStmtArg Catch, Stmt *Finally);
3688 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3689 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3691 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3693 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3697 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3699 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3700 SourceLocation StartLoc,
3701 SourceLocation IdLoc,
3702 IdentifierInfo *Id);
3704 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3706 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3707 Decl *ExDecl, Stmt *HandlerBlock);
3708 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3709 ArrayRef<Stmt *> Handlers);
3711 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3712 SourceLocation TryLoc, Stmt *TryBlock,
3714 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3717 void ActOnStartSEHFinallyBlock();
3718 void ActOnAbortSEHFinallyBlock();
3719 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3720 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3722 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3724 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3726 /// \brief If it's a file scoped decl that must warn if not used, keep track
3728 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3730 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3731 /// whose result is unused, warn.
3732 void DiagnoseUnusedExprResult(const Stmt *S);
3733 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3734 void DiagnoseUnusedDecl(const NamedDecl *ND);
3736 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3737 /// statement as a \p Body, and it is located on the same line.
3739 /// This helps prevent bugs due to typos, such as:
3742 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3746 /// Warn if a for/while loop statement \p S, which is followed by
3747 /// \p PossibleBody, has a suspicious null statement as a body.
3748 void DiagnoseEmptyLoopBody(const Stmt *S,
3749 const Stmt *PossibleBody);
3751 /// Warn if a value is moved to itself.
3752 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3753 SourceLocation OpLoc);
3755 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3757 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3758 SourceLocation Loc);
3760 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3761 return DelayedDiagnostics.push(pool);
3763 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3765 typedef ProcessingContextState ParsingClassState;
3766 ParsingClassState PushParsingClass() {
3767 return DelayedDiagnostics.pushUndelayed();
3769 void PopParsingClass(ParsingClassState state) {
3770 DelayedDiagnostics.popUndelayed(state);
3773 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3775 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3776 StringRef Message, SourceLocation Loc,
3777 const ObjCInterfaceDecl *UnknownObjCClass,
3778 const ObjCPropertyDecl *ObjCProperty,
3779 bool ObjCPropertyAccess);
3781 bool makeUnavailableInSystemHeader(SourceLocation loc,
3782 UnavailableAttr::ImplicitReason reason);
3784 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3785 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3787 //===--------------------------------------------------------------------===//
3788 // Expression Parsing Callbacks: SemaExpr.cpp.
3790 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3791 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3792 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3793 bool ObjCPropertyAccess=false);
3794 void NoteDeletedFunction(FunctionDecl *FD);
3795 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3796 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3797 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3798 ObjCMethodDecl *Getter,
3799 SourceLocation Loc);
3800 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3801 ArrayRef<Expr *> Args);
3803 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3804 Decl *LambdaContextDecl = nullptr,
3805 bool IsDecltype = false);
3806 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3807 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3808 ReuseLambdaContextDecl_t,
3809 bool IsDecltype = false);
3810 void PopExpressionEvaluationContext();
3812 void DiscardCleanupsInEvaluationContext();
3814 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3815 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3817 ExprResult ActOnConstantExpression(ExprResult Res);
3819 // Functions for marking a declaration referenced. These functions also
3820 // contain the relevant logic for marking if a reference to a function or
3821 // variable is an odr-use (in the C++11 sense). There are separate variants
3822 // for expressions referring to a decl; these exist because odr-use marking
3823 // needs to be delayed for some constant variables when we build one of the
3824 // named expressions.
3826 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3827 // should usually be true. This only needs to be set to false if the lack of
3828 // odr-use cannot be determined from the current context (for instance,
3829 // because the name denotes a virtual function and was written without an
3830 // explicit nested-name-specifier).
3831 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3832 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3833 bool MightBeOdrUse = true);
3834 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3835 void MarkDeclRefReferenced(DeclRefExpr *E);
3836 void MarkMemberReferenced(MemberExpr *E);
3838 void UpdateMarkingForLValueToRValue(Expr *E);
3839 void CleanupVarDeclMarking();
3841 enum TryCaptureKind {
3842 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3845 /// \brief Try to capture the given variable.
3847 /// \param Var The variable to capture.
3849 /// \param Loc The location at which the capture occurs.
3851 /// \param Kind The kind of capture, which may be implicit (for either a
3852 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3854 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3855 /// an explicit lambda capture.
3857 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3858 /// captures or diagnose errors. If false, this routine merely check whether
3859 /// the capture can occur without performing the capture itself or complaining
3860 /// if the variable cannot be captured.
3862 /// \param CaptureType Will be set to the type of the field used to capture
3863 /// this variable in the innermost block or lambda. Only valid when the
3864 /// variable can be captured.
3866 /// \param DeclRefType Will be set to the type of a reference to the capture
3867 /// from within the current scope. Only valid when the variable can be
3870 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3871 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3872 /// This is useful when enclosing lambdas must speculatively capture
3873 /// variables that may or may not be used in certain specializations of
3874 /// a nested generic lambda.
3876 /// \returns true if an error occurred (i.e., the variable cannot be
3877 /// captured) and false if the capture succeeded.
3878 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3879 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3880 QualType &CaptureType,
3881 QualType &DeclRefType,
3882 const unsigned *const FunctionScopeIndexToStopAt);
3884 /// \brief Try to capture the given variable.
3885 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3886 TryCaptureKind Kind = TryCapture_Implicit,
3887 SourceLocation EllipsisLoc = SourceLocation());
3889 /// \brief Checks if the variable must be captured.
3890 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3892 /// \brief Given a variable, determine the type that a reference to that
3893 /// variable will have in the given scope.
3894 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3896 /// Mark all of the declarations referenced within a particular AST node as
3897 /// referenced. Used when template instantiation instantiates a non-dependent
3898 /// type -- entities referenced by the type are now referenced.
3899 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3900 void MarkDeclarationsReferencedInExpr(Expr *E,
3901 bool SkipLocalVariables = false);
3903 /// \brief Try to recover by turning the given expression into a
3904 /// call. Returns true if recovery was attempted or an error was
3905 /// emitted; this may also leave the ExprResult invalid.
3906 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3907 bool ForceComplain = false,
3908 bool (*IsPlausibleResult)(QualType) = nullptr);
3910 /// \brief Figure out if an expression could be turned into a call.
3911 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3912 UnresolvedSetImpl &NonTemplateOverloads);
3914 /// \brief Conditionally issue a diagnostic based on the current
3915 /// evaluation context.
3917 /// \param Statement If Statement is non-null, delay reporting the
3918 /// diagnostic until the function body is parsed, and then do a basic
3919 /// reachability analysis to determine if the statement is reachable.
3920 /// If it is unreachable, the diagnostic will not be emitted.
3921 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3922 const PartialDiagnostic &PD);
3924 // Primary Expressions.
3925 SourceRange getExprRange(Expr *E) const;
3927 ExprResult ActOnIdExpression(
3928 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3929 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3930 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3931 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3933 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3934 TemplateArgumentListInfo &Buffer,
3935 DeclarationNameInfo &NameInfo,
3936 const TemplateArgumentListInfo *&TemplateArgs);
3939 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3940 std::unique_ptr<CorrectionCandidateCallback> CCC,
3941 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3942 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3944 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3946 bool AllowBuiltinCreation=false);
3948 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3949 SourceLocation TemplateKWLoc,
3950 const DeclarationNameInfo &NameInfo,
3951 bool isAddressOfOperand,
3952 const TemplateArgumentListInfo *TemplateArgs);
3954 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3957 const CXXScopeSpec *SS = nullptr);
3959 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3960 const DeclarationNameInfo &NameInfo,
3961 const CXXScopeSpec *SS = nullptr,
3962 NamedDecl *FoundD = nullptr,
3963 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3965 BuildAnonymousStructUnionMemberReference(
3966 const CXXScopeSpec &SS,
3967 SourceLocation nameLoc,
3968 IndirectFieldDecl *indirectField,
3969 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3970 Expr *baseObjectExpr = nullptr,
3971 SourceLocation opLoc = SourceLocation());
3973 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3974 SourceLocation TemplateKWLoc,
3976 const TemplateArgumentListInfo *TemplateArgs,
3978 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3979 SourceLocation TemplateKWLoc,
3981 const TemplateArgumentListInfo *TemplateArgs,
3982 bool IsDefiniteInstance,
3984 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3985 const LookupResult &R,
3986 bool HasTrailingLParen);
3989 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3990 const DeclarationNameInfo &NameInfo,
3991 bool IsAddressOfOperand, const Scope *S,
3992 TypeSourceInfo **RecoveryTSI = nullptr);
3994 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3995 SourceLocation TemplateKWLoc,
3996 const DeclarationNameInfo &NameInfo,
3997 const TemplateArgumentListInfo *TemplateArgs);
3999 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4002 bool AcceptInvalidDecl = false);
4003 ExprResult BuildDeclarationNameExpr(
4004 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4005 NamedDecl *FoundD = nullptr,
4006 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4007 bool AcceptInvalidDecl = false);
4009 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4010 DeclarationNameInfo &SuffixInfo,
4011 ArrayRef<Expr *> Args,
4012 SourceLocation LitEndLoc,
4013 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4015 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4016 PredefinedExpr::IdentType IT);
4017 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4018 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4020 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4022 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4023 ExprResult ActOnCharacterConstant(const Token &Tok,
4024 Scope *UDLScope = nullptr);
4025 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4026 ExprResult ActOnParenListExpr(SourceLocation L,
4030 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4031 /// fragments (e.g. "foo" "bar" L"baz").
4032 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4033 Scope *UDLScope = nullptr);
4035 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4036 SourceLocation DefaultLoc,
4037 SourceLocation RParenLoc,
4038 Expr *ControllingExpr,
4039 ArrayRef<ParsedType> ArgTypes,
4040 ArrayRef<Expr *> ArgExprs);
4041 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4042 SourceLocation DefaultLoc,
4043 SourceLocation RParenLoc,
4044 Expr *ControllingExpr,
4045 ArrayRef<TypeSourceInfo *> Types,
4046 ArrayRef<Expr *> Exprs);
4048 // Binary/Unary Operators. 'Tok' is the token for the operator.
4049 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4051 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4052 UnaryOperatorKind Opc, Expr *Input);
4053 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4054 tok::TokenKind Op, Expr *Input);
4056 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4058 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4059 SourceLocation OpLoc,
4060 UnaryExprOrTypeTrait ExprKind,
4062 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4063 UnaryExprOrTypeTrait ExprKind);
4065 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4066 UnaryExprOrTypeTrait ExprKind,
4067 bool IsType, void *TyOrEx,
4068 SourceRange ArgRange);
4070 ExprResult CheckPlaceholderExpr(Expr *E);
4071 bool CheckVecStepExpr(Expr *E);
4073 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4074 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4075 SourceRange ExprRange,
4076 UnaryExprOrTypeTrait ExprKind);
4077 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4078 SourceLocation OpLoc,
4079 IdentifierInfo &Name,
4080 SourceLocation NameLoc,
4081 SourceLocation RParenLoc);
4082 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4083 tok::TokenKind Kind, Expr *Input);
4085 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4086 Expr *Idx, SourceLocation RLoc);
4087 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4088 Expr *Idx, SourceLocation RLoc);
4089 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4090 Expr *LowerBound, SourceLocation ColonLoc,
4091 Expr *Length, SourceLocation RBLoc);
4093 // This struct is for use by ActOnMemberAccess to allow
4094 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4095 // changing the access operator from a '.' to a '->' (to see if that is the
4096 // change needed to fix an error about an unknown member, e.g. when the class
4097 // defines a custom operator->).
4098 struct ActOnMemberAccessExtraArgs {
4104 ExprResult BuildMemberReferenceExpr(
4105 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4106 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4107 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4108 const TemplateArgumentListInfo *TemplateArgs,
4110 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4113 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4114 bool IsArrow, const CXXScopeSpec &SS,
4115 SourceLocation TemplateKWLoc,
4116 NamedDecl *FirstQualifierInScope, LookupResult &R,
4117 const TemplateArgumentListInfo *TemplateArgs,
4119 bool SuppressQualifierCheck = false,
4120 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4122 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4123 SourceLocation OpLoc,
4124 const CXXScopeSpec &SS, FieldDecl *Field,
4125 DeclAccessPair FoundDecl,
4126 const DeclarationNameInfo &MemberNameInfo);
4128 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4130 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4131 const CXXScopeSpec &SS,
4132 const LookupResult &R);
4134 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4135 bool IsArrow, SourceLocation OpLoc,
4136 const CXXScopeSpec &SS,
4137 SourceLocation TemplateKWLoc,
4138 NamedDecl *FirstQualifierInScope,
4139 const DeclarationNameInfo &NameInfo,
4140 const TemplateArgumentListInfo *TemplateArgs);
4142 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4143 SourceLocation OpLoc,
4144 tok::TokenKind OpKind,
4146 SourceLocation TemplateKWLoc,
4147 UnqualifiedId &Member,
4150 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4151 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4152 FunctionDecl *FDecl,
4153 const FunctionProtoType *Proto,
4154 ArrayRef<Expr *> Args,
4155 SourceLocation RParenLoc,
4156 bool ExecConfig = false);
4157 void CheckStaticArrayArgument(SourceLocation CallLoc,
4159 const Expr *ArgExpr);
4161 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4162 /// This provides the location of the left/right parens and a list of comma
4164 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4165 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4166 Expr *ExecConfig = nullptr,
4167 bool IsExecConfig = false);
4168 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4169 SourceLocation LParenLoc,
4170 ArrayRef<Expr *> Arg,
4171 SourceLocation RParenLoc,
4172 Expr *Config = nullptr,
4173 bool IsExecConfig = false);
4175 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4176 MultiExprArg ExecConfig,
4177 SourceLocation GGGLoc);
4179 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4180 Declarator &D, ParsedType &Ty,
4181 SourceLocation RParenLoc, Expr *CastExpr);
4182 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4184 SourceLocation RParenLoc,
4186 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4188 /// \brief Build an altivec or OpenCL literal.
4189 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4190 SourceLocation RParenLoc, Expr *E,
4191 TypeSourceInfo *TInfo);
4193 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4195 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4197 SourceLocation RParenLoc,
4200 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4201 TypeSourceInfo *TInfo,
4202 SourceLocation RParenLoc,
4205 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4206 MultiExprArg InitArgList,
4207 SourceLocation RBraceLoc);
4209 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4215 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4218 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4219 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4220 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4221 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4222 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4223 Expr *LHSExpr, Expr *RHSExpr);
4225 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4227 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4228 /// in the case of a the GNU conditional expr extension.
4229 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4230 SourceLocation ColonLoc,
4231 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4233 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4234 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4235 LabelDecl *TheDecl);
4237 void ActOnStartStmtExpr();
4238 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4239 SourceLocation RPLoc); // "({..})"
4240 void ActOnStmtExprError();
4242 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4243 struct OffsetOfComponent {
4244 SourceLocation LocStart, LocEnd;
4245 bool isBrackets; // true if [expr], false if .ident
4247 IdentifierInfo *IdentInfo;
4252 /// __builtin_offsetof(type, a.b[123][456].c)
4253 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4254 TypeSourceInfo *TInfo,
4255 ArrayRef<OffsetOfComponent> Components,
4256 SourceLocation RParenLoc);
4257 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4258 SourceLocation BuiltinLoc,
4259 SourceLocation TypeLoc,
4260 ParsedType ParsedArgTy,
4261 ArrayRef<OffsetOfComponent> Components,
4262 SourceLocation RParenLoc);
4264 // __builtin_choose_expr(constExpr, expr1, expr2)
4265 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4266 Expr *CondExpr, Expr *LHSExpr,
4267 Expr *RHSExpr, SourceLocation RPLoc);
4269 // __builtin_va_arg(expr, type)
4270 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4271 SourceLocation RPLoc);
4272 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4273 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4276 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4278 bool CheckCaseExpression(Expr *E);
4280 /// \brief Describes the result of an "if-exists" condition check.
4281 enum IfExistsResult {
4282 /// \brief The symbol exists.
4285 /// \brief The symbol does not exist.
4288 /// \brief The name is a dependent name, so the results will differ
4289 /// from one instantiation to the next.
4292 /// \brief An error occurred.
4297 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4298 const DeclarationNameInfo &TargetNameInfo);
4301 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4302 bool IsIfExists, CXXScopeSpec &SS,
4303 UnqualifiedId &Name);
4305 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4307 NestedNameSpecifierLoc QualifierLoc,
4308 DeclarationNameInfo NameInfo,
4310 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4312 CXXScopeSpec &SS, UnqualifiedId &Name,
4315 //===------------------------- "Block" Extension ------------------------===//
4317 /// ActOnBlockStart - This callback is invoked when a block literal is
4319 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4321 /// ActOnBlockArguments - This callback allows processing of block arguments.
4322 /// If there are no arguments, this is still invoked.
4323 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4326 /// ActOnBlockError - If there is an error parsing a block, this callback
4327 /// is invoked to pop the information about the block from the action impl.
4328 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4330 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4331 /// literal was successfully completed. ^(int x){...}
4332 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4335 //===---------------------------- Clang Extensions ----------------------===//
4337 /// __builtin_convertvector(...)
4338 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4339 SourceLocation BuiltinLoc,
4340 SourceLocation RParenLoc);
4342 //===---------------------------- OpenCL Features -----------------------===//
4344 /// __builtin_astype(...)
4345 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4346 SourceLocation BuiltinLoc,
4347 SourceLocation RParenLoc);
4349 //===---------------------------- C++ Features --------------------------===//
4351 // Act on C++ namespaces
4352 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4353 SourceLocation NamespaceLoc,
4354 SourceLocation IdentLoc,
4355 IdentifierInfo *Ident,
4356 SourceLocation LBrace,
4357 AttributeList *AttrList,
4358 UsingDirectiveDecl * &UsingDecl);
4359 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4361 NamespaceDecl *getStdNamespace() const;
4362 NamespaceDecl *getOrCreateStdNamespace();
4364 NamespaceDecl *lookupStdExperimentalNamespace();
4366 CXXRecordDecl *getStdBadAlloc() const;
4367 EnumDecl *getStdAlignValT() const;
4369 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4370 /// it is and Element is not NULL, assigns the element type to Element.
4371 bool isStdInitializerList(QualType Ty, QualType *Element);
4373 /// \brief Looks for the std::initializer_list template and instantiates it
4374 /// with Element, or emits an error if it's not found.
4376 /// \returns The instantiated template, or null on error.
4377 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4379 /// \brief Determine whether Ctor is an initializer-list constructor, as
4380 /// defined in [dcl.init.list]p2.
4381 bool isInitListConstructor(const FunctionDecl *Ctor);
4383 Decl *ActOnUsingDirective(Scope *CurScope,
4384 SourceLocation UsingLoc,
4385 SourceLocation NamespcLoc,
4387 SourceLocation IdentLoc,
4388 IdentifierInfo *NamespcName,
4389 AttributeList *AttrList);
4391 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4393 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4394 SourceLocation NamespaceLoc,
4395 SourceLocation AliasLoc,
4396 IdentifierInfo *Alias,
4398 SourceLocation IdentLoc,
4399 IdentifierInfo *Ident);
4401 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4402 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4403 const LookupResult &PreviousDecls,
4404 UsingShadowDecl *&PrevShadow);
4405 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4407 UsingShadowDecl *PrevDecl);
4409 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4410 bool HasTypenameKeyword,
4411 const CXXScopeSpec &SS,
4412 SourceLocation NameLoc,
4413 const LookupResult &Previous);
4414 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4416 const CXXScopeSpec &SS,
4417 const DeclarationNameInfo &NameInfo,
4418 SourceLocation NameLoc);
4420 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4421 SourceLocation UsingLoc,
4422 bool HasTypenameKeyword,
4423 SourceLocation TypenameLoc,
4425 DeclarationNameInfo NameInfo,
4426 SourceLocation EllipsisLoc,
4427 AttributeList *AttrList,
4428 bool IsInstantiation);
4429 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4430 ArrayRef<NamedDecl *> Expansions);
4432 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4434 /// Given a derived-class using shadow declaration for a constructor and the
4435 /// correspnding base class constructor, find or create the implicit
4436 /// synthesized derived class constructor to use for this initialization.
4437 CXXConstructorDecl *
4438 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4439 ConstructorUsingShadowDecl *DerivedShadow);
4441 Decl *ActOnUsingDeclaration(Scope *CurScope,
4443 SourceLocation UsingLoc,
4444 SourceLocation TypenameLoc,
4446 UnqualifiedId &Name,
4447 SourceLocation EllipsisLoc,
4448 AttributeList *AttrList);
4449 Decl *ActOnAliasDeclaration(Scope *CurScope,
4451 MultiTemplateParamsArg TemplateParams,
4452 SourceLocation UsingLoc,
4453 UnqualifiedId &Name,
4454 AttributeList *AttrList,
4456 Decl *DeclFromDeclSpec);
4458 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4459 /// including handling of its default argument expressions.
4461 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4463 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4464 NamedDecl *FoundDecl,
4465 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4466 bool HadMultipleCandidates, bool IsListInitialization,
4467 bool IsStdInitListInitialization,
4468 bool RequiresZeroInit, unsigned ConstructKind,
4469 SourceRange ParenRange);
4471 /// Build a CXXConstructExpr whose constructor has already been resolved if
4472 /// it denotes an inherited constructor.
4474 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4475 CXXConstructorDecl *Constructor, bool Elidable,
4477 bool HadMultipleCandidates, bool IsListInitialization,
4478 bool IsStdInitListInitialization,
4479 bool RequiresZeroInit, unsigned ConstructKind,
4480 SourceRange ParenRange);
4482 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4483 // the constructor can be elidable?
4485 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4486 NamedDecl *FoundDecl,
4487 CXXConstructorDecl *Constructor, bool Elidable,
4488 MultiExprArg Exprs, bool HadMultipleCandidates,
4489 bool IsListInitialization,
4490 bool IsStdInitListInitialization, bool RequiresZeroInit,
4491 unsigned ConstructKind, SourceRange ParenRange);
4493 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4496 /// Instantiate or parse a C++ default argument expression as necessary.
4497 /// Return true on error.
4498 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4499 ParmVarDecl *Param);
4501 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4502 /// the default expr if needed.
4503 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4505 ParmVarDecl *Param);
4507 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4508 /// constructed variable.
4509 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4511 /// \brief Helper class that collects exception specifications for
4512 /// implicitly-declared special member functions.
4513 class ImplicitExceptionSpecification {
4514 // Pointer to allow copying
4516 // We order exception specifications thus:
4517 // noexcept is the most restrictive, but is only used in C++11.
4518 // throw() comes next.
4519 // Then a throw(collected exceptions)
4520 // Finally no specification, which is expressed as noexcept(false).
4521 // throw(...) is used instead if any called function uses it.
4522 ExceptionSpecificationType ComputedEST;
4523 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4524 SmallVector<QualType, 4> Exceptions;
4526 void ClearExceptions() {
4527 ExceptionsSeen.clear();
4532 explicit ImplicitExceptionSpecification(Sema &Self)
4533 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4534 if (!Self.getLangOpts().CPlusPlus11)
4535 ComputedEST = EST_DynamicNone;
4538 /// \brief Get the computed exception specification type.
4539 ExceptionSpecificationType getExceptionSpecType() const {
4540 assert(ComputedEST != EST_ComputedNoexcept &&
4541 "noexcept(expr) should not be a possible result");
4545 /// \brief The number of exceptions in the exception specification.
4546 unsigned size() const { return Exceptions.size(); }
4548 /// \brief The set of exceptions in the exception specification.
4549 const QualType *data() const { return Exceptions.data(); }
4551 /// \brief Integrate another called method into the collected data.
4552 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4554 /// \brief Integrate an invoked expression into the collected data.
4555 void CalledExpr(Expr *E);
4557 /// \brief Overwrite an EPI's exception specification with this
4558 /// computed exception specification.
4559 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4560 FunctionProtoType::ExceptionSpecInfo ESI;
4561 ESI.Type = getExceptionSpecType();
4562 if (ESI.Type == EST_Dynamic) {
4563 ESI.Exceptions = Exceptions;
4564 } else if (ESI.Type == EST_None) {
4565 /// C++11 [except.spec]p14:
4566 /// The exception-specification is noexcept(false) if the set of
4567 /// potential exceptions of the special member function contains "any"
4568 ESI.Type = EST_ComputedNoexcept;
4569 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4570 tok::kw_false).get();
4576 /// \brief Determine what sort of exception specification a defaulted
4577 /// copy constructor of a class will have.
4578 ImplicitExceptionSpecification
4579 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4582 /// \brief Determine what sort of exception specification a defaulted
4583 /// default constructor of a class will have, and whether the parameter
4585 ImplicitExceptionSpecification
4586 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4588 /// \brief Determine what sort of exception specification a defautled
4589 /// copy assignment operator of a class will have, and whether the
4590 /// parameter will be const.
4591 ImplicitExceptionSpecification
4592 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4594 /// \brief Determine what sort of exception specification a defaulted move
4595 /// constructor of a class will have.
4596 ImplicitExceptionSpecification
4597 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4599 /// \brief Determine what sort of exception specification a defaulted move
4600 /// assignment operator of a class will have.
4601 ImplicitExceptionSpecification
4602 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4604 /// \brief Determine what sort of exception specification a defaulted
4605 /// destructor of a class will have.
4606 ImplicitExceptionSpecification
4607 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4609 /// \brief Determine what sort of exception specification an inheriting
4610 /// constructor of a class will have.
4611 ImplicitExceptionSpecification
4612 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4613 CXXConstructorDecl *CD);
4615 /// \brief Evaluate the implicit exception specification for a defaulted
4616 /// special member function.
4617 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4619 /// \brief Check the given exception-specification and update the
4620 /// exception specification information with the results.
4621 void checkExceptionSpecification(bool IsTopLevel,
4622 ExceptionSpecificationType EST,
4623 ArrayRef<ParsedType> DynamicExceptions,
4624 ArrayRef<SourceRange> DynamicExceptionRanges,
4626 SmallVectorImpl<QualType> &Exceptions,
4627 FunctionProtoType::ExceptionSpecInfo &ESI);
4629 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4630 /// parse an exception specification to work around a libstdc++ bug.
4631 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4633 /// \brief Add an exception-specification to the given member function
4634 /// (or member function template). The exception-specification was parsed
4635 /// after the method itself was declared.
4636 void actOnDelayedExceptionSpecification(Decl *Method,
4637 ExceptionSpecificationType EST,
4638 SourceRange SpecificationRange,
4639 ArrayRef<ParsedType> DynamicExceptions,
4640 ArrayRef<SourceRange> DynamicExceptionRanges,
4641 Expr *NoexceptExpr);
4643 class InheritedConstructorInfo;
4645 /// \brief Determine if a special member function should have a deleted
4646 /// definition when it is defaulted.
4647 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4648 InheritedConstructorInfo *ICI = nullptr,
4649 bool Diagnose = false);
4651 /// \brief Declare the implicit default constructor for the given class.
4653 /// \param ClassDecl The class declaration into which the implicit
4654 /// default constructor will be added.
4656 /// \returns The implicitly-declared default constructor.
4657 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4658 CXXRecordDecl *ClassDecl);
4660 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4661 /// defining this constructor as the default constructor.
4662 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4663 CXXConstructorDecl *Constructor);
4665 /// \brief Declare the implicit destructor for the given class.
4667 /// \param ClassDecl The class declaration into which the implicit
4668 /// destructor will be added.
4670 /// \returns The implicitly-declared destructor.
4671 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4673 /// DefineImplicitDestructor - Checks for feasibility of
4674 /// defining this destructor as the default destructor.
4675 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4676 CXXDestructorDecl *Destructor);
4678 /// \brief Build an exception spec for destructors that don't have one.
4680 /// C++11 says that user-defined destructors with no exception spec get one
4681 /// that looks as if the destructor was implicitly declared.
4682 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4683 CXXDestructorDecl *Destructor);
4685 /// \brief Define the specified inheriting constructor.
4686 void DefineInheritingConstructor(SourceLocation UseLoc,
4687 CXXConstructorDecl *Constructor);
4689 /// \brief Declare the implicit copy constructor for the given class.
4691 /// \param ClassDecl The class declaration into which the implicit
4692 /// copy constructor will be added.
4694 /// \returns The implicitly-declared copy constructor.
4695 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4697 /// DefineImplicitCopyConstructor - Checks for feasibility of
4698 /// defining this constructor as the copy constructor.
4699 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4700 CXXConstructorDecl *Constructor);
4702 /// \brief Declare the implicit move constructor for the given class.
4704 /// \param ClassDecl The Class declaration into which the implicit
4705 /// move constructor will be added.
4707 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4709 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4711 /// DefineImplicitMoveConstructor - Checks for feasibility of
4712 /// defining this constructor as the move constructor.
4713 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4714 CXXConstructorDecl *Constructor);
4716 /// \brief Declare the implicit copy assignment operator for the given class.
4718 /// \param ClassDecl The class declaration into which the implicit
4719 /// copy assignment operator will be added.
4721 /// \returns The implicitly-declared copy assignment operator.
4722 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4724 /// \brief Defines an implicitly-declared copy assignment operator.
4725 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4726 CXXMethodDecl *MethodDecl);
4728 /// \brief Declare the implicit move assignment operator for the given class.
4730 /// \param ClassDecl The Class declaration into which the implicit
4731 /// move assignment operator will be added.
4733 /// \returns The implicitly-declared move assignment operator, or NULL if it
4734 /// wasn't declared.
4735 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4737 /// \brief Defines an implicitly-declared move assignment operator.
4738 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4739 CXXMethodDecl *MethodDecl);
4741 /// \brief Force the declaration of any implicitly-declared members of this
4743 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4745 /// \brief Check a completed declaration of an implicit special member.
4746 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4748 /// \brief Determine whether the given function is an implicitly-deleted
4749 /// special member function.
4750 bool isImplicitlyDeleted(FunctionDecl *FD);
4752 /// \brief Check whether 'this' shows up in the type of a static member
4753 /// function after the (naturally empty) cv-qualifier-seq would be.
4755 /// \returns true if an error occurred.
4756 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4758 /// \brief Whether this' shows up in the exception specification of a static
4759 /// member function.
4760 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4762 /// \brief Check whether 'this' shows up in the attributes of the given
4763 /// static member function.
4765 /// \returns true if an error occurred.
4766 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4768 /// MaybeBindToTemporary - If the passed in expression has a record type with
4769 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4770 /// it simply returns the passed in expression.
4771 ExprResult MaybeBindToTemporary(Expr *E);
4773 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4774 MultiExprArg ArgsPtr,
4776 SmallVectorImpl<Expr*> &ConvertedArgs,
4777 bool AllowExplicit = false,
4778 bool IsListInitialization = false);
4780 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4781 SourceLocation NameLoc,
4782 IdentifierInfo &Name);
4784 ParsedType getDestructorName(SourceLocation TildeLoc,
4785 IdentifierInfo &II, SourceLocation NameLoc,
4786 Scope *S, CXXScopeSpec &SS,
4787 ParsedType ObjectType,
4788 bool EnteringContext);
4790 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4791 ParsedType ObjectType);
4793 // Checks that reinterpret casts don't have undefined behavior.
4794 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4795 bool IsDereference, SourceRange Range);
4797 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4798 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4799 tok::TokenKind Kind,
4800 SourceLocation LAngleBracketLoc,
4802 SourceLocation RAngleBracketLoc,
4803 SourceLocation LParenLoc,
4805 SourceLocation RParenLoc);
4807 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4808 tok::TokenKind Kind,
4811 SourceRange AngleBrackets,
4812 SourceRange Parens);
4814 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4815 SourceLocation TypeidLoc,
4816 TypeSourceInfo *Operand,
4817 SourceLocation RParenLoc);
4818 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4819 SourceLocation TypeidLoc,
4821 SourceLocation RParenLoc);
4823 /// ActOnCXXTypeid - Parse typeid( something ).
4824 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4825 SourceLocation LParenLoc, bool isType,
4827 SourceLocation RParenLoc);
4829 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4830 SourceLocation TypeidLoc,
4831 TypeSourceInfo *Operand,
4832 SourceLocation RParenLoc);
4833 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4834 SourceLocation TypeidLoc,
4836 SourceLocation RParenLoc);
4838 /// ActOnCXXUuidof - Parse __uuidof( something ).
4839 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4840 SourceLocation LParenLoc, bool isType,
4842 SourceLocation RParenLoc);
4844 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4845 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4846 tok::TokenKind Operator,
4847 SourceLocation EllipsisLoc, Expr *RHS,
4848 SourceLocation RParenLoc);
4849 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4850 BinaryOperatorKind Operator,
4851 SourceLocation EllipsisLoc, Expr *RHS,
4852 SourceLocation RParenLoc);
4853 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4854 BinaryOperatorKind Operator);
4856 //// ActOnCXXThis - Parse 'this' pointer.
4857 ExprResult ActOnCXXThis(SourceLocation loc);
4859 /// \brief Try to retrieve the type of the 'this' pointer.
4861 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4862 QualType getCurrentThisType();
4864 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4865 /// current context not being a non-static member function. In such cases,
4866 /// this provides the type used for 'this'.
4867 QualType CXXThisTypeOverride;
4869 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4870 /// to be used, with the given qualifiers on the current class type.
4871 class CXXThisScopeRAII {
4873 QualType OldCXXThisTypeOverride;
4877 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4878 /// using the given declaration (which is either a class template or a
4879 /// class) along with the given qualifiers.
4880 /// along with the qualifiers placed on '*this'.
4881 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4882 bool Enabled = true);
4884 ~CXXThisScopeRAII();
4887 /// \brief Make sure the value of 'this' is actually available in the current
4888 /// context, if it is a potentially evaluated context.
4890 /// \param Loc The location at which the capture of 'this' occurs.
4892 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4895 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4896 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4897 /// This is useful when enclosing lambdas must speculatively capture
4898 /// 'this' that may or may not be used in certain specializations of
4899 /// a nested generic lambda (depending on whether the name resolves to
4900 /// a non-static member function or a static function).
4901 /// \return returns 'true' if failed, 'false' if success.
4902 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4903 bool BuildAndDiagnose = true,
4904 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4905 bool ByCopy = false);
4907 /// \brief Determine whether the given type is the type of *this that is used
4908 /// outside of the body of a member function for a type that is currently
4910 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4912 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4913 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4916 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4917 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4920 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4921 SourceLocation AtLoc, SourceLocation RParen);
4923 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4924 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4926 //// ActOnCXXThrow - Parse throw expressions.
4927 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4928 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4929 bool IsThrownVarInScope);
4930 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4932 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4933 /// Can be interpreted either as function-style casting ("int(x)")
4934 /// or class type construction ("ClassType(x,y,z)")
4935 /// or creation of a value-initialized type ("int()").
4936 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4937 SourceLocation LParenLoc,
4939 SourceLocation RParenLoc);
4941 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4942 SourceLocation LParenLoc,
4944 SourceLocation RParenLoc);
4946 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4947 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4948 SourceLocation PlacementLParen,
4949 MultiExprArg PlacementArgs,
4950 SourceLocation PlacementRParen,
4951 SourceRange TypeIdParens, Declarator &D,
4953 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4954 SourceLocation PlacementLParen,
4955 MultiExprArg PlacementArgs,
4956 SourceLocation PlacementRParen,
4957 SourceRange TypeIdParens,
4959 TypeSourceInfo *AllocTypeInfo,
4961 SourceRange DirectInitRange,
4964 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4966 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4967 bool UseGlobal, QualType AllocType, bool IsArray,
4968 bool &PassAlignment, MultiExprArg PlaceArgs,
4969 FunctionDecl *&OperatorNew,
4970 FunctionDecl *&OperatorDelete);
4971 void DeclareGlobalNewDelete();
4972 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4973 ArrayRef<QualType> Params);
4975 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4976 DeclarationName Name, FunctionDecl* &Operator,
4977 bool Diagnose = true);
4978 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4979 bool CanProvideSize,
4981 DeclarationName Name);
4982 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
4985 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4986 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4987 bool UseGlobal, bool ArrayForm,
4989 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4990 bool IsDelete, bool CallCanBeVirtual,
4991 bool WarnOnNonAbstractTypes,
4992 SourceLocation DtorLoc);
4994 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4995 Expr *Operand, SourceLocation RParen);
4996 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4997 SourceLocation RParen);
4999 /// \brief Parsed one of the type trait support pseudo-functions.
5000 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5001 ArrayRef<ParsedType> Args,
5002 SourceLocation RParenLoc);
5003 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5004 ArrayRef<TypeSourceInfo *> Args,
5005 SourceLocation RParenLoc);
5007 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5008 /// pseudo-functions.
5009 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5010 SourceLocation KWLoc,
5013 SourceLocation RParen);
5015 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5016 SourceLocation KWLoc,
5017 TypeSourceInfo *TSInfo,
5019 SourceLocation RParen);
5021 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5022 /// pseudo-functions.
5023 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5024 SourceLocation KWLoc,
5026 SourceLocation RParen);
5028 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5029 SourceLocation KWLoc,
5031 SourceLocation RParen);
5033 ExprResult ActOnStartCXXMemberReference(Scope *S,
5035 SourceLocation OpLoc,
5036 tok::TokenKind OpKind,
5037 ParsedType &ObjectType,
5038 bool &MayBePseudoDestructor);
5040 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5041 SourceLocation OpLoc,
5042 tok::TokenKind OpKind,
5043 const CXXScopeSpec &SS,
5044 TypeSourceInfo *ScopeType,
5045 SourceLocation CCLoc,
5046 SourceLocation TildeLoc,
5047 PseudoDestructorTypeStorage DestroyedType);
5049 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5050 SourceLocation OpLoc,
5051 tok::TokenKind OpKind,
5053 UnqualifiedId &FirstTypeName,
5054 SourceLocation CCLoc,
5055 SourceLocation TildeLoc,
5056 UnqualifiedId &SecondTypeName);
5058 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5059 SourceLocation OpLoc,
5060 tok::TokenKind OpKind,
5061 SourceLocation TildeLoc,
5062 const DeclSpec& DS);
5064 /// MaybeCreateExprWithCleanups - If the current full-expression
5065 /// requires any cleanups, surround it with a ExprWithCleanups node.
5066 /// Otherwise, just returns the passed-in expression.
5067 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5068 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5069 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5071 MaterializeTemporaryExpr *
5072 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5073 bool BoundToLvalueReference);
5075 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5076 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5077 : SourceLocation());
5079 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5080 bool DiscardedValue = false,
5081 bool IsConstexpr = false,
5082 bool IsLambdaInitCaptureInitializer = false);
5083 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5085 // Marks SS invalid if it represents an incomplete type.
5086 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5088 DeclContext *computeDeclContext(QualType T);
5089 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5090 bool EnteringContext = false);
5091 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5092 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5094 /// \brief The parser has parsed a global nested-name-specifier '::'.
5096 /// \param CCLoc The location of the '::'.
5098 /// \param SS The nested-name-specifier, which will be updated in-place
5099 /// to reflect the parsed nested-name-specifier.
5101 /// \returns true if an error occurred, false otherwise.
5102 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5104 /// \brief The parser has parsed a '__super' nested-name-specifier.
5106 /// \param SuperLoc The location of the '__super' keyword.
5108 /// \param ColonColonLoc The location of the '::'.
5110 /// \param SS The nested-name-specifier, which will be updated in-place
5111 /// to reflect the parsed nested-name-specifier.
5113 /// \returns true if an error occurred, false otherwise.
5114 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5115 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5117 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5118 bool *CanCorrect = nullptr);
5119 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5121 /// \brief Keeps information about an identifier in a nested-name-spec.
5123 struct NestedNameSpecInfo {
5124 /// \brief The type of the object, if we're parsing nested-name-specifier in
5125 /// a member access expression.
5126 ParsedType ObjectType;
5128 /// \brief The identifier preceding the '::'.
5129 IdentifierInfo *Identifier;
5131 /// \brief The location of the identifier.
5132 SourceLocation IdentifierLoc;
5134 /// \brief The location of the '::'.
5135 SourceLocation CCLoc;
5137 /// \brief Creates info object for the most typical case.
5138 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5139 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5140 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5141 CCLoc(ColonColonLoc) {
5144 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5145 SourceLocation ColonColonLoc, QualType ObjectType)
5146 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5147 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5151 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5152 NestedNameSpecInfo &IdInfo);
5154 bool BuildCXXNestedNameSpecifier(Scope *S,
5155 NestedNameSpecInfo &IdInfo,
5156 bool EnteringContext,
5158 NamedDecl *ScopeLookupResult,
5159 bool ErrorRecoveryLookup,
5160 bool *IsCorrectedToColon = nullptr,
5161 bool OnlyNamespace = false);
5163 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5165 /// \param S The scope in which this nested-name-specifier occurs.
5167 /// \param IdInfo Parser information about an identifier in the
5168 /// nested-name-spec.
5170 /// \param EnteringContext Whether we're entering the context nominated by
5171 /// this nested-name-specifier.
5173 /// \param SS The nested-name-specifier, which is both an input
5174 /// parameter (the nested-name-specifier before this type) and an
5175 /// output parameter (containing the full nested-name-specifier,
5176 /// including this new type).
5178 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5179 /// error recovery. In this case do not emit error message.
5181 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5182 /// are allowed. The bool value pointed by this parameter is set to 'true'
5183 /// if the identifier is treated as if it was followed by ':', not '::'.
5185 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5187 /// \returns true if an error occurred, false otherwise.
5188 bool ActOnCXXNestedNameSpecifier(Scope *S,
5189 NestedNameSpecInfo &IdInfo,
5190 bool EnteringContext,
5192 bool ErrorRecoveryLookup = false,
5193 bool *IsCorrectedToColon = nullptr,
5194 bool OnlyNamespace = false);
5196 ExprResult ActOnDecltypeExpression(Expr *E);
5198 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5200 SourceLocation ColonColonLoc);
5202 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5203 NestedNameSpecInfo &IdInfo,
5204 bool EnteringContext);
5206 /// \brief The parser has parsed a nested-name-specifier
5207 /// 'template[opt] template-name < template-args >::'.
5209 /// \param S The scope in which this nested-name-specifier occurs.
5211 /// \param SS The nested-name-specifier, which is both an input
5212 /// parameter (the nested-name-specifier before this type) and an
5213 /// output parameter (containing the full nested-name-specifier,
5214 /// including this new type).
5216 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5217 /// \param TemplateName the template name.
5218 /// \param TemplateNameLoc The location of the template name.
5219 /// \param LAngleLoc The location of the opening angle bracket ('<').
5220 /// \param TemplateArgs The template arguments.
5221 /// \param RAngleLoc The location of the closing angle bracket ('>').
5222 /// \param CCLoc The location of the '::'.
5224 /// \param EnteringContext Whether we're entering the context of the
5225 /// nested-name-specifier.
5228 /// \returns true if an error occurred, false otherwise.
5229 bool ActOnCXXNestedNameSpecifier(Scope *S,
5231 SourceLocation TemplateKWLoc,
5232 TemplateTy TemplateName,
5233 SourceLocation TemplateNameLoc,
5234 SourceLocation LAngleLoc,
5235 ASTTemplateArgsPtr TemplateArgs,
5236 SourceLocation RAngleLoc,
5237 SourceLocation CCLoc,
5238 bool EnteringContext);
5240 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5241 /// that the parser can use later to reconstruct the given
5242 /// nested-name-specifier.
5244 /// \param SS A nested-name-specifier.
5246 /// \returns A pointer containing all of the information in the
5247 /// nested-name-specifier \p SS.
5248 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5250 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5251 /// the nested-name-specifier structure.
5253 /// \param Annotation The annotation pointer, produced by
5254 /// \c SaveNestedNameSpecifierAnnotation().
5256 /// \param AnnotationRange The source range corresponding to the annotation.
5258 /// \param SS The nested-name-specifier that will be updated with the contents
5259 /// of the annotation pointer.
5260 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5261 SourceRange AnnotationRange,
5264 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5266 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5267 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5268 /// After this method is called, according to [C++ 3.4.3p3], names should be
5269 /// looked up in the declarator-id's scope, until the declarator is parsed and
5270 /// ActOnCXXExitDeclaratorScope is called.
5271 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5272 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5274 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5275 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5276 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5277 /// Used to indicate that names should revert to being looked up in the
5279 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5281 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5282 /// initializer for the declaration 'Dcl'.
5283 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5284 /// static data member of class X, names should be looked up in the scope of
5286 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5288 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5289 /// initializer for the declaration 'Dcl'.
5290 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5292 /// \brief Create a new lambda closure type.
5293 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5294 TypeSourceInfo *Info,
5295 bool KnownDependent,
5296 LambdaCaptureDefault CaptureDefault);
5298 /// \brief Start the definition of a lambda expression.
5299 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5300 SourceRange IntroducerRange,
5301 TypeSourceInfo *MethodType,
5302 SourceLocation EndLoc,
5303 ArrayRef<ParmVarDecl *> Params,
5304 bool IsConstexprSpecified);
5306 /// \brief Endow the lambda scope info with the relevant properties.
5307 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5308 CXXMethodDecl *CallOperator,
5309 SourceRange IntroducerRange,
5310 LambdaCaptureDefault CaptureDefault,
5311 SourceLocation CaptureDefaultLoc,
5312 bool ExplicitParams,
5313 bool ExplicitResultType,
5316 /// \brief Perform initialization analysis of the init-capture and perform
5317 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5318 /// not being used to initialize a reference.
5319 ParsedType actOnLambdaInitCaptureInitialization(
5320 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5321 LambdaCaptureInitKind InitKind, Expr *&Init) {
5322 return ParsedType::make(buildLambdaInitCaptureInitialization(
5323 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5325 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5327 bool DirectInit, Expr *&Init);
5329 /// \brief Create a dummy variable within the declcontext of the lambda's
5330 /// call operator, for name lookup purposes for a lambda init capture.
5332 /// CodeGen handles emission of lambda captures, ignoring these dummy
5333 /// variables appropriately.
5334 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5335 QualType InitCaptureType,
5337 unsigned InitStyle, Expr *Init);
5339 /// \brief Build the implicit field for an init-capture.
5340 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5342 /// \brief Note that we have finished the explicit captures for the
5344 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5346 /// \brief Introduce the lambda parameters into scope.
5347 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5349 /// \brief Deduce a block or lambda's return type based on the return
5350 /// statements present in the body.
5351 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5353 /// ActOnStartOfLambdaDefinition - This is called just before we start
5354 /// parsing the body of a lambda; it analyzes the explicit captures and
5355 /// arguments, and sets up various data-structures for the body of the
5357 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5358 Declarator &ParamInfo, Scope *CurScope);
5360 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5361 /// is invoked to pop the information about the lambda.
5362 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5363 bool IsInstantiation = false);
5365 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5366 /// was successfully completed.
5367 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5370 /// \brief Does copying/destroying the captured variable have side effects?
5371 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5373 /// \brief Diagnose if an explicit lambda capture is unused.
5374 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5376 /// \brief Complete a lambda-expression having processed and attached the
5378 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5379 sema::LambdaScopeInfo *LSI);
5381 /// \brief Define the "body" of the conversion from a lambda object to a
5382 /// function pointer.
5384 /// This routine doesn't actually define a sensible body; rather, it fills
5385 /// in the initialization expression needed to copy the lambda object into
5386 /// the block, and IR generation actually generates the real body of the
5387 /// block pointer conversion.
5388 void DefineImplicitLambdaToFunctionPointerConversion(
5389 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5391 /// \brief Define the "body" of the conversion from a lambda object to a
5394 /// This routine doesn't actually define a sensible body; rather, it fills
5395 /// in the initialization expression needed to copy the lambda object into
5396 /// the block, and IR generation actually generates the real body of the
5397 /// block pointer conversion.
5398 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5399 CXXConversionDecl *Conv);
5401 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5402 SourceLocation ConvLocation,
5403 CXXConversionDecl *Conv,
5406 // ParseObjCStringLiteral - Parse Objective-C string literals.
5407 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5408 ArrayRef<Expr *> Strings);
5410 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5412 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5413 /// numeric literal expression. Type of the expression will be "NSNumber *"
5414 /// or "id" if NSNumber is unavailable.
5415 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5416 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5418 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5420 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5421 /// '@' prefixed parenthesized expression. The type of the expression will
5422 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5423 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5424 /// "const char *" or C structure with attribute 'objc_boxable'.
5425 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5427 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5429 ObjCMethodDecl *getterMethod,
5430 ObjCMethodDecl *setterMethod);
5432 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5433 MutableArrayRef<ObjCDictionaryElement> Elements);
5435 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5436 TypeSourceInfo *EncodedTypeInfo,
5437 SourceLocation RParenLoc);
5438 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5439 CXXConversionDecl *Method,
5440 bool HadMultipleCandidates);
5442 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5443 SourceLocation EncodeLoc,
5444 SourceLocation LParenLoc,
5446 SourceLocation RParenLoc);
5448 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5449 ExprResult ParseObjCSelectorExpression(Selector Sel,
5450 SourceLocation AtLoc,
5451 SourceLocation SelLoc,
5452 SourceLocation LParenLoc,
5453 SourceLocation RParenLoc,
5454 bool WarnMultipleSelectors);
5456 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5457 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5458 SourceLocation AtLoc,
5459 SourceLocation ProtoLoc,
5460 SourceLocation LParenLoc,
5461 SourceLocation ProtoIdLoc,
5462 SourceLocation RParenLoc);
5464 //===--------------------------------------------------------------------===//
5467 Decl *ActOnStartLinkageSpecification(Scope *S,
5468 SourceLocation ExternLoc,
5470 SourceLocation LBraceLoc);
5471 Decl *ActOnFinishLinkageSpecification(Scope *S,
5473 SourceLocation RBraceLoc);
5476 //===--------------------------------------------------------------------===//
5479 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5480 const CXXScopeSpec *SS = nullptr);
5481 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5483 bool ActOnAccessSpecifier(AccessSpecifier Access,
5484 SourceLocation ASLoc,
5485 SourceLocation ColonLoc,
5486 AttributeList *Attrs = nullptr);
5488 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5490 MultiTemplateParamsArg TemplateParameterLists,
5491 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5492 InClassInitStyle InitStyle);
5494 void ActOnStartCXXInClassMemberInitializer();
5495 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5496 SourceLocation EqualLoc,
5499 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5502 IdentifierInfo *MemberOrBase,
5503 ParsedType TemplateTypeTy,
5505 SourceLocation IdLoc,
5506 SourceLocation LParenLoc,
5507 ArrayRef<Expr *> Args,
5508 SourceLocation RParenLoc,
5509 SourceLocation EllipsisLoc);
5511 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5514 IdentifierInfo *MemberOrBase,
5515 ParsedType TemplateTypeTy,
5517 SourceLocation IdLoc,
5519 SourceLocation EllipsisLoc);
5521 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5524 IdentifierInfo *MemberOrBase,
5525 ParsedType TemplateTypeTy,
5527 SourceLocation IdLoc,
5529 SourceLocation EllipsisLoc);
5531 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5533 SourceLocation IdLoc);
5535 MemInitResult BuildBaseInitializer(QualType BaseType,
5536 TypeSourceInfo *BaseTInfo,
5538 CXXRecordDecl *ClassDecl,
5539 SourceLocation EllipsisLoc);
5541 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5543 CXXRecordDecl *ClassDecl);
5545 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5546 CXXCtorInitializer *Initializer);
5548 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5549 ArrayRef<CXXCtorInitializer *> Initializers = None);
5551 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5554 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5555 /// mark all the non-trivial destructors of its members and bases as
5557 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5558 CXXRecordDecl *Record);
5560 /// \brief The list of classes whose vtables have been used within
5561 /// this translation unit, and the source locations at which the
5562 /// first use occurred.
5563 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5565 /// \brief The list of vtables that are required but have not yet been
5567 SmallVector<VTableUse, 16> VTableUses;
5569 /// \brief The set of classes whose vtables have been used within
5570 /// this translation unit, and a bit that will be true if the vtable is
5571 /// required to be emitted (otherwise, it should be emitted only if needed
5572 /// by code generation).
5573 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5575 /// \brief Load any externally-stored vtable uses.
5576 void LoadExternalVTableUses();
5578 /// \brief Note that the vtable for the given class was used at the
5580 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5581 bool DefinitionRequired = false);
5583 /// \brief Mark the exception specifications of all virtual member functions
5584 /// in the given class as needed.
5585 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5586 const CXXRecordDecl *RD);
5588 /// MarkVirtualMembersReferenced - Will mark all members of the given
5589 /// CXXRecordDecl referenced.
5590 void MarkVirtualMembersReferenced(SourceLocation Loc,
5591 const CXXRecordDecl *RD);
5593 /// \brief Define all of the vtables that have been used in this
5594 /// translation unit and reference any virtual members used by those
5597 /// \returns true if any work was done, false otherwise.
5598 bool DefineUsedVTables();
5600 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5602 void ActOnMemInitializers(Decl *ConstructorDecl,
5603 SourceLocation ColonLoc,
5604 ArrayRef<CXXCtorInitializer*> MemInits,
5607 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5608 /// ensure that referenceDLLExportedClassMethods is called some point later
5609 /// when all outer classes of Class are complete.
5610 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5612 void referenceDLLExportedClassMethods();
5614 void propagateDLLAttrToBaseClassTemplate(
5615 CXXRecordDecl *Class, Attr *ClassAttr,
5616 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5617 SourceLocation BaseLoc);
5619 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5620 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5622 SourceLocation LBrac,
5623 SourceLocation RBrac,
5624 AttributeList *AttrList);
5625 void ActOnFinishCXXMemberDecls();
5626 void ActOnFinishCXXNonNestedClass(Decl *D);
5628 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5629 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5630 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5631 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5632 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5633 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5634 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5635 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5636 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5637 CachedTokens &Toks);
5638 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5639 bool IsInsideALocalClassWithinATemplateFunction();
5641 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5643 Expr *AssertMessageExpr,
5644 SourceLocation RParenLoc);
5645 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5647 StringLiteral *AssertMessageExpr,
5648 SourceLocation RParenLoc,
5651 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5652 SourceLocation FriendLoc,
5653 TypeSourceInfo *TSInfo);
5654 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5655 MultiTemplateParamsArg TemplateParams);
5656 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5657 MultiTemplateParamsArg TemplateParams);
5659 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5661 void CheckConstructor(CXXConstructorDecl *Constructor);
5662 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5664 bool CheckDestructor(CXXDestructorDecl *Destructor);
5665 void CheckConversionDeclarator(Declarator &D, QualType &R,
5667 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5668 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5670 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5672 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5673 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5674 const FunctionProtoType *T);
5675 void CheckDelayedMemberExceptionSpecs();
5677 //===--------------------------------------------------------------------===//
5678 // C++ Derived Classes
5681 /// ActOnBaseSpecifier - Parsed a base specifier
5682 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5683 SourceRange SpecifierRange,
5684 bool Virtual, AccessSpecifier Access,
5685 TypeSourceInfo *TInfo,
5686 SourceLocation EllipsisLoc);
5688 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5689 SourceRange SpecifierRange,
5690 ParsedAttributes &Attrs,
5691 bool Virtual, AccessSpecifier Access,
5692 ParsedType basetype,
5693 SourceLocation BaseLoc,
5694 SourceLocation EllipsisLoc);
5696 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5697 MutableArrayRef<CXXBaseSpecifier *> Bases);
5698 void ActOnBaseSpecifiers(Decl *ClassDecl,
5699 MutableArrayRef<CXXBaseSpecifier *> Bases);
5701 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5702 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5703 CXXBasePaths &Paths);
5705 // FIXME: I don't like this name.
5706 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5708 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5709 SourceLocation Loc, SourceRange Range,
5710 CXXCastPath *BasePath = nullptr,
5711 bool IgnoreAccess = false);
5712 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5713 unsigned InaccessibleBaseID,
5714 unsigned AmbigiousBaseConvID,
5715 SourceLocation Loc, SourceRange Range,
5716 DeclarationName Name,
5717 CXXCastPath *BasePath,
5718 bool IgnoreAccess = false);
5720 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5722 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5723 const CXXMethodDecl *Old);
5725 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5726 /// covariant, according to C++ [class.virtual]p5.
5727 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5728 const CXXMethodDecl *Old);
5730 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5731 /// spec is a subset of base spec.
5732 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5733 const CXXMethodDecl *Old);
5735 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5737 /// CheckOverrideControl - Check C++11 override control semantics.
5738 void CheckOverrideControl(NamedDecl *D);
5740 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5741 /// not used in the declaration of an overriding method.
5742 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5744 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5745 /// overrides a virtual member function marked 'final', according to
5746 /// C++11 [class.virtual]p4.
5747 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5748 const CXXMethodDecl *Old);
5751 //===--------------------------------------------------------------------===//
5752 // C++ Access Control
5762 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5763 NamedDecl *PrevMemberDecl,
5764 AccessSpecifier LexicalAS);
5766 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5767 DeclAccessPair FoundDecl);
5768 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5769 DeclAccessPair FoundDecl);
5770 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5771 SourceRange PlacementRange,
5772 CXXRecordDecl *NamingClass,
5773 DeclAccessPair FoundDecl,
5774 bool Diagnose = true);
5775 AccessResult CheckConstructorAccess(SourceLocation Loc,
5776 CXXConstructorDecl *D,
5777 DeclAccessPair FoundDecl,
5778 const InitializedEntity &Entity,
5779 bool IsCopyBindingRefToTemp = false);
5780 AccessResult CheckConstructorAccess(SourceLocation Loc,
5781 CXXConstructorDecl *D,
5782 DeclAccessPair FoundDecl,
5783 const InitializedEntity &Entity,
5784 const PartialDiagnostic &PDiag);
5785 AccessResult CheckDestructorAccess(SourceLocation Loc,
5786 CXXDestructorDecl *Dtor,
5787 const PartialDiagnostic &PDiag,
5788 QualType objectType = QualType());
5789 AccessResult CheckFriendAccess(NamedDecl *D);
5790 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5791 CXXRecordDecl *NamingClass,
5792 DeclAccessPair Found);
5793 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5796 DeclAccessPair FoundDecl);
5797 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5798 DeclAccessPair FoundDecl);
5799 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5800 QualType Base, QualType Derived,
5801 const CXXBasePath &Path,
5803 bool ForceCheck = false,
5804 bool ForceUnprivileged = false);
5805 void CheckLookupAccess(const LookupResult &R);
5806 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5807 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5808 AccessSpecifier access,
5809 QualType objectType);
5811 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5812 const MultiLevelTemplateArgumentList &TemplateArgs);
5813 void PerformDependentDiagnostics(const DeclContext *Pattern,
5814 const MultiLevelTemplateArgumentList &TemplateArgs);
5816 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5818 /// \brief When true, access checking violations are treated as SFINAE
5819 /// failures rather than hard errors.
5820 bool AccessCheckingSFINAE;
5822 enum AbstractDiagSelID {
5826 AbstractVariableType,
5829 AbstractSynthesizedIvarType,
5833 bool isAbstractType(SourceLocation Loc, QualType T);
5834 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5835 TypeDiagnoser &Diagnoser);
5836 template <typename... Ts>
5837 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5838 const Ts &...Args) {
5839 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5840 return RequireNonAbstractType(Loc, T, Diagnoser);
5843 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5845 //===--------------------------------------------------------------------===//
5846 // C++ Overloaded Operators [C++ 13.5]
5849 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5851 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5853 //===--------------------------------------------------------------------===//
5854 // C++ Templates [C++ 14]
5856 void FilterAcceptableTemplateNames(LookupResult &R,
5857 bool AllowFunctionTemplates = true);
5858 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5859 bool AllowFunctionTemplates = true);
5861 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5862 QualType ObjectType, bool EnteringContext,
5863 bool &MemberOfUnknownSpecialization);
5865 TemplateNameKind isTemplateName(Scope *S,
5867 bool hasTemplateKeyword,
5868 UnqualifiedId &Name,
5869 ParsedType ObjectType,
5870 bool EnteringContext,
5871 TemplateTy &Template,
5872 bool &MemberOfUnknownSpecialization);
5874 /// Determine whether a particular identifier might be the name in a C++1z
5875 /// deduction-guide declaration.
5876 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5877 SourceLocation NameLoc,
5878 ParsedTemplateTy *Template = nullptr);
5880 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5881 SourceLocation IILoc,
5883 const CXXScopeSpec *SS,
5884 TemplateTy &SuggestedTemplate,
5885 TemplateNameKind &SuggestedKind);
5887 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5888 NamedDecl *Instantiation,
5889 bool InstantiatedFromMember,
5890 const NamedDecl *Pattern,
5891 const NamedDecl *PatternDef,
5892 TemplateSpecializationKind TSK,
5893 bool Complain = true);
5895 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5896 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5898 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5899 SourceLocation EllipsisLoc,
5900 SourceLocation KeyLoc,
5901 IdentifierInfo *ParamName,
5902 SourceLocation ParamNameLoc,
5903 unsigned Depth, unsigned Position,
5904 SourceLocation EqualLoc,
5905 ParsedType DefaultArg);
5907 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5908 SourceLocation Loc);
5909 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5911 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5914 SourceLocation EqualLoc,
5916 Decl *ActOnTemplateTemplateParameter(Scope *S,
5917 SourceLocation TmpLoc,
5918 TemplateParameterList *Params,
5919 SourceLocation EllipsisLoc,
5920 IdentifierInfo *ParamName,
5921 SourceLocation ParamNameLoc,
5924 SourceLocation EqualLoc,
5925 ParsedTemplateArgument DefaultArg);
5927 TemplateParameterList *
5928 ActOnTemplateParameterList(unsigned Depth,
5929 SourceLocation ExportLoc,
5930 SourceLocation TemplateLoc,
5931 SourceLocation LAngleLoc,
5932 ArrayRef<Decl *> Params,
5933 SourceLocation RAngleLoc,
5934 Expr *RequiresClause);
5936 /// \brief The context in which we are checking a template parameter list.
5937 enum TemplateParamListContext {
5940 TPC_FunctionTemplate,
5941 TPC_ClassTemplateMember,
5942 TPC_FriendClassTemplate,
5943 TPC_FriendFunctionTemplate,
5944 TPC_FriendFunctionTemplateDefinition,
5945 TPC_TypeAliasTemplate
5948 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5949 TemplateParameterList *OldParams,
5950 TemplateParamListContext TPC);
5951 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5952 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5953 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5954 ArrayRef<TemplateParameterList *> ParamLists,
5955 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5957 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5958 SourceLocation KWLoc, CXXScopeSpec &SS,
5959 IdentifierInfo *Name, SourceLocation NameLoc,
5960 AttributeList *Attr,
5961 TemplateParameterList *TemplateParams,
5963 SourceLocation ModulePrivateLoc,
5964 SourceLocation FriendLoc,
5965 unsigned NumOuterTemplateParamLists,
5966 TemplateParameterList **OuterTemplateParamLists,
5967 SkipBodyInfo *SkipBody = nullptr);
5969 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
5971 SourceLocation Loc);
5973 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5974 TemplateArgumentListInfo &Out);
5976 void NoteAllFoundTemplates(TemplateName Name);
5978 QualType CheckTemplateIdType(TemplateName Template,
5979 SourceLocation TemplateLoc,
5980 TemplateArgumentListInfo &TemplateArgs);
5983 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5984 TemplateTy Template, IdentifierInfo *TemplateII,
5985 SourceLocation TemplateIILoc,
5986 SourceLocation LAngleLoc,
5987 ASTTemplateArgsPtr TemplateArgs,
5988 SourceLocation RAngleLoc,
5989 bool IsCtorOrDtorName = false,
5990 bool IsClassName = false);
5992 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5993 /// such as \c class T::template apply<U>.
5994 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5995 TypeSpecifierType TagSpec,
5996 SourceLocation TagLoc,
5998 SourceLocation TemplateKWLoc,
5999 TemplateTy TemplateD,
6000 SourceLocation TemplateLoc,
6001 SourceLocation LAngleLoc,
6002 ASTTemplateArgsPtr TemplateArgsIn,
6003 SourceLocation RAngleLoc);
6005 DeclResult ActOnVarTemplateSpecialization(
6006 Scope *S, Declarator &D, TypeSourceInfo *DI,
6007 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6008 StorageClass SC, bool IsPartialSpecialization);
6010 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6011 SourceLocation TemplateLoc,
6012 SourceLocation TemplateNameLoc,
6013 const TemplateArgumentListInfo &TemplateArgs);
6015 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6016 const DeclarationNameInfo &NameInfo,
6017 VarTemplateDecl *Template,
6018 SourceLocation TemplateLoc,
6019 const TemplateArgumentListInfo *TemplateArgs);
6021 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6022 SourceLocation TemplateKWLoc,
6025 const TemplateArgumentListInfo *TemplateArgs);
6027 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6028 SourceLocation TemplateKWLoc,
6029 const DeclarationNameInfo &NameInfo,
6030 const TemplateArgumentListInfo *TemplateArgs);
6032 TemplateNameKind ActOnDependentTemplateName(
6033 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6034 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6035 TemplateTy &Template, bool AllowInjectedClassName = false);
6038 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6039 SourceLocation KWLoc,
6040 SourceLocation ModulePrivateLoc,
6041 TemplateIdAnnotation &TemplateId,
6042 AttributeList *Attr,
6043 MultiTemplateParamsArg TemplateParameterLists,
6044 SkipBodyInfo *SkipBody = nullptr);
6046 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6047 TemplateDecl *PrimaryTemplate,
6048 unsigned NumExplicitArgs,
6049 ArrayRef<TemplateArgument> Args);
6050 void CheckTemplatePartialSpecialization(
6051 ClassTemplatePartialSpecializationDecl *Partial);
6052 void CheckTemplatePartialSpecialization(
6053 VarTemplatePartialSpecializationDecl *Partial);
6055 Decl *ActOnTemplateDeclarator(Scope *S,
6056 MultiTemplateParamsArg TemplateParameterLists,
6060 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6061 TemplateSpecializationKind NewTSK,
6062 NamedDecl *PrevDecl,
6063 TemplateSpecializationKind PrevTSK,
6064 SourceLocation PrevPtOfInstantiation,
6067 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6068 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6069 LookupResult &Previous);
6071 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6072 TemplateArgumentListInfo *ExplicitTemplateArgs,
6073 LookupResult &Previous);
6074 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6077 ActOnExplicitInstantiation(Scope *S,
6078 SourceLocation ExternLoc,
6079 SourceLocation TemplateLoc,
6081 SourceLocation KWLoc,
6082 const CXXScopeSpec &SS,
6083 TemplateTy Template,
6084 SourceLocation TemplateNameLoc,
6085 SourceLocation LAngleLoc,
6086 ASTTemplateArgsPtr TemplateArgs,
6087 SourceLocation RAngleLoc,
6088 AttributeList *Attr);
6091 ActOnExplicitInstantiation(Scope *S,
6092 SourceLocation ExternLoc,
6093 SourceLocation TemplateLoc,
6095 SourceLocation KWLoc,
6097 IdentifierInfo *Name,
6098 SourceLocation NameLoc,
6099 AttributeList *Attr);
6101 DeclResult ActOnExplicitInstantiation(Scope *S,
6102 SourceLocation ExternLoc,
6103 SourceLocation TemplateLoc,
6107 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6108 SourceLocation TemplateLoc,
6109 SourceLocation RAngleLoc,
6111 SmallVectorImpl<TemplateArgument>
6113 bool &HasDefaultArg);
6115 /// \brief Specifies the context in which a particular template
6116 /// argument is being checked.
6117 enum CheckTemplateArgumentKind {
6118 /// \brief The template argument was specified in the code or was
6119 /// instantiated with some deduced template arguments.
6122 /// \brief The template argument was deduced via template argument
6126 /// \brief The template argument was deduced from an array bound
6127 /// via template argument deduction.
6128 CTAK_DeducedFromArrayBound
6131 bool CheckTemplateArgument(NamedDecl *Param,
6132 TemplateArgumentLoc &Arg,
6133 NamedDecl *Template,
6134 SourceLocation TemplateLoc,
6135 SourceLocation RAngleLoc,
6136 unsigned ArgumentPackIndex,
6137 SmallVectorImpl<TemplateArgument> &Converted,
6138 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6140 /// \brief Check that the given template arguments can be be provided to
6141 /// the given template, converting the arguments along the way.
6143 /// \param Template The template to which the template arguments are being
6146 /// \param TemplateLoc The location of the template name in the source.
6148 /// \param TemplateArgs The list of template arguments. If the template is
6149 /// a template template parameter, this function may extend the set of
6150 /// template arguments to also include substituted, defaulted template
6153 /// \param PartialTemplateArgs True if the list of template arguments is
6154 /// intentionally partial, e.g., because we're checking just the initial
6155 /// set of template arguments.
6157 /// \param Converted Will receive the converted, canonicalized template
6160 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6161 /// contain the converted forms of the template arguments as written.
6162 /// Otherwise, \p TemplateArgs will not be modified.
6164 /// \returns true if an error occurred, false otherwise.
6165 bool CheckTemplateArgumentList(TemplateDecl *Template,
6166 SourceLocation TemplateLoc,
6167 TemplateArgumentListInfo &TemplateArgs,
6168 bool PartialTemplateArgs,
6169 SmallVectorImpl<TemplateArgument> &Converted,
6170 bool UpdateArgsWithConversions = true);
6172 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6173 TemplateArgumentLoc &Arg,
6174 SmallVectorImpl<TemplateArgument> &Converted);
6176 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6177 TypeSourceInfo *Arg);
6178 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6179 QualType InstantiatedParamType, Expr *Arg,
6180 TemplateArgument &Converted,
6181 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6182 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6183 TemplateArgumentLoc &Arg,
6184 unsigned ArgumentPackIndex);
6187 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6189 SourceLocation Loc);
6191 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6192 SourceLocation Loc);
6194 /// \brief Enumeration describing how template parameter lists are compared
6196 enum TemplateParameterListEqualKind {
6197 /// \brief We are matching the template parameter lists of two templates
6198 /// that might be redeclarations.
6201 /// template<typename T> struct X;
6202 /// template<typename T> struct X;
6206 /// \brief We are matching the template parameter lists of two template
6207 /// template parameters as part of matching the template parameter lists
6208 /// of two templates that might be redeclarations.
6211 /// template<template<int I> class TT> struct X;
6212 /// template<template<int Value> class Other> struct X;
6214 TPL_TemplateTemplateParmMatch,
6216 /// \brief We are matching the template parameter lists of a template
6217 /// template argument against the template parameter lists of a template
6218 /// template parameter.
6221 /// template<template<int Value> class Metafun> struct X;
6222 /// template<int Value> struct integer_c;
6223 /// X<integer_c> xic;
6225 TPL_TemplateTemplateArgumentMatch
6228 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6229 TemplateParameterList *Old,
6231 TemplateParameterListEqualKind Kind,
6232 SourceLocation TemplateArgLoc
6233 = SourceLocation());
6235 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6237 /// \brief Called when the parser has parsed a C++ typename
6238 /// specifier, e.g., "typename T::type".
6240 /// \param S The scope in which this typename type occurs.
6241 /// \param TypenameLoc the location of the 'typename' keyword
6242 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6243 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6244 /// \param IdLoc the location of the identifier.
6246 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6247 const CXXScopeSpec &SS, const IdentifierInfo &II,
6248 SourceLocation IdLoc);
6250 /// \brief Called when the parser has parsed a C++ typename
6251 /// specifier that ends in a template-id, e.g.,
6252 /// "typename MetaFun::template apply<T1, T2>".
6254 /// \param S The scope in which this typename type occurs.
6255 /// \param TypenameLoc the location of the 'typename' keyword
6256 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6257 /// \param TemplateLoc the location of the 'template' keyword, if any.
6258 /// \param TemplateName The template name.
6259 /// \param TemplateII The identifier used to name the template.
6260 /// \param TemplateIILoc The location of the template name.
6261 /// \param LAngleLoc The location of the opening angle bracket ('<').
6262 /// \param TemplateArgs The template arguments.
6263 /// \param RAngleLoc The location of the closing angle bracket ('>').
6265 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6266 const CXXScopeSpec &SS,
6267 SourceLocation TemplateLoc,
6268 TemplateTy TemplateName,
6269 IdentifierInfo *TemplateII,
6270 SourceLocation TemplateIILoc,
6271 SourceLocation LAngleLoc,
6272 ASTTemplateArgsPtr TemplateArgs,
6273 SourceLocation RAngleLoc);
6275 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6276 SourceLocation KeywordLoc,
6277 NestedNameSpecifierLoc QualifierLoc,
6278 const IdentifierInfo &II,
6279 SourceLocation IILoc);
6281 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6283 DeclarationName Name);
6284 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6286 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6287 bool RebuildTemplateParamsInCurrentInstantiation(
6288 TemplateParameterList *Params);
6291 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6292 const TemplateArgumentList &Args);
6295 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6296 const TemplateArgument *Args,
6299 //===--------------------------------------------------------------------===//
6300 // C++ Variadic Templates (C++0x [temp.variadic])
6301 //===--------------------------------------------------------------------===//
6303 /// Determine whether an unexpanded parameter pack might be permitted in this
6304 /// location. Useful for error recovery.
6305 bool isUnexpandedParameterPackPermitted();
6307 /// \brief The context in which an unexpanded parameter pack is
6308 /// being diagnosed.
6310 /// Note that the values of this enumeration line up with the first
6311 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6312 enum UnexpandedParameterPackContext {
6313 /// \brief An arbitrary expression.
6314 UPPC_Expression = 0,
6316 /// \brief The base type of a class type.
6319 /// \brief The type of an arbitrary declaration.
6320 UPPC_DeclarationType,
6322 /// \brief The type of a data member.
6323 UPPC_DataMemberType,
6325 /// \brief The size of a bit-field.
6328 /// \brief The expression in a static assertion.
6329 UPPC_StaticAssertExpression,
6331 /// \brief The fixed underlying type of an enumeration.
6332 UPPC_FixedUnderlyingType,
6334 /// \brief The enumerator value.
6335 UPPC_EnumeratorValue,
6337 /// \brief A using declaration.
6338 UPPC_UsingDeclaration,
6340 /// \brief A friend declaration.
6341 UPPC_FriendDeclaration,
6343 /// \brief A declaration qualifier.
6344 UPPC_DeclarationQualifier,
6346 /// \brief An initializer.
6349 /// \brief A default argument.
6350 UPPC_DefaultArgument,
6352 /// \brief The type of a non-type template parameter.
6353 UPPC_NonTypeTemplateParameterType,
6355 /// \brief The type of an exception.
6358 /// \brief Partial specialization.
6359 UPPC_PartialSpecialization,
6361 /// \brief Microsoft __if_exists.
6364 /// \brief Microsoft __if_not_exists.
6367 /// \brief Lambda expression.
6370 /// \brief Block expression,
6374 /// \brief Diagnose unexpanded parameter packs.
6376 /// \param Loc The location at which we should emit the diagnostic.
6378 /// \param UPPC The context in which we are diagnosing unexpanded
6379 /// parameter packs.
6381 /// \param Unexpanded the set of unexpanded parameter packs.
6383 /// \returns true if an error occurred, false otherwise.
6384 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6385 UnexpandedParameterPackContext UPPC,
6386 ArrayRef<UnexpandedParameterPack> Unexpanded);
6388 /// \brief If the given type contains an unexpanded parameter pack,
6389 /// diagnose the error.
6391 /// \param Loc The source location where a diagnostc should be emitted.
6393 /// \param T The type that is being checked for unexpanded parameter
6396 /// \returns true if an error occurred, false otherwise.
6397 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6398 UnexpandedParameterPackContext UPPC);
6400 /// \brief If the given expression contains an unexpanded parameter
6401 /// pack, diagnose the error.
6403 /// \param E The expression that is being checked for unexpanded
6404 /// parameter packs.
6406 /// \returns true if an error occurred, false otherwise.
6407 bool DiagnoseUnexpandedParameterPack(Expr *E,
6408 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6410 /// \brief If the given nested-name-specifier contains an unexpanded
6411 /// parameter pack, diagnose the error.
6413 /// \param SS The nested-name-specifier that is being checked for
6414 /// unexpanded parameter packs.
6416 /// \returns true if an error occurred, false otherwise.
6417 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6418 UnexpandedParameterPackContext UPPC);
6420 /// \brief If the given name contains an unexpanded parameter pack,
6421 /// diagnose the error.
6423 /// \param NameInfo The name (with source location information) that
6424 /// is being checked for unexpanded parameter packs.
6426 /// \returns true if an error occurred, false otherwise.
6427 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6428 UnexpandedParameterPackContext UPPC);
6430 /// \brief If the given template name contains an unexpanded parameter pack,
6431 /// diagnose the error.
6433 /// \param Loc The location of the template name.
6435 /// \param Template The template name that is being checked for unexpanded
6436 /// parameter packs.
6438 /// \returns true if an error occurred, false otherwise.
6439 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6440 TemplateName Template,
6441 UnexpandedParameterPackContext UPPC);
6443 /// \brief If the given template argument contains an unexpanded parameter
6444 /// pack, diagnose the error.
6446 /// \param Arg The template argument that is being checked for unexpanded
6447 /// parameter packs.
6449 /// \returns true if an error occurred, false otherwise.
6450 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6451 UnexpandedParameterPackContext UPPC);
6453 /// \brief Collect the set of unexpanded parameter packs within the given
6454 /// template argument.
6456 /// \param Arg The template argument that will be traversed to find
6457 /// unexpanded parameter packs.
6458 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6459 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6461 /// \brief Collect the set of unexpanded parameter packs within the given
6462 /// template argument.
6464 /// \param Arg The template argument that will be traversed to find
6465 /// unexpanded parameter packs.
6466 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6467 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6469 /// \brief Collect the set of unexpanded parameter packs within the given
6472 /// \param T The type that will be traversed to find
6473 /// unexpanded parameter packs.
6474 void collectUnexpandedParameterPacks(QualType T,
6475 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6477 /// \brief Collect the set of unexpanded parameter packs within the given
6480 /// \param TL The type that will be traversed to find
6481 /// unexpanded parameter packs.
6482 void collectUnexpandedParameterPacks(TypeLoc TL,
6483 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6485 /// \brief Collect the set of unexpanded parameter packs within the given
6486 /// nested-name-specifier.
6488 /// \param NNS The nested-name-specifier that will be traversed to find
6489 /// unexpanded parameter packs.
6490 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6491 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6493 /// \brief Collect the set of unexpanded parameter packs within the given
6496 /// \param NameInfo The name that will be traversed to find
6497 /// unexpanded parameter packs.
6498 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6499 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6501 /// \brief Invoked when parsing a template argument followed by an
6502 /// ellipsis, which creates a pack expansion.
6504 /// \param Arg The template argument preceding the ellipsis, which
6505 /// may already be invalid.
6507 /// \param EllipsisLoc The location of the ellipsis.
6508 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6509 SourceLocation EllipsisLoc);
6511 /// \brief Invoked when parsing a type followed by an ellipsis, which
6512 /// creates a pack expansion.
6514 /// \param Type The type preceding the ellipsis, which will become
6515 /// the pattern of the pack expansion.
6517 /// \param EllipsisLoc The location of the ellipsis.
6518 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6520 /// \brief Construct a pack expansion type from the pattern of the pack
6522 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6523 SourceLocation EllipsisLoc,
6524 Optional<unsigned> NumExpansions);
6526 /// \brief Construct a pack expansion type from the pattern of the pack
6528 QualType CheckPackExpansion(QualType Pattern,
6529 SourceRange PatternRange,
6530 SourceLocation EllipsisLoc,
6531 Optional<unsigned> NumExpansions);
6533 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6534 /// creates a pack expansion.
6536 /// \param Pattern The expression preceding the ellipsis, which will become
6537 /// the pattern of the pack expansion.
6539 /// \param EllipsisLoc The location of the ellipsis.
6540 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6542 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6543 /// creates a pack expansion.
6545 /// \param Pattern The expression preceding the ellipsis, which will become
6546 /// the pattern of the pack expansion.
6548 /// \param EllipsisLoc The location of the ellipsis.
6549 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6550 Optional<unsigned> NumExpansions);
6552 /// \brief Determine whether we could expand a pack expansion with the
6553 /// given set of parameter packs into separate arguments by repeatedly
6554 /// transforming the pattern.
6556 /// \param EllipsisLoc The location of the ellipsis that identifies the
6559 /// \param PatternRange The source range that covers the entire pattern of
6560 /// the pack expansion.
6562 /// \param Unexpanded The set of unexpanded parameter packs within the
6565 /// \param ShouldExpand Will be set to \c true if the transformer should
6566 /// expand the corresponding pack expansions into separate arguments. When
6567 /// set, \c NumExpansions must also be set.
6569 /// \param RetainExpansion Whether the caller should add an unexpanded
6570 /// pack expansion after all of the expanded arguments. This is used
6571 /// when extending explicitly-specified template argument packs per
6572 /// C++0x [temp.arg.explicit]p9.
6574 /// \param NumExpansions The number of separate arguments that will be in
6575 /// the expanded form of the corresponding pack expansion. This is both an
6576 /// input and an output parameter, which can be set by the caller if the
6577 /// number of expansions is known a priori (e.g., due to a prior substitution)
6578 /// and will be set by the callee when the number of expansions is known.
6579 /// The callee must set this value when \c ShouldExpand is \c true; it may
6580 /// set this value in other cases.
6582 /// \returns true if an error occurred (e.g., because the parameter packs
6583 /// are to be instantiated with arguments of different lengths), false
6584 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6586 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6587 SourceRange PatternRange,
6588 ArrayRef<UnexpandedParameterPack> Unexpanded,
6589 const MultiLevelTemplateArgumentList &TemplateArgs,
6591 bool &RetainExpansion,
6592 Optional<unsigned> &NumExpansions);
6594 /// \brief Determine the number of arguments in the given pack expansion
6597 /// This routine assumes that the number of arguments in the expansion is
6598 /// consistent across all of the unexpanded parameter packs in its pattern.
6600 /// Returns an empty Optional if the type can't be expanded.
6601 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6602 const MultiLevelTemplateArgumentList &TemplateArgs);
6604 /// \brief Determine whether the given declarator contains any unexpanded
6605 /// parameter packs.
6607 /// This routine is used by the parser to disambiguate function declarators
6608 /// with an ellipsis prior to the ')', e.g.,
6614 /// To determine whether we have an (unnamed) function parameter pack or
6615 /// a variadic function.
6617 /// \returns true if the declarator contains any unexpanded parameter packs,
6618 /// false otherwise.
6619 bool containsUnexpandedParameterPacks(Declarator &D);
6621 /// \brief Returns the pattern of the pack expansion for a template argument.
6623 /// \param OrigLoc The template argument to expand.
6625 /// \param Ellipsis Will be set to the location of the ellipsis.
6627 /// \param NumExpansions Will be set to the number of expansions that will
6628 /// be generated from this pack expansion, if known a priori.
6629 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6630 TemplateArgumentLoc OrigLoc,
6631 SourceLocation &Ellipsis,
6632 Optional<unsigned> &NumExpansions) const;
6634 /// Given a template argument that contains an unexpanded parameter pack, but
6635 /// which has already been substituted, attempt to determine the number of
6636 /// elements that will be produced once this argument is fully-expanded.
6638 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6639 /// avoid actually expanding the pack where possible.
6640 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6642 //===--------------------------------------------------------------------===//
6643 // C++ Template Argument Deduction (C++ [temp.deduct])
6644 //===--------------------------------------------------------------------===//
6646 /// Adjust the type \p ArgFunctionType to match the calling convention,
6647 /// noreturn, and optionally the exception specification of \p FunctionType.
6648 /// Deduction often wants to ignore these properties when matching function
6650 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6651 bool AdjustExceptionSpec = false);
6653 /// \brief Describes the result of template argument deduction.
6655 /// The TemplateDeductionResult enumeration describes the result of
6656 /// template argument deduction, as returned from
6657 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6658 /// structure provides additional information about the results of
6659 /// template argument deduction, e.g., the deduced template argument
6660 /// list (if successful) or the specific template parameters or
6661 /// deduced arguments that were involved in the failure.
6662 enum TemplateDeductionResult {
6663 /// \brief Template argument deduction was successful.
6665 /// \brief The declaration was invalid; do nothing.
6667 /// \brief Template argument deduction exceeded the maximum template
6668 /// instantiation depth (which has already been diagnosed).
6669 TDK_InstantiationDepth,
6670 /// \brief Template argument deduction did not deduce a value
6671 /// for every template parameter.
6673 /// \brief Template argument deduction produced inconsistent
6674 /// deduced values for the given template parameter.
6676 /// \brief Template argument deduction failed due to inconsistent
6677 /// cv-qualifiers on a template parameter type that would
6678 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6679 /// but were given a non-const "X".
6681 /// \brief Substitution of the deduced template argument values
6682 /// resulted in an error.
6683 TDK_SubstitutionFailure,
6684 /// \brief After substituting deduced template arguments, a dependent
6685 /// parameter type did not match the corresponding argument.
6686 TDK_DeducedMismatch,
6687 /// \brief After substituting deduced template arguments, an element of
6688 /// a dependent parameter type did not match the corresponding element
6689 /// of the corresponding argument (when deducing from an initializer list).
6690 TDK_DeducedMismatchNested,
6691 /// \brief A non-depnedent component of the parameter did not match the
6692 /// corresponding component of the argument.
6693 TDK_NonDeducedMismatch,
6694 /// \brief When performing template argument deduction for a function
6695 /// template, there were too many call arguments.
6696 TDK_TooManyArguments,
6697 /// \brief When performing template argument deduction for a function
6698 /// template, there were too few call arguments.
6699 TDK_TooFewArguments,
6700 /// \brief The explicitly-specified template arguments were not valid
6701 /// template arguments for the given template.
6702 TDK_InvalidExplicitArguments,
6703 /// \brief Checking non-dependent argument conversions failed.
6704 TDK_NonDependentConversionFailure,
6705 /// \brief Deduction failed; that's all we know.
6706 TDK_MiscellaneousDeductionFailure,
6707 /// \brief CUDA Target attributes do not match.
6708 TDK_CUDATargetMismatch
6711 TemplateDeductionResult
6712 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6713 const TemplateArgumentList &TemplateArgs,
6714 sema::TemplateDeductionInfo &Info);
6716 TemplateDeductionResult
6717 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6718 const TemplateArgumentList &TemplateArgs,
6719 sema::TemplateDeductionInfo &Info);
6721 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6722 FunctionTemplateDecl *FunctionTemplate,
6723 TemplateArgumentListInfo &ExplicitTemplateArgs,
6724 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6725 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6726 sema::TemplateDeductionInfo &Info);
6728 /// brief A function argument from which we performed template argument
6729 // deduction for a call.
6730 struct OriginalCallArg {
6731 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6732 unsigned ArgIdx, QualType OriginalArgType)
6733 : OriginalParamType(OriginalParamType),
6734 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6735 OriginalArgType(OriginalArgType) {}
6737 QualType OriginalParamType;
6738 bool DecomposedParam;
6740 QualType OriginalArgType;
6743 TemplateDeductionResult FinishTemplateArgumentDeduction(
6744 FunctionTemplateDecl *FunctionTemplate,
6745 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6746 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6747 sema::TemplateDeductionInfo &Info,
6748 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6749 bool PartialOverloading = false,
6750 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6752 TemplateDeductionResult DeduceTemplateArguments(
6753 FunctionTemplateDecl *FunctionTemplate,
6754 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6755 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6756 bool PartialOverloading,
6757 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6759 TemplateDeductionResult
6760 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6761 TemplateArgumentListInfo *ExplicitTemplateArgs,
6762 QualType ArgFunctionType,
6763 FunctionDecl *&Specialization,
6764 sema::TemplateDeductionInfo &Info,
6765 bool IsAddressOfFunction = false);
6767 TemplateDeductionResult
6768 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6770 CXXConversionDecl *&Specialization,
6771 sema::TemplateDeductionInfo &Info);
6773 TemplateDeductionResult
6774 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6775 TemplateArgumentListInfo *ExplicitTemplateArgs,
6776 FunctionDecl *&Specialization,
6777 sema::TemplateDeductionInfo &Info,
6778 bool IsAddressOfFunction = false);
6780 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6781 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6782 /// \brief Substitute Replacement for auto in TypeWithAuto
6783 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6784 QualType Replacement);
6785 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6786 /// \p Replacement. This does not retain any \c auto type sugar.
6787 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6789 /// \brief Result type of DeduceAutoType.
6790 enum DeduceAutoResult {
6793 DAR_FailedAlreadyDiagnosed
6797 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6798 Optional<unsigned> DependentDeductionDepth = None);
6800 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6801 Optional<unsigned> DependentDeductionDepth = None);
6802 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6803 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6804 bool Diagnose = true);
6806 /// \brief Declare implicit deduction guides for a class template if we've
6807 /// not already done so.
6808 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6809 SourceLocation Loc);
6811 QualType DeduceTemplateSpecializationFromInitializer(
6812 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6813 const InitializationKind &Kind, MultiExprArg Init);
6815 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6816 QualType Type, TypeSourceInfo *TSI,
6817 SourceRange Range, bool DirectInit,
6820 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6822 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6823 SourceLocation ReturnLoc,
6824 Expr *&RetExpr, AutoType *AT);
6826 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6827 FunctionTemplateDecl *FT2,
6829 TemplatePartialOrderingContext TPOC,
6830 unsigned NumCallArguments1,
6831 unsigned NumCallArguments2);
6832 UnresolvedSetIterator
6833 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6834 TemplateSpecCandidateSet &FailedCandidates,
6836 const PartialDiagnostic &NoneDiag,
6837 const PartialDiagnostic &AmbigDiag,
6838 const PartialDiagnostic &CandidateDiag,
6839 bool Complain = true, QualType TargetType = QualType());
6841 ClassTemplatePartialSpecializationDecl *
6842 getMoreSpecializedPartialSpecialization(
6843 ClassTemplatePartialSpecializationDecl *PS1,
6844 ClassTemplatePartialSpecializationDecl *PS2,
6845 SourceLocation Loc);
6847 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6848 sema::TemplateDeductionInfo &Info);
6850 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6851 VarTemplatePartialSpecializationDecl *PS1,
6852 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6854 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6855 sema::TemplateDeductionInfo &Info);
6857 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6858 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6860 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6863 llvm::SmallBitVector &Used);
6864 void MarkDeducedTemplateParameters(
6865 const FunctionTemplateDecl *FunctionTemplate,
6866 llvm::SmallBitVector &Deduced) {
6867 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6869 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6870 const FunctionTemplateDecl *FunctionTemplate,
6871 llvm::SmallBitVector &Deduced);
6873 //===--------------------------------------------------------------------===//
6874 // C++ Template Instantiation
6877 MultiLevelTemplateArgumentList
6878 getTemplateInstantiationArgs(NamedDecl *D,
6879 const TemplateArgumentList *Innermost = nullptr,
6880 bool RelativeToPrimary = false,
6881 const FunctionDecl *Pattern = nullptr);
6883 /// A context in which code is being synthesized (where a source location
6884 /// alone is not sufficient to identify the context). This covers template
6885 /// instantiation and various forms of implicitly-generated functions.
6886 struct CodeSynthesisContext {
6887 /// \brief The kind of template instantiation we are performing
6888 enum SynthesisKind {
6889 /// We are instantiating a template declaration. The entity is
6890 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6891 TemplateInstantiation,
6893 /// We are instantiating a default argument for a template
6894 /// parameter. The Entity is the template parameter whose argument is
6895 /// being instantiated, the Template is the template, and the
6896 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6898 DefaultTemplateArgumentInstantiation,
6900 /// We are instantiating a default argument for a function.
6901 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6902 /// provides the template arguments as specified.
6903 DefaultFunctionArgumentInstantiation,
6905 /// We are substituting explicit template arguments provided for
6906 /// a function template. The entity is a FunctionTemplateDecl.
6907 ExplicitTemplateArgumentSubstitution,
6909 /// We are substituting template argument determined as part of
6910 /// template argument deduction for either a class template
6911 /// partial specialization or a function template. The
6912 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6914 DeducedTemplateArgumentSubstitution,
6916 /// We are substituting prior template arguments into a new
6917 /// template parameter. The template parameter itself is either a
6918 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6919 PriorTemplateArgumentSubstitution,
6921 /// We are checking the validity of a default template argument that
6922 /// has been used when naming a template-id.
6923 DefaultTemplateArgumentChecking,
6925 /// We are instantiating the exception specification for a function
6926 /// template which was deferred until it was needed.
6927 ExceptionSpecInstantiation,
6929 /// We are declaring an implicit special member function.
6930 DeclaringSpecialMember,
6933 /// \brief Was the enclosing context a non-instantiation SFINAE context?
6934 bool SavedInNonInstantiationSFINAEContext;
6936 /// \brief The point of instantiation or synthesis within the source code.
6937 SourceLocation PointOfInstantiation;
6939 /// \brief The entity that is being synthesized.
6942 /// \brief The template (or partial specialization) in which we are
6943 /// performing the instantiation, for substitutions of prior template
6945 NamedDecl *Template;
6947 /// \brief The list of template arguments we are substituting, if they
6948 /// are not part of the entity.
6949 const TemplateArgument *TemplateArgs;
6951 // FIXME: Wrap this union around more members, or perhaps store the
6952 // kind-specific members in the RAII object owning the context.
6954 /// \brief The number of template arguments in TemplateArgs.
6955 unsigned NumTemplateArgs;
6957 /// \brief The special member being declared or defined.
6958 CXXSpecialMember SpecialMember;
6961 ArrayRef<TemplateArgument> template_arguments() const {
6962 assert(Kind != DeclaringSpecialMember);
6963 return {TemplateArgs, NumTemplateArgs};
6966 /// \brief The template deduction info object associated with the
6967 /// substitution or checking of explicit or deduced template arguments.
6968 sema::TemplateDeductionInfo *DeductionInfo;
6970 /// \brief The source range that covers the construct that cause
6971 /// the instantiation, e.g., the template-id that causes a class
6972 /// template instantiation.
6973 SourceRange InstantiationRange;
6975 CodeSynthesisContext()
6976 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
6977 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6979 /// \brief Determines whether this template is an actual instantiation
6980 /// that should be counted toward the maximum instantiation depth.
6981 bool isInstantiationRecord() const;
6984 /// \brief List of active code synthesis contexts.
6986 /// This vector is treated as a stack. As synthesis of one entity requires
6987 /// synthesis of another, additional contexts are pushed onto the stack.
6988 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
6990 /// Specializations whose definitions are currently being instantiated.
6991 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
6993 /// Non-dependent types used in templates that have already been instantiated
6994 /// by some template instantiation.
6995 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
6997 /// \brief Extra modules inspected when performing a lookup during a template
6998 /// instantiation. Computed lazily.
6999 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7001 /// \brief Cache of additional modules that should be used for name lookup
7002 /// within the current template instantiation. Computed lazily; use
7003 /// getLookupModules() to get a complete set.
7004 llvm::DenseSet<Module*> LookupModulesCache;
7006 /// \brief Get the set of additional modules that should be checked during
7007 /// name lookup. A module and its imports become visible when instanting a
7008 /// template defined within it.
7009 llvm::DenseSet<Module*> &getLookupModules();
7011 /// \brief Map from the most recent declaration of a namespace to the most
7012 /// recent visible declaration of that namespace.
7013 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7015 /// \brief Whether we are in a SFINAE context that is not associated with
7016 /// template instantiation.
7018 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7019 /// of a template instantiation or template argument deduction.
7020 bool InNonInstantiationSFINAEContext;
7022 /// \brief The number of \p CodeSynthesisContexts that are not template
7023 /// instantiations and, therefore, should not be counted as part of the
7024 /// instantiation depth.
7026 /// When the instantiation depth reaches the user-configurable limit
7027 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7028 // FIXME: Should we have a similar limit for other forms of synthesis?
7029 unsigned NonInstantiationEntries;
7031 /// \brief The depth of the context stack at the point when the most recent
7032 /// error or warning was produced.
7034 /// This value is used to suppress printing of redundant context stacks
7035 /// when there are multiple errors or warnings in the same instantiation.
7036 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7037 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7039 /// \brief The current index into pack expansion arguments that will be
7040 /// used for substitution of parameter packs.
7042 /// The pack expansion index will be -1 to indicate that parameter packs
7043 /// should be instantiated as themselves. Otherwise, the index specifies
7044 /// which argument within the parameter pack will be used for substitution.
7045 int ArgumentPackSubstitutionIndex;
7047 /// \brief RAII object used to change the argument pack substitution index
7048 /// within a \c Sema object.
7050 /// See \c ArgumentPackSubstitutionIndex for more information.
7051 class ArgumentPackSubstitutionIndexRAII {
7053 int OldSubstitutionIndex;
7056 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7057 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7058 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7061 ~ArgumentPackSubstitutionIndexRAII() {
7062 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7066 friend class ArgumentPackSubstitutionRAII;
7068 /// \brief For each declaration that involved template argument deduction, the
7069 /// set of diagnostics that were suppressed during that template argument
7072 /// FIXME: Serialize this structure to the AST file.
7073 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7074 SuppressedDiagnosticsMap;
7075 SuppressedDiagnosticsMap SuppressedDiagnostics;
7077 /// \brief A stack object to be created when performing template
7080 /// Construction of an object of type \c InstantiatingTemplate
7081 /// pushes the current instantiation onto the stack of active
7082 /// instantiations. If the size of this stack exceeds the maximum
7083 /// number of recursive template instantiations, construction
7084 /// produces an error and evaluates true.
7086 /// Destruction of this object will pop the named instantiation off
7088 struct InstantiatingTemplate {
7089 /// \brief Note that we are instantiating a class template,
7090 /// function template, variable template, alias template,
7091 /// or a member thereof.
7092 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7094 SourceRange InstantiationRange = SourceRange());
7096 struct ExceptionSpecification {};
7097 /// \brief Note that we are instantiating an exception specification
7098 /// of a function template.
7099 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7100 FunctionDecl *Entity, ExceptionSpecification,
7101 SourceRange InstantiationRange = SourceRange());
7103 /// \brief Note that we are instantiating a default argument in a
7105 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7106 TemplateParameter Param, TemplateDecl *Template,
7107 ArrayRef<TemplateArgument> TemplateArgs,
7108 SourceRange InstantiationRange = SourceRange());
7110 /// \brief Note that we are substituting either explicitly-specified or
7111 /// deduced template arguments during function template argument deduction.
7112 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7113 FunctionTemplateDecl *FunctionTemplate,
7114 ArrayRef<TemplateArgument> TemplateArgs,
7115 CodeSynthesisContext::SynthesisKind Kind,
7116 sema::TemplateDeductionInfo &DeductionInfo,
7117 SourceRange InstantiationRange = SourceRange());
7119 /// \brief Note that we are instantiating as part of template
7120 /// argument deduction for a class template declaration.
7121 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7122 TemplateDecl *Template,
7123 ArrayRef<TemplateArgument> TemplateArgs,
7124 sema::TemplateDeductionInfo &DeductionInfo,
7125 SourceRange InstantiationRange = SourceRange());
7127 /// \brief Note that we are instantiating as part of template
7128 /// argument deduction for a class template partial
7130 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7131 ClassTemplatePartialSpecializationDecl *PartialSpec,
7132 ArrayRef<TemplateArgument> TemplateArgs,
7133 sema::TemplateDeductionInfo &DeductionInfo,
7134 SourceRange InstantiationRange = SourceRange());
7136 /// \brief Note that we are instantiating as part of template
7137 /// argument deduction for a variable template partial
7139 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7140 VarTemplatePartialSpecializationDecl *PartialSpec,
7141 ArrayRef<TemplateArgument> TemplateArgs,
7142 sema::TemplateDeductionInfo &DeductionInfo,
7143 SourceRange InstantiationRange = SourceRange());
7145 /// \brief Note that we are instantiating a default argument for a function
7147 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7149 ArrayRef<TemplateArgument> TemplateArgs,
7150 SourceRange InstantiationRange = SourceRange());
7152 /// \brief Note that we are substituting prior template arguments into a
7153 /// non-type parameter.
7154 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7155 NamedDecl *Template,
7156 NonTypeTemplateParmDecl *Param,
7157 ArrayRef<TemplateArgument> TemplateArgs,
7158 SourceRange InstantiationRange);
7160 /// \brief Note that we are substituting prior template arguments into a
7161 /// template template parameter.
7162 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7163 NamedDecl *Template,
7164 TemplateTemplateParmDecl *Param,
7165 ArrayRef<TemplateArgument> TemplateArgs,
7166 SourceRange InstantiationRange);
7168 /// \brief Note that we are checking the default template argument
7169 /// against the template parameter for a given template-id.
7170 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7171 TemplateDecl *Template,
7173 ArrayRef<TemplateArgument> TemplateArgs,
7174 SourceRange InstantiationRange);
7177 /// \brief Note that we have finished instantiating this template.
7180 ~InstantiatingTemplate() { Clear(); }
7182 /// \brief Determines whether we have exceeded the maximum
7183 /// recursive template instantiations.
7184 bool isInvalid() const { return Invalid; }
7186 /// \brief Determine whether we are already instantiating this
7187 /// specialization in some surrounding active instantiation.
7188 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7193 bool AlreadyInstantiating;
7194 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7195 SourceRange InstantiationRange);
7197 InstantiatingTemplate(
7198 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7199 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7200 Decl *Entity, NamedDecl *Template = nullptr,
7201 ArrayRef<TemplateArgument> TemplateArgs = None,
7202 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7204 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7206 InstantiatingTemplate&
7207 operator=(const InstantiatingTemplate&) = delete;
7210 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7211 void popCodeSynthesisContext();
7213 /// Determine whether we are currently performing template instantiation.
7214 bool inTemplateInstantiation() const {
7215 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7218 void PrintContextStack() {
7219 if (!CodeSynthesisContexts.empty() &&
7220 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7221 PrintInstantiationStack();
7222 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7224 if (PragmaAttributeCurrentTargetDecl)
7225 PrintPragmaAttributeInstantiationPoint();
7227 void PrintInstantiationStack();
7229 void PrintPragmaAttributeInstantiationPoint();
7231 /// \brief Determines whether we are currently in a context where
7232 /// template argument substitution failures are not considered
7235 /// \returns An empty \c Optional if we're not in a SFINAE context.
7236 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7237 /// template-deduction context object, which can be used to capture
7238 /// diagnostics that will be suppressed.
7239 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7241 /// \brief Determines whether we are currently in a context that
7242 /// is not evaluated as per C++ [expr] p5.
7243 bool isUnevaluatedContext() const {
7244 assert(!ExprEvalContexts.empty() &&
7245 "Must be in an expression evaluation context");
7246 return ExprEvalContexts.back().isUnevaluated();
7249 /// \brief RAII class used to determine whether SFINAE has
7250 /// trapped any errors that occur during template argument
7254 unsigned PrevSFINAEErrors;
7255 bool PrevInNonInstantiationSFINAEContext;
7256 bool PrevAccessCheckingSFINAE;
7259 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7260 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7261 PrevInNonInstantiationSFINAEContext(
7262 SemaRef.InNonInstantiationSFINAEContext),
7263 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7265 if (!SemaRef.isSFINAEContext())
7266 SemaRef.InNonInstantiationSFINAEContext = true;
7267 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7271 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7272 SemaRef.InNonInstantiationSFINAEContext
7273 = PrevInNonInstantiationSFINAEContext;
7274 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7277 /// \brief Determine whether any SFINAE errors have been trapped.
7278 bool hasErrorOccurred() const {
7279 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7283 /// \brief RAII class used to indicate that we are performing provisional
7284 /// semantic analysis to determine the validity of a construct, so
7285 /// typo-correction and diagnostics in the immediate context (not within
7286 /// implicitly-instantiated templates) should be suppressed.
7287 class TentativeAnalysisScope {
7289 // FIXME: Using a SFINAETrap for this is a hack.
7291 bool PrevDisableTypoCorrection;
7293 explicit TentativeAnalysisScope(Sema &SemaRef)
7294 : SemaRef(SemaRef), Trap(SemaRef, true),
7295 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7296 SemaRef.DisableTypoCorrection = true;
7298 ~TentativeAnalysisScope() {
7299 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7303 /// \brief The current instantiation scope used to store local
7305 LocalInstantiationScope *CurrentInstantiationScope;
7307 /// \brief Tracks whether we are in a context where typo correction is
7309 bool DisableTypoCorrection;
7311 /// \brief The number of typos corrected by CorrectTypo.
7312 unsigned TyposCorrected;
7314 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7315 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7317 /// \brief A cache containing identifiers for which typo correction failed and
7318 /// their locations, so that repeated attempts to correct an identifier in a
7319 /// given location are ignored if typo correction already failed for it.
7320 IdentifierSourceLocations TypoCorrectionFailures;
7322 /// \brief Worker object for performing CFG-based warnings.
7323 sema::AnalysisBasedWarnings AnalysisWarnings;
7324 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7326 /// \brief An entity for which implicit template instantiation is required.
7328 /// The source location associated with the declaration is the first place in
7329 /// the source code where the declaration was "used". It is not necessarily
7330 /// the point of instantiation (which will be either before or after the
7331 /// namespace-scope declaration that triggered this implicit instantiation),
7332 /// However, it is the location that diagnostics should generally refer to,
7333 /// because users will need to know what code triggered the instantiation.
7334 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7336 /// \brief The queue of implicit template instantiations that are required
7337 /// but have not yet been performed.
7338 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7340 class SavePendingInstantiationsAndVTableUsesRAII {
7342 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7343 : S(S), Enabled(Enabled) {
7344 if (!Enabled) return;
7346 SavedPendingInstantiations.swap(S.PendingInstantiations);
7347 SavedVTableUses.swap(S.VTableUses);
7350 ~SavePendingInstantiationsAndVTableUsesRAII() {
7351 if (!Enabled) return;
7353 // Restore the set of pending vtables.
7354 assert(S.VTableUses.empty() &&
7355 "VTableUses should be empty before it is discarded.");
7356 S.VTableUses.swap(SavedVTableUses);
7358 // Restore the set of pending implicit instantiations.
7359 assert(S.PendingInstantiations.empty() &&
7360 "PendingInstantiations should be empty before it is discarded.");
7361 S.PendingInstantiations.swap(SavedPendingInstantiations);
7366 SmallVector<VTableUse, 16> SavedVTableUses;
7367 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7371 /// \brief The queue of implicit template instantiations that are required
7372 /// and must be performed within the current local scope.
7374 /// This queue is only used for member functions of local classes in
7375 /// templates, which must be instantiated in the same scope as their
7376 /// enclosing function, so that they can reference function-local
7377 /// types, static variables, enumerators, etc.
7378 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7380 class SavePendingLocalImplicitInstantiationsRAII {
7382 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7383 SavedPendingLocalImplicitInstantiations.swap(
7384 S.PendingLocalImplicitInstantiations);
7387 ~SavePendingLocalImplicitInstantiationsRAII() {
7388 assert(S.PendingLocalImplicitInstantiations.empty() &&
7389 "there shouldn't be any pending local implicit instantiations");
7390 SavedPendingLocalImplicitInstantiations.swap(
7391 S.PendingLocalImplicitInstantiations);
7396 std::deque<PendingImplicitInstantiation>
7397 SavedPendingLocalImplicitInstantiations;
7400 /// A helper class for building up ExtParameterInfos.
7401 class ExtParameterInfoBuilder {
7402 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7403 bool HasInteresting = false;
7406 /// Set the ExtParameterInfo for the parameter at the given index,
7408 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7409 assert(Infos.size() <= index);
7410 Infos.resize(index);
7411 Infos.push_back(info);
7413 if (!HasInteresting)
7414 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7417 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7418 /// ExtParameterInfo array we've built up.
7419 const FunctionProtoType::ExtParameterInfo *
7420 getPointerOrNull(unsigned numParams) {
7421 if (!HasInteresting) return nullptr;
7422 Infos.resize(numParams);
7423 return Infos.data();
7427 void PerformPendingInstantiations(bool LocalOnly = false);
7429 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7430 const MultiLevelTemplateArgumentList &TemplateArgs,
7431 SourceLocation Loc, DeclarationName Entity,
7432 bool AllowDeducedTST = false);
7434 QualType SubstType(QualType T,
7435 const MultiLevelTemplateArgumentList &TemplateArgs,
7436 SourceLocation Loc, DeclarationName Entity);
7438 TypeSourceInfo *SubstType(TypeLoc TL,
7439 const MultiLevelTemplateArgumentList &TemplateArgs,
7440 SourceLocation Loc, DeclarationName Entity);
7442 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7443 const MultiLevelTemplateArgumentList &TemplateArgs,
7445 DeclarationName Entity,
7446 CXXRecordDecl *ThisContext,
7447 unsigned ThisTypeQuals);
7448 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7449 const MultiLevelTemplateArgumentList &Args);
7450 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7451 const MultiLevelTemplateArgumentList &TemplateArgs,
7452 int indexAdjustment,
7453 Optional<unsigned> NumExpansions,
7454 bool ExpectParameterPack);
7455 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7456 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7457 const MultiLevelTemplateArgumentList &TemplateArgs,
7458 SmallVectorImpl<QualType> &ParamTypes,
7459 SmallVectorImpl<ParmVarDecl *> *OutParams,
7460 ExtParameterInfoBuilder &ParamInfos);
7461 ExprResult SubstExpr(Expr *E,
7462 const MultiLevelTemplateArgumentList &TemplateArgs);
7464 /// \brief Substitute the given template arguments into a list of
7465 /// expressions, expanding pack expansions if required.
7467 /// \param Exprs The list of expressions to substitute into.
7469 /// \param IsCall Whether this is some form of call, in which case
7470 /// default arguments will be dropped.
7472 /// \param TemplateArgs The set of template arguments to substitute.
7474 /// \param Outputs Will receive all of the substituted arguments.
7476 /// \returns true if an error occurred, false otherwise.
7477 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7478 const MultiLevelTemplateArgumentList &TemplateArgs,
7479 SmallVectorImpl<Expr *> &Outputs);
7481 StmtResult SubstStmt(Stmt *S,
7482 const MultiLevelTemplateArgumentList &TemplateArgs);
7484 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7485 const MultiLevelTemplateArgumentList &TemplateArgs);
7487 ExprResult SubstInitializer(Expr *E,
7488 const MultiLevelTemplateArgumentList &TemplateArgs,
7489 bool CXXDirectInit);
7492 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7493 CXXRecordDecl *Pattern,
7494 const MultiLevelTemplateArgumentList &TemplateArgs);
7497 InstantiateClass(SourceLocation PointOfInstantiation,
7498 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7499 const MultiLevelTemplateArgumentList &TemplateArgs,
7500 TemplateSpecializationKind TSK,
7501 bool Complain = true);
7503 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7504 EnumDecl *Instantiation, EnumDecl *Pattern,
7505 const MultiLevelTemplateArgumentList &TemplateArgs,
7506 TemplateSpecializationKind TSK);
7508 bool InstantiateInClassInitializer(
7509 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7510 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7512 struct LateInstantiatedAttribute {
7513 const Attr *TmplAttr;
7514 LocalInstantiationScope *Scope;
7517 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7519 : TmplAttr(A), Scope(S), NewDecl(D)
7522 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7524 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7525 const Decl *Pattern, Decl *Inst,
7526 LateInstantiatedAttrVec *LateAttrs = nullptr,
7527 LocalInstantiationScope *OuterMostScope = nullptr);
7530 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7531 const Decl *Pattern, Decl *Inst,
7532 LateInstantiatedAttrVec *LateAttrs = nullptr,
7533 LocalInstantiationScope *OuterMostScope = nullptr);
7536 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7537 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7538 TemplateSpecializationKind TSK,
7539 bool Complain = true);
7541 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7542 CXXRecordDecl *Instantiation,
7543 const MultiLevelTemplateArgumentList &TemplateArgs,
7544 TemplateSpecializationKind TSK);
7546 void InstantiateClassTemplateSpecializationMembers(
7547 SourceLocation PointOfInstantiation,
7548 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7549 TemplateSpecializationKind TSK);
7551 NestedNameSpecifierLoc
7552 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7553 const MultiLevelTemplateArgumentList &TemplateArgs);
7556 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7557 const MultiLevelTemplateArgumentList &TemplateArgs);
7559 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7561 const MultiLevelTemplateArgumentList &TemplateArgs);
7562 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7563 TemplateArgumentListInfo &Result,
7564 const MultiLevelTemplateArgumentList &TemplateArgs);
7566 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7567 FunctionDecl *Function);
7568 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7569 FunctionDecl *Function,
7570 bool Recursive = false,
7571 bool DefinitionRequired = false,
7572 bool AtEndOfTU = false);
7573 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7574 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7575 const TemplateArgumentList &TemplateArgList,
7576 const TemplateArgumentListInfo &TemplateArgsInfo,
7577 SmallVectorImpl<TemplateArgument> &Converted,
7578 SourceLocation PointOfInstantiation, void *InsertPos,
7579 LateInstantiatedAttrVec *LateAttrs = nullptr,
7580 LocalInstantiationScope *StartingScope = nullptr);
7581 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7582 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7583 const MultiLevelTemplateArgumentList &TemplateArgs);
7585 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7586 const MultiLevelTemplateArgumentList &TemplateArgs,
7587 LateInstantiatedAttrVec *LateAttrs,
7589 LocalInstantiationScope *StartingScope,
7590 bool InstantiatingVarTemplate = false);
7591 void InstantiateVariableInitializer(
7592 VarDecl *Var, VarDecl *OldVar,
7593 const MultiLevelTemplateArgumentList &TemplateArgs);
7594 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7595 VarDecl *Var, bool Recursive = false,
7596 bool DefinitionRequired = false,
7597 bool AtEndOfTU = false);
7598 void InstantiateStaticDataMemberDefinition(
7599 SourceLocation PointOfInstantiation,
7601 bool Recursive = false,
7602 bool DefinitionRequired = false);
7604 void InstantiateMemInitializers(CXXConstructorDecl *New,
7605 const CXXConstructorDecl *Tmpl,
7606 const MultiLevelTemplateArgumentList &TemplateArgs);
7608 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7609 const MultiLevelTemplateArgumentList &TemplateArgs);
7610 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7611 const MultiLevelTemplateArgumentList &TemplateArgs);
7613 // Objective-C declarations.
7614 enum ObjCContainerKind {
7621 OCK_CategoryImplementation
7623 ObjCContainerKind getObjCContainerKind() const;
7625 DeclResult actOnObjCTypeParam(Scope *S,
7626 ObjCTypeParamVariance variance,
7627 SourceLocation varianceLoc,
7629 IdentifierInfo *paramName,
7630 SourceLocation paramLoc,
7631 SourceLocation colonLoc,
7632 ParsedType typeBound);
7634 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7635 ArrayRef<Decl *> typeParams,
7636 SourceLocation rAngleLoc);
7637 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7639 Decl *ActOnStartClassInterface(Scope *S,
7640 SourceLocation AtInterfaceLoc,
7641 IdentifierInfo *ClassName,
7642 SourceLocation ClassLoc,
7643 ObjCTypeParamList *typeParamList,
7644 IdentifierInfo *SuperName,
7645 SourceLocation SuperLoc,
7646 ArrayRef<ParsedType> SuperTypeArgs,
7647 SourceRange SuperTypeArgsRange,
7648 Decl * const *ProtoRefs,
7649 unsigned NumProtoRefs,
7650 const SourceLocation *ProtoLocs,
7651 SourceLocation EndProtoLoc,
7652 AttributeList *AttrList);
7654 void ActOnSuperClassOfClassInterface(Scope *S,
7655 SourceLocation AtInterfaceLoc,
7656 ObjCInterfaceDecl *IDecl,
7657 IdentifierInfo *ClassName,
7658 SourceLocation ClassLoc,
7659 IdentifierInfo *SuperName,
7660 SourceLocation SuperLoc,
7661 ArrayRef<ParsedType> SuperTypeArgs,
7662 SourceRange SuperTypeArgsRange);
7664 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7665 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7666 IdentifierInfo *SuperName,
7667 SourceLocation SuperLoc);
7669 Decl *ActOnCompatibilityAlias(
7670 SourceLocation AtCompatibilityAliasLoc,
7671 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7672 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7674 bool CheckForwardProtocolDeclarationForCircularDependency(
7675 IdentifierInfo *PName,
7676 SourceLocation &PLoc, SourceLocation PrevLoc,
7677 const ObjCList<ObjCProtocolDecl> &PList);
7679 Decl *ActOnStartProtocolInterface(
7680 SourceLocation AtProtoInterfaceLoc,
7681 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7682 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7683 const SourceLocation *ProtoLocs,
7684 SourceLocation EndProtoLoc,
7685 AttributeList *AttrList);
7687 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7688 IdentifierInfo *ClassName,
7689 SourceLocation ClassLoc,
7690 ObjCTypeParamList *typeParamList,
7691 IdentifierInfo *CategoryName,
7692 SourceLocation CategoryLoc,
7693 Decl * const *ProtoRefs,
7694 unsigned NumProtoRefs,
7695 const SourceLocation *ProtoLocs,
7696 SourceLocation EndProtoLoc,
7697 AttributeList *AttrList);
7699 Decl *ActOnStartClassImplementation(
7700 SourceLocation AtClassImplLoc,
7701 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7702 IdentifierInfo *SuperClassname,
7703 SourceLocation SuperClassLoc);
7705 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7706 IdentifierInfo *ClassName,
7707 SourceLocation ClassLoc,
7708 IdentifierInfo *CatName,
7709 SourceLocation CatLoc);
7711 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7712 ArrayRef<Decl *> Decls);
7714 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7715 IdentifierInfo **IdentList,
7716 SourceLocation *IdentLocs,
7717 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7720 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7721 ArrayRef<IdentifierLocPair> IdentList,
7722 AttributeList *attrList);
7724 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7725 ArrayRef<IdentifierLocPair> ProtocolId,
7726 SmallVectorImpl<Decl *> &Protocols);
7728 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7729 SourceLocation ProtocolLoc,
7730 IdentifierInfo *TypeArgId,
7731 SourceLocation TypeArgLoc,
7732 bool SelectProtocolFirst = false);
7734 /// Given a list of identifiers (and their locations), resolve the
7735 /// names to either Objective-C protocol qualifiers or type
7736 /// arguments, as appropriate.
7737 void actOnObjCTypeArgsOrProtocolQualifiers(
7739 ParsedType baseType,
7740 SourceLocation lAngleLoc,
7741 ArrayRef<IdentifierInfo *> identifiers,
7742 ArrayRef<SourceLocation> identifierLocs,
7743 SourceLocation rAngleLoc,
7744 SourceLocation &typeArgsLAngleLoc,
7745 SmallVectorImpl<ParsedType> &typeArgs,
7746 SourceLocation &typeArgsRAngleLoc,
7747 SourceLocation &protocolLAngleLoc,
7748 SmallVectorImpl<Decl *> &protocols,
7749 SourceLocation &protocolRAngleLoc,
7750 bool warnOnIncompleteProtocols);
7752 /// Build a an Objective-C protocol-qualified 'id' type where no
7753 /// base type was specified.
7754 TypeResult actOnObjCProtocolQualifierType(
7755 SourceLocation lAngleLoc,
7756 ArrayRef<Decl *> protocols,
7757 ArrayRef<SourceLocation> protocolLocs,
7758 SourceLocation rAngleLoc);
7760 /// Build a specialized and/or protocol-qualified Objective-C type.
7761 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7764 ParsedType BaseType,
7765 SourceLocation TypeArgsLAngleLoc,
7766 ArrayRef<ParsedType> TypeArgs,
7767 SourceLocation TypeArgsRAngleLoc,
7768 SourceLocation ProtocolLAngleLoc,
7769 ArrayRef<Decl *> Protocols,
7770 ArrayRef<SourceLocation> ProtocolLocs,
7771 SourceLocation ProtocolRAngleLoc);
7773 /// Build an Objective-C type parameter type.
7774 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7775 SourceLocation ProtocolLAngleLoc,
7776 ArrayRef<ObjCProtocolDecl *> Protocols,
7777 ArrayRef<SourceLocation> ProtocolLocs,
7778 SourceLocation ProtocolRAngleLoc,
7779 bool FailOnError = false);
7781 /// Build an Objective-C object pointer type.
7782 QualType BuildObjCObjectType(QualType BaseType,
7784 SourceLocation TypeArgsLAngleLoc,
7785 ArrayRef<TypeSourceInfo *> TypeArgs,
7786 SourceLocation TypeArgsRAngleLoc,
7787 SourceLocation ProtocolLAngleLoc,
7788 ArrayRef<ObjCProtocolDecl *> Protocols,
7789 ArrayRef<SourceLocation> ProtocolLocs,
7790 SourceLocation ProtocolRAngleLoc,
7791 bool FailOnError = false);
7793 /// Check the application of the Objective-C '__kindof' qualifier to
7795 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7797 /// Ensure attributes are consistent with type.
7798 /// \param [in, out] Attributes The attributes to check; they will
7799 /// be modified to be consistent with \p PropertyTy.
7800 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7802 unsigned &Attributes,
7803 bool propertyInPrimaryClass);
7805 /// Process the specified property declaration and create decls for the
7806 /// setters and getters as needed.
7807 /// \param property The property declaration being processed
7808 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7811 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7812 ObjCPropertyDecl *SuperProperty,
7813 const IdentifierInfo *Name,
7814 bool OverridingProtocolProperty);
7816 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7817 ObjCInterfaceDecl *ID);
7819 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7820 ArrayRef<Decl *> allMethods = None,
7821 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7823 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7824 SourceLocation LParenLoc,
7825 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7826 Selector GetterSel, Selector SetterSel,
7827 tok::ObjCKeywordKind MethodImplKind,
7828 DeclContext *lexicalDC = nullptr);
7830 Decl *ActOnPropertyImplDecl(Scope *S,
7831 SourceLocation AtLoc,
7832 SourceLocation PropertyLoc,
7834 IdentifierInfo *PropertyId,
7835 IdentifierInfo *PropertyIvar,
7836 SourceLocation PropertyIvarLoc,
7837 ObjCPropertyQueryKind QueryKind);
7839 enum ObjCSpecialMethodKind {
7845 OSMK_NonRetainingInit
7848 struct ObjCArgInfo {
7849 IdentifierInfo *Name;
7850 SourceLocation NameLoc;
7851 // The Type is null if no type was specified, and the DeclSpec is invalid
7854 ObjCDeclSpec DeclSpec;
7856 /// ArgAttrs - Attribute list for this argument.
7857 AttributeList *ArgAttrs;
7860 Decl *ActOnMethodDeclaration(
7862 SourceLocation BeginLoc, // location of the + or -.
7863 SourceLocation EndLoc, // location of the ; or {.
7864 tok::TokenKind MethodType,
7865 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7866 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7867 // optional arguments. The number of types/arguments is obtained
7868 // from the Sel.getNumArgs().
7869 ObjCArgInfo *ArgInfo,
7870 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7871 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7872 bool isVariadic, bool MethodDefinition);
7874 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7875 const ObjCObjectPointerType *OPT,
7877 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7880 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7881 bool inferObjCARCLifetime(ValueDecl *decl);
7884 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7886 SourceLocation OpLoc,
7887 DeclarationName MemberName,
7888 SourceLocation MemberLoc,
7889 SourceLocation SuperLoc, QualType SuperType,
7893 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7894 IdentifierInfo &propertyName,
7895 SourceLocation receiverNameLoc,
7896 SourceLocation propertyNameLoc);
7898 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7900 /// \brief Describes the kind of message expression indicated by a message
7901 /// send that starts with an identifier.
7902 enum ObjCMessageKind {
7903 /// \brief The message is sent to 'super'.
7905 /// \brief The message is an instance message.
7906 ObjCInstanceMessage,
7907 /// \brief The message is a class message, and the identifier is a type
7912 ObjCMessageKind getObjCMessageKind(Scope *S,
7913 IdentifierInfo *Name,
7914 SourceLocation NameLoc,
7916 bool HasTrailingDot,
7917 ParsedType &ReceiverType);
7919 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7921 SourceLocation LBracLoc,
7922 ArrayRef<SourceLocation> SelectorLocs,
7923 SourceLocation RBracLoc,
7926 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7927 QualType ReceiverType,
7928 SourceLocation SuperLoc,
7930 ObjCMethodDecl *Method,
7931 SourceLocation LBracLoc,
7932 ArrayRef<SourceLocation> SelectorLocs,
7933 SourceLocation RBracLoc,
7935 bool isImplicit = false);
7937 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7938 bool isSuperReceiver,
7941 ObjCMethodDecl *Method,
7944 ExprResult ActOnClassMessage(Scope *S,
7945 ParsedType Receiver,
7947 SourceLocation LBracLoc,
7948 ArrayRef<SourceLocation> SelectorLocs,
7949 SourceLocation RBracLoc,
7952 ExprResult BuildInstanceMessage(Expr *Receiver,
7953 QualType ReceiverType,
7954 SourceLocation SuperLoc,
7956 ObjCMethodDecl *Method,
7957 SourceLocation LBracLoc,
7958 ArrayRef<SourceLocation> SelectorLocs,
7959 SourceLocation RBracLoc,
7961 bool isImplicit = false);
7963 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7964 QualType ReceiverType,
7967 ObjCMethodDecl *Method,
7970 ExprResult ActOnInstanceMessage(Scope *S,
7973 SourceLocation LBracLoc,
7974 ArrayRef<SourceLocation> SelectorLocs,
7975 SourceLocation RBracLoc,
7978 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7979 ObjCBridgeCastKind Kind,
7980 SourceLocation BridgeKeywordLoc,
7981 TypeSourceInfo *TSInfo,
7984 ExprResult ActOnObjCBridgedCast(Scope *S,
7985 SourceLocation LParenLoc,
7986 ObjCBridgeCastKind Kind,
7987 SourceLocation BridgeKeywordLoc,
7989 SourceLocation RParenLoc,
7992 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7994 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7996 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7999 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8000 QualType DestType, QualType SrcType,
8001 ObjCInterfaceDecl *&RelatedClass,
8002 ObjCMethodDecl *&ClassMethod,
8003 ObjCMethodDecl *&InstanceMethod,
8004 TypedefNameDecl *&TDNDecl,
8005 bool CfToNs, bool Diagnose = true);
8007 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8008 QualType DestType, QualType SrcType,
8009 Expr *&SrcExpr, bool Diagnose = true);
8011 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8012 bool Diagnose = true);
8014 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8016 /// \brief Check whether the given new method is a valid override of the
8017 /// given overridden method, and set any properties that should be inherited.
8018 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8019 const ObjCMethodDecl *Overridden);
8021 /// \brief Describes the compatibility of a result type with its method.
8022 enum ResultTypeCompatibilityKind {
8028 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8029 ObjCInterfaceDecl *CurrentClass,
8030 ResultTypeCompatibilityKind RTC);
8032 enum PragmaOptionsAlignKind {
8033 POAK_Native, // #pragma options align=native
8034 POAK_Natural, // #pragma options align=natural
8035 POAK_Packed, // #pragma options align=packed
8036 POAK_Power, // #pragma options align=power
8037 POAK_Mac68k, // #pragma options align=mac68k
8038 POAK_Reset // #pragma options align=reset
8041 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8042 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8043 SourceLocation PragmaLoc);
8045 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8046 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8047 StringRef SlotLabel, Expr *Alignment);
8049 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8050 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8052 /// ActOnPragmaMSComment - Called on well formed
8053 /// \#pragma comment(kind, "arg").
8054 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8057 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8058 /// pointers_to_members(representation method[, general purpose
8059 /// representation]).
8060 void ActOnPragmaMSPointersToMembers(
8061 LangOptions::PragmaMSPointersToMembersKind Kind,
8062 SourceLocation PragmaLoc);
8064 /// \brief Called on well formed \#pragma vtordisp().
8065 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8066 SourceLocation PragmaLoc,
8067 MSVtorDispAttr::Mode Value);
8069 enum PragmaSectionKind {
8076 bool UnifySection(StringRef SectionName,
8078 DeclaratorDecl *TheDecl);
8079 bool UnifySection(StringRef SectionName,
8081 SourceLocation PragmaSectionLocation);
8083 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8084 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8085 PragmaMsStackAction Action,
8086 llvm::StringRef StackSlotLabel,
8087 StringLiteral *SegmentName,
8088 llvm::StringRef PragmaName);
8090 /// \brief Called on well formed \#pragma section().
8091 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8092 int SectionFlags, StringLiteral *SegmentName);
8094 /// \brief Called on well-formed \#pragma init_seg().
8095 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8096 StringLiteral *SegmentName);
8098 /// \brief Called on #pragma clang __debug dump II
8099 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8101 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8102 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8105 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8106 void ActOnPragmaUnused(const Token &Identifier,
8108 SourceLocation PragmaLoc);
8110 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8111 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8112 SourceLocation PragmaLoc);
8114 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8115 SourceLocation Loc);
8116 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8118 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8119 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8120 SourceLocation PragmaLoc,
8121 SourceLocation WeakNameLoc);
8123 /// ActOnPragmaRedefineExtname - Called on well formed
8124 /// \#pragma redefine_extname oldname newname.
8125 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8126 IdentifierInfo* AliasName,
8127 SourceLocation PragmaLoc,
8128 SourceLocation WeakNameLoc,
8129 SourceLocation AliasNameLoc);
8131 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8132 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8133 IdentifierInfo* AliasName,
8134 SourceLocation PragmaLoc,
8135 SourceLocation WeakNameLoc,
8136 SourceLocation AliasNameLoc);
8138 /// ActOnPragmaFPContract - Called on well formed
8139 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8140 /// \#pragma clang fp contract
8141 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8143 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8144 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8145 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8147 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8148 void AddMsStructLayoutForRecord(RecordDecl *RD);
8150 /// FreePackedContext - Deallocate and null out PackContext.
8151 void FreePackedContext();
8153 /// PushNamespaceVisibilityAttr - Note that we've entered a
8154 /// namespace with a visibility attribute.
8155 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8156 SourceLocation Loc);
8158 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8159 /// add an appropriate visibility attribute.
8160 void AddPushedVisibilityAttribute(Decl *RD);
8162 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8163 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8164 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8166 /// FreeVisContext - Deallocate and null out VisContext.
8167 void FreeVisContext();
8169 /// AddCFAuditedAttribute - Check whether we're currently within
8170 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8171 /// the appropriate attribute.
8172 void AddCFAuditedAttribute(Decl *D);
8174 /// \brief Called on well-formed '\#pragma clang attribute push'.
8175 void ActOnPragmaAttributePush(AttributeList &Attribute,
8176 SourceLocation PragmaLoc,
8177 attr::ParsedSubjectMatchRuleSet Rules);
8179 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8180 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8182 /// \brief Adds the attributes that have been specified using the
8183 /// '\#pragma clang attribute push' directives to the given declaration.
8184 void AddPragmaAttributes(Scope *S, Decl *D);
8186 void DiagnoseUnterminatedPragmaAttribute();
8188 /// \brief Called on well formed \#pragma clang optimize.
8189 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8191 /// \brief Get the location for the currently active "\#pragma clang optimize
8192 /// off". If this location is invalid, then the state of the pragma is "on".
8193 SourceLocation getOptimizeOffPragmaLocation() const {
8194 return OptimizeOffPragmaLocation;
8197 /// \brief Only called on function definitions; if there is a pragma in scope
8198 /// with the effect of a range-based optnone, consider marking the function
8199 /// with attribute optnone.
8200 void AddRangeBasedOptnone(FunctionDecl *FD);
8202 /// \brief Adds the 'optnone' attribute to the function declaration if there
8203 /// are no conflicts; Loc represents the location causing the 'optnone'
8204 /// attribute to be added (usually because of a pragma).
8205 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8207 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8208 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8209 unsigned SpellingListIndex, bool IsPackExpansion);
8210 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8211 unsigned SpellingListIndex, bool IsPackExpansion);
8213 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8215 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8216 unsigned SpellingListIndex);
8218 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8220 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8221 unsigned SpellingListIndex);
8223 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8225 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8226 unsigned SpellingListIndex);
8228 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8230 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8231 Expr *MinBlocks, unsigned SpellingListIndex);
8233 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8234 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8235 unsigned SpellingListIndex, bool InInstantiation = false);
8237 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8238 ParameterABI ABI, unsigned SpellingListIndex);
8240 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8241 unsigned SpellingListIndex, bool isNSConsumed,
8242 bool isTemplateInstantiation);
8244 //===--------------------------------------------------------------------===//
8245 // C++ Coroutines TS
8247 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8248 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8249 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8251 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8252 bool IsImplicit = false);
8253 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8254 UnresolvedLookupExpr* Lookup);
8255 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8256 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8257 bool IsImplicit = false);
8258 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8259 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8260 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8262 //===--------------------------------------------------------------------===//
8263 // OpenCL extensions.
8266 std::string CurrOpenCLExtension;
8267 /// Extensions required by an OpenCL type.
8268 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8269 /// Extensions required by an OpenCL declaration.
8270 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8272 llvm::StringRef getCurrentOpenCLExtension() const {
8273 return CurrOpenCLExtension;
8275 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8276 CurrOpenCLExtension = Ext;
8279 /// \brief Set OpenCL extensions for a type which can only be used when these
8280 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8281 /// \param Exts A space separated list of OpenCL extensions.
8282 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8284 /// \brief Set OpenCL extensions for a declaration which can only be
8285 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8287 /// \param Exts A space separated list of OpenCL extensions.
8288 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8290 /// \brief Set current OpenCL extensions for a type which can only be used
8291 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8292 /// empty, do nothing.
8293 void setCurrentOpenCLExtensionForType(QualType T);
8295 /// \brief Set current OpenCL extensions for a declaration which
8296 /// can only be used when these OpenCL extensions are enabled. If current
8297 /// OpenCL extension is empty, do nothing.
8298 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8300 bool isOpenCLDisabledDecl(Decl *FD);
8302 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8303 /// is disabled due to required OpenCL extensions being disabled. If so,
8304 /// emit diagnostics.
8305 /// \return true if type is disabled.
8306 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8308 /// \brief Check if declaration \p D used by expression \p E
8309 /// is disabled due to required OpenCL extensions being disabled. If so,
8310 /// emit diagnostics.
8311 /// \return true if type is disabled.
8312 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8314 //===--------------------------------------------------------------------===//
8315 // OpenMP directives and clauses.
8318 void *VarDataSharingAttributesStack;
8319 /// Set to true inside '#pragma omp declare target' region.
8320 bool IsInOpenMPDeclareTargetContext = false;
8321 /// \brief Initialization of data-sharing attributes stack.
8322 void InitDataSharingAttributesStack();
8323 void DestroyDataSharingAttributesStack();
8325 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8326 bool StrictlyPositive = true);
8327 /// Returns OpenMP nesting level for current directive.
8328 unsigned getOpenMPNestingLevel() const;
8330 /// Push new OpenMP function region for non-capturing function.
8331 void pushOpenMPFunctionRegion();
8333 /// Pop OpenMP function region for non-capturing function.
8334 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8336 /// Checks if a type or a declaration is disabled due to the owning extension
8337 /// being disabled, and emits diagnostic messages if it is disabled.
8338 /// \param D type or declaration to be checked.
8339 /// \param DiagLoc source location for the diagnostic message.
8340 /// \param DiagInfo information to be emitted for the diagnostic message.
8341 /// \param SrcRange source range of the declaration.
8342 /// \param Map maps type or declaration to the extensions.
8343 /// \param Selector selects diagnostic message: 0 for type and 1 for
8345 /// \return true if the type or declaration is disabled.
8346 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8347 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8348 MapT &Map, unsigned Selector = 0,
8349 SourceRange SrcRange = SourceRange());
8352 /// \brief Return true if the provided declaration \a VD should be captured by
8354 /// \param Level Relative level of nested OpenMP construct for that the check
8356 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8358 /// \brief Check if the specified variable is used in one of the private
8359 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8361 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8362 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8363 ExprObjectKind OK, SourceLocation Loc);
8365 /// \brief Check if the specified variable is used in 'private' clause.
8366 /// \param Level Relative level of nested OpenMP construct for that the check
8368 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8370 /// \brief Check if the specified variable is captured by 'target' directive.
8371 /// \param Level Relative level of nested OpenMP construct for that the check
8373 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8375 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8377 /// \brief Called on start of new data sharing attribute block.
8378 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8379 const DeclarationNameInfo &DirName, Scope *CurScope,
8380 SourceLocation Loc);
8381 /// \brief Start analysis of clauses.
8382 void StartOpenMPClause(OpenMPClauseKind K);
8383 /// \brief End analysis of clauses.
8384 void EndOpenMPClause();
8385 /// \brief Called on end of data sharing attribute block.
8386 void EndOpenMPDSABlock(Stmt *CurDirective);
8388 /// \brief Check if the current region is an OpenMP loop region and if it is,
8389 /// mark loop control variable, used in \p Init for loop initialization, as
8390 /// private by default.
8391 /// \param Init First part of the for loop.
8392 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8394 // OpenMP directives and clauses.
8395 /// \brief Called on correct id-expression from the '#pragma omp
8397 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8398 CXXScopeSpec &ScopeSpec,
8399 const DeclarationNameInfo &Id);
8400 /// \brief Called on well-formed '#pragma omp threadprivate'.
8401 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8403 ArrayRef<Expr *> VarList);
8404 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8405 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8407 ArrayRef<Expr *> VarList);
8408 /// \brief Check if the specified type is allowed to be used in 'omp declare
8409 /// reduction' construct.
8410 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8411 TypeResult ParsedType);
8412 /// \brief Called on start of '#pragma omp declare reduction'.
8413 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8414 Scope *S, DeclContext *DC, DeclarationName Name,
8415 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8416 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8417 /// \brief Initialize declare reduction construct initializer.
8418 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8419 /// \brief Finish current declare reduction construct initializer.
8420 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8421 /// \brief Initialize declare reduction construct initializer.
8422 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8423 /// \brief Finish current declare reduction construct initializer.
8424 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8425 /// \brief Called at the end of '#pragma omp declare reduction'.
8426 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8427 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8429 /// Called on the start of target region i.e. '#pragma omp declare target'.
8430 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8431 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8432 void ActOnFinishOpenMPDeclareTargetDirective();
8433 /// Called on correct id-expression from the '#pragma omp declare target'.
8434 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8435 const DeclarationNameInfo &Id,
8436 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8437 NamedDeclSetType &SameDirectiveDecls);
8438 /// Check declaration inside target region.
8439 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8440 /// Return true inside OpenMP target region.
8441 bool isInOpenMPDeclareTargetContext() const {
8442 return IsInOpenMPDeclareTargetContext;
8445 /// Return the number of captured regions created for an OpenMP directive.
8446 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8448 /// \brief Initialization of captured region for OpenMP region.
8449 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8450 /// \brief End of OpenMP region.
8452 /// \param S Statement associated with the current OpenMP region.
8453 /// \param Clauses List of clauses for the current OpenMP region.
8455 /// \returns Statement for finished OpenMP region.
8456 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8457 StmtResult ActOnOpenMPExecutableDirective(
8458 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8459 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8460 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8461 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8462 /// of the associated statement.
8463 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8465 SourceLocation StartLoc,
8466 SourceLocation EndLoc);
8467 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8468 /// of the associated statement.
8469 StmtResult ActOnOpenMPSimdDirective(
8470 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8471 SourceLocation EndLoc,
8472 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8473 /// \brief Called on well-formed '\#pragma omp for' after parsing
8474 /// of the associated statement.
8475 StmtResult ActOnOpenMPForDirective(
8476 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8477 SourceLocation EndLoc,
8478 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8479 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8480 /// of the associated statement.
8481 StmtResult ActOnOpenMPForSimdDirective(
8482 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8483 SourceLocation EndLoc,
8484 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8485 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8486 /// of the associated statement.
8487 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8488 Stmt *AStmt, SourceLocation StartLoc,
8489 SourceLocation EndLoc);
8490 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8491 /// associated statement.
8492 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8493 SourceLocation EndLoc);
8494 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8495 /// associated statement.
8496 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8497 Stmt *AStmt, SourceLocation StartLoc,
8498 SourceLocation EndLoc);
8499 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8500 /// associated statement.
8501 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8502 SourceLocation EndLoc);
8503 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8504 /// associated statement.
8505 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8506 ArrayRef<OMPClause *> Clauses,
8507 Stmt *AStmt, SourceLocation StartLoc,
8508 SourceLocation EndLoc);
8509 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8510 /// of the associated statement.
8511 StmtResult ActOnOpenMPParallelForDirective(
8512 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8513 SourceLocation EndLoc,
8514 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8515 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8516 /// parsing of the associated statement.
8517 StmtResult ActOnOpenMPParallelForSimdDirective(
8518 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8519 SourceLocation EndLoc,
8520 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8521 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8522 /// parsing of the associated statement.
8523 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8525 SourceLocation StartLoc,
8526 SourceLocation EndLoc);
8527 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8528 /// associated statement.
8529 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8530 Stmt *AStmt, SourceLocation StartLoc,
8531 SourceLocation EndLoc);
8532 /// \brief Called on well-formed '\#pragma omp taskyield'.
8533 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8534 SourceLocation EndLoc);
8535 /// \brief Called on well-formed '\#pragma omp barrier'.
8536 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8537 SourceLocation EndLoc);
8538 /// \brief Called on well-formed '\#pragma omp taskwait'.
8539 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8540 SourceLocation EndLoc);
8541 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8542 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8543 SourceLocation EndLoc);
8544 /// \brief Called on well-formed '\#pragma omp flush'.
8545 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8546 SourceLocation StartLoc,
8547 SourceLocation EndLoc);
8548 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8549 /// associated statement.
8550 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8551 Stmt *AStmt, SourceLocation StartLoc,
8552 SourceLocation EndLoc);
8553 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8554 /// associated statement.
8555 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8556 Stmt *AStmt, SourceLocation StartLoc,
8557 SourceLocation EndLoc);
8558 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8559 /// associated statement.
8560 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8561 Stmt *AStmt, SourceLocation StartLoc,
8562 SourceLocation EndLoc);
8563 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8564 /// the associated statement.
8565 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8566 Stmt *AStmt, SourceLocation StartLoc,
8567 SourceLocation EndLoc);
8568 /// \brief Called on well-formed '\#pragma omp target enter data' after
8569 /// parsing of the associated statement.
8570 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8571 SourceLocation StartLoc,
8572 SourceLocation EndLoc);
8573 /// \brief Called on well-formed '\#pragma omp target exit data' after
8574 /// parsing of the associated statement.
8575 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8576 SourceLocation StartLoc,
8577 SourceLocation EndLoc);
8578 /// \brief Called on well-formed '\#pragma omp target parallel' after
8579 /// parsing of the associated statement.
8580 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8582 SourceLocation StartLoc,
8583 SourceLocation EndLoc);
8584 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8585 /// parsing of the associated statement.
8586 StmtResult ActOnOpenMPTargetParallelForDirective(
8587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8588 SourceLocation EndLoc,
8589 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8590 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8591 /// associated statement.
8592 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8593 Stmt *AStmt, SourceLocation StartLoc,
8594 SourceLocation EndLoc);
8595 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8597 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8598 SourceLocation EndLoc,
8599 OpenMPDirectiveKind CancelRegion);
8600 /// \brief Called on well-formed '\#pragma omp cancel'.
8601 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8602 SourceLocation StartLoc,
8603 SourceLocation EndLoc,
8604 OpenMPDirectiveKind CancelRegion);
8605 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8606 /// associated statement.
8607 StmtResult ActOnOpenMPTaskLoopDirective(
8608 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8609 SourceLocation EndLoc,
8610 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8611 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8612 /// the associated statement.
8613 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8614 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8615 SourceLocation EndLoc,
8616 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8617 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8618 /// of the associated statement.
8619 StmtResult ActOnOpenMPDistributeDirective(
8620 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8621 SourceLocation EndLoc,
8622 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8623 /// \brief Called on well-formed '\#pragma omp target update'.
8624 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8625 SourceLocation StartLoc,
8626 SourceLocation EndLoc);
8627 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8628 /// parsing of the associated statement.
8629 StmtResult ActOnOpenMPDistributeParallelForDirective(
8630 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8631 SourceLocation EndLoc,
8632 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8633 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8634 /// after parsing of the associated statement.
8635 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8636 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8637 SourceLocation EndLoc,
8638 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8639 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8640 /// parsing of the associated statement.
8641 StmtResult ActOnOpenMPDistributeSimdDirective(
8642 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8643 SourceLocation EndLoc,
8644 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8645 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8646 /// parsing of the associated statement.
8647 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8648 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8649 SourceLocation EndLoc,
8650 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8651 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8652 /// the associated statement.
8653 StmtResult ActOnOpenMPTargetSimdDirective(
8654 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8655 SourceLocation EndLoc,
8656 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8657 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8658 /// the associated statement.
8659 StmtResult ActOnOpenMPTeamsDistributeDirective(
8660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8661 SourceLocation EndLoc,
8662 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8663 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8664 /// of the associated statement.
8665 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8667 SourceLocation EndLoc,
8668 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8669 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8670 /// after parsing of the associated statement.
8671 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8672 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8673 SourceLocation EndLoc,
8674 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8675 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8676 /// after parsing of the associated statement.
8677 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8679 SourceLocation EndLoc,
8680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8681 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8682 /// associated statement.
8683 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8685 SourceLocation StartLoc,
8686 SourceLocation EndLoc);
8687 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8688 /// of the associated statement.
8689 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8690 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8691 SourceLocation EndLoc,
8692 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8693 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8694 /// after parsing of the associated statement.
8695 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8697 SourceLocation EndLoc,
8698 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8699 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8700 /// simd' after parsing of the associated statement.
8701 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8702 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8703 SourceLocation EndLoc,
8704 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8705 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8706 /// parsing of the associated statement.
8707 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8708 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8709 SourceLocation EndLoc,
8710 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8712 /// Checks correctness of linear modifiers.
8713 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8714 SourceLocation LinLoc);
8715 /// Checks that the specified declaration matches requirements for the linear
8717 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8718 OpenMPLinearClauseKind LinKind, QualType Type);
8720 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8721 /// the associated method/function.
8722 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8723 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8724 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8725 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8726 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8728 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8730 SourceLocation StartLoc,
8731 SourceLocation LParenLoc,
8732 SourceLocation EndLoc);
8733 /// \brief Called on well-formed 'if' clause.
8734 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8735 Expr *Condition, SourceLocation StartLoc,
8736 SourceLocation LParenLoc,
8737 SourceLocation NameModifierLoc,
8738 SourceLocation ColonLoc,
8739 SourceLocation EndLoc);
8740 /// \brief Called on well-formed 'final' clause.
8741 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8742 SourceLocation LParenLoc,
8743 SourceLocation EndLoc);
8744 /// \brief Called on well-formed 'num_threads' clause.
8745 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8746 SourceLocation StartLoc,
8747 SourceLocation LParenLoc,
8748 SourceLocation EndLoc);
8749 /// \brief Called on well-formed 'safelen' clause.
8750 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8751 SourceLocation StartLoc,
8752 SourceLocation LParenLoc,
8753 SourceLocation EndLoc);
8754 /// \brief Called on well-formed 'simdlen' clause.
8755 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8756 SourceLocation LParenLoc,
8757 SourceLocation EndLoc);
8758 /// \brief Called on well-formed 'collapse' clause.
8759 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8760 SourceLocation StartLoc,
8761 SourceLocation LParenLoc,
8762 SourceLocation EndLoc);
8763 /// \brief Called on well-formed 'ordered' clause.
8765 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8766 SourceLocation LParenLoc = SourceLocation(),
8767 Expr *NumForLoops = nullptr);
8768 /// \brief Called on well-formed 'grainsize' clause.
8769 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8770 SourceLocation LParenLoc,
8771 SourceLocation EndLoc);
8772 /// \brief Called on well-formed 'num_tasks' clause.
8773 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8774 SourceLocation LParenLoc,
8775 SourceLocation EndLoc);
8776 /// \brief Called on well-formed 'hint' clause.
8777 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8778 SourceLocation LParenLoc,
8779 SourceLocation EndLoc);
8781 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8783 SourceLocation ArgumentLoc,
8784 SourceLocation StartLoc,
8785 SourceLocation LParenLoc,
8786 SourceLocation EndLoc);
8787 /// \brief Called on well-formed 'default' clause.
8788 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8789 SourceLocation KindLoc,
8790 SourceLocation StartLoc,
8791 SourceLocation LParenLoc,
8792 SourceLocation EndLoc);
8793 /// \brief Called on well-formed 'proc_bind' clause.
8794 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8795 SourceLocation KindLoc,
8796 SourceLocation StartLoc,
8797 SourceLocation LParenLoc,
8798 SourceLocation EndLoc);
8800 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8801 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8802 SourceLocation StartLoc, SourceLocation LParenLoc,
8803 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8804 SourceLocation EndLoc);
8805 /// \brief Called on well-formed 'schedule' clause.
8806 OMPClause *ActOnOpenMPScheduleClause(
8807 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8808 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8809 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8810 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8812 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8813 SourceLocation EndLoc);
8814 /// \brief Called on well-formed 'nowait' clause.
8815 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8816 SourceLocation EndLoc);
8817 /// \brief Called on well-formed 'untied' clause.
8818 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8819 SourceLocation EndLoc);
8820 /// \brief Called on well-formed 'mergeable' clause.
8821 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8822 SourceLocation EndLoc);
8823 /// \brief Called on well-formed 'read' clause.
8824 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8825 SourceLocation EndLoc);
8826 /// \brief Called on well-formed 'write' clause.
8827 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8828 SourceLocation EndLoc);
8829 /// \brief Called on well-formed 'update' clause.
8830 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8831 SourceLocation EndLoc);
8832 /// \brief Called on well-formed 'capture' clause.
8833 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8834 SourceLocation EndLoc);
8835 /// \brief Called on well-formed 'seq_cst' clause.
8836 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8837 SourceLocation EndLoc);
8838 /// \brief Called on well-formed 'threads' clause.
8839 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8840 SourceLocation EndLoc);
8841 /// \brief Called on well-formed 'simd' clause.
8842 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8843 SourceLocation EndLoc);
8844 /// \brief Called on well-formed 'nogroup' clause.
8845 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8846 SourceLocation EndLoc);
8848 OMPClause *ActOnOpenMPVarListClause(
8849 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8850 SourceLocation StartLoc, SourceLocation LParenLoc,
8851 SourceLocation ColonLoc, SourceLocation EndLoc,
8852 CXXScopeSpec &ReductionIdScopeSpec,
8853 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8854 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8855 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8856 SourceLocation DepLinMapLoc);
8857 /// \brief Called on well-formed 'private' clause.
8858 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8859 SourceLocation StartLoc,
8860 SourceLocation LParenLoc,
8861 SourceLocation EndLoc);
8862 /// \brief Called on well-formed 'firstprivate' clause.
8863 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8864 SourceLocation StartLoc,
8865 SourceLocation LParenLoc,
8866 SourceLocation EndLoc);
8867 /// \brief Called on well-formed 'lastprivate' clause.
8868 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8869 SourceLocation StartLoc,
8870 SourceLocation LParenLoc,
8871 SourceLocation EndLoc);
8872 /// \brief Called on well-formed 'shared' clause.
8873 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8874 SourceLocation StartLoc,
8875 SourceLocation LParenLoc,
8876 SourceLocation EndLoc);
8877 /// \brief Called on well-formed 'reduction' clause.
8878 OMPClause *ActOnOpenMPReductionClause(
8879 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8880 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8881 CXXScopeSpec &ReductionIdScopeSpec,
8882 const DeclarationNameInfo &ReductionId,
8883 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8884 /// \brief Called on well-formed 'linear' clause.
8886 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8887 SourceLocation StartLoc, SourceLocation LParenLoc,
8888 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8889 SourceLocation ColonLoc, SourceLocation EndLoc);
8890 /// \brief Called on well-formed 'aligned' clause.
8891 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8893 SourceLocation StartLoc,
8894 SourceLocation LParenLoc,
8895 SourceLocation ColonLoc,
8896 SourceLocation EndLoc);
8897 /// \brief Called on well-formed 'copyin' clause.
8898 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8899 SourceLocation StartLoc,
8900 SourceLocation LParenLoc,
8901 SourceLocation EndLoc);
8902 /// \brief Called on well-formed 'copyprivate' clause.
8903 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8904 SourceLocation StartLoc,
8905 SourceLocation LParenLoc,
8906 SourceLocation EndLoc);
8907 /// \brief Called on well-formed 'flush' pseudo clause.
8908 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8909 SourceLocation StartLoc,
8910 SourceLocation LParenLoc,
8911 SourceLocation EndLoc);
8912 /// \brief Called on well-formed 'depend' clause.
8914 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8915 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8916 SourceLocation StartLoc, SourceLocation LParenLoc,
8917 SourceLocation EndLoc);
8918 /// \brief Called on well-formed 'device' clause.
8919 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8920 SourceLocation LParenLoc,
8921 SourceLocation EndLoc);
8922 /// \brief Called on well-formed 'map' clause.
8924 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8925 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8926 SourceLocation MapLoc, SourceLocation ColonLoc,
8927 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8928 SourceLocation LParenLoc, SourceLocation EndLoc);
8929 /// \brief Called on well-formed 'num_teams' clause.
8930 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8931 SourceLocation LParenLoc,
8932 SourceLocation EndLoc);
8933 /// \brief Called on well-formed 'thread_limit' clause.
8934 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8935 SourceLocation StartLoc,
8936 SourceLocation LParenLoc,
8937 SourceLocation EndLoc);
8938 /// \brief Called on well-formed 'priority' clause.
8939 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8940 SourceLocation LParenLoc,
8941 SourceLocation EndLoc);
8942 /// \brief Called on well-formed 'dist_schedule' clause.
8943 OMPClause *ActOnOpenMPDistScheduleClause(
8944 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8945 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8946 SourceLocation CommaLoc, SourceLocation EndLoc);
8947 /// \brief Called on well-formed 'defaultmap' clause.
8948 OMPClause *ActOnOpenMPDefaultmapClause(
8949 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8950 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8951 SourceLocation KindLoc, SourceLocation EndLoc);
8952 /// \brief Called on well-formed 'to' clause.
8953 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8954 SourceLocation StartLoc,
8955 SourceLocation LParenLoc,
8956 SourceLocation EndLoc);
8957 /// \brief Called on well-formed 'from' clause.
8958 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8959 SourceLocation StartLoc,
8960 SourceLocation LParenLoc,
8961 SourceLocation EndLoc);
8962 /// Called on well-formed 'use_device_ptr' clause.
8963 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8964 SourceLocation StartLoc,
8965 SourceLocation LParenLoc,
8966 SourceLocation EndLoc);
8967 /// Called on well-formed 'is_device_ptr' clause.
8968 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8969 SourceLocation StartLoc,
8970 SourceLocation LParenLoc,
8971 SourceLocation EndLoc);
8973 /// \brief The kind of conversion being performed.
8974 enum CheckedConversionKind {
8975 /// \brief An implicit conversion.
8976 CCK_ImplicitConversion,
8977 /// \brief A C-style cast.
8979 /// \brief A functional-style cast.
8981 /// \brief A cast other than a C-style cast.
8985 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8986 /// cast. If there is already an implicit cast, merge into the existing one.
8987 /// If isLvalue, the result of the cast is an lvalue.
8988 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8989 ExprValueKind VK = VK_RValue,
8990 const CXXCastPath *BasePath = nullptr,
8991 CheckedConversionKind CCK
8992 = CCK_ImplicitConversion);
8994 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8995 /// to the conversion from scalar type ScalarTy to the Boolean type.
8996 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8998 /// IgnoredValueConversions - Given that an expression's result is
8999 /// syntactically ignored, perform any conversions that are
9001 ExprResult IgnoredValueConversions(Expr *E);
9003 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9004 // functions and arrays to their respective pointers (C99 6.3.2.1).
9005 ExprResult UsualUnaryConversions(Expr *E);
9007 /// CallExprUnaryConversions - a special case of an unary conversion
9008 /// performed on a function designator of a call expression.
9009 ExprResult CallExprUnaryConversions(Expr *E);
9011 // DefaultFunctionArrayConversion - converts functions and arrays
9012 // to their respective pointers (C99 6.3.2.1).
9013 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9015 // DefaultFunctionArrayLvalueConversion - converts functions and
9016 // arrays to their respective pointers and performs the
9017 // lvalue-to-rvalue conversion.
9018 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9019 bool Diagnose = true);
9021 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9022 // the operand. This is DefaultFunctionArrayLvalueConversion,
9023 // except that it assumes the operand isn't of function or array
9025 ExprResult DefaultLvalueConversion(Expr *E);
9027 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9028 // do not have a prototype. Integer promotions are performed on each
9029 // argument, and arguments that have type float are promoted to double.
9030 ExprResult DefaultArgumentPromotion(Expr *E);
9032 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9033 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9034 /// we don't have xvalues there.
9035 ExprResult TemporaryMaterializationConversion(Expr *E);
9037 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9038 enum VariadicCallType {
9042 VariadicConstructor,
9043 VariadicDoesNotApply
9046 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9047 const FunctionProtoType *Proto,
9050 // Used for determining in which context a type is allowed to be passed to a
9060 // Determines which VarArgKind fits an expression.
9061 VarArgKind isValidVarArgType(const QualType &Ty);
9063 /// Check to see if the given expression is a valid argument to a variadic
9064 /// function, issuing a diagnostic if not.
9065 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9067 /// Check to see if a given expression could have '.c_str()' called on it.
9068 bool hasCStrMethod(const Expr *E);
9070 /// GatherArgumentsForCall - Collector argument expressions for various
9071 /// form of call prototypes.
9072 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9073 const FunctionProtoType *Proto,
9074 unsigned FirstParam, ArrayRef<Expr *> Args,
9075 SmallVectorImpl<Expr *> &AllArgs,
9076 VariadicCallType CallType = VariadicDoesNotApply,
9077 bool AllowExplicit = false,
9078 bool IsListInitialization = false);
9080 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9081 // will create a runtime trap if the resulting type is not a POD type.
9082 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9083 FunctionDecl *FDecl);
9085 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9086 // operands and then handles various conversions that are common to binary
9087 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9088 // routine returns the first non-arithmetic type found. The client is
9089 // responsible for emitting appropriate error diagnostics.
9090 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9091 bool IsCompAssign = false);
9093 /// AssignConvertType - All of the 'assignment' semantic checks return this
9094 /// enum to indicate whether the assignment was allowed. These checks are
9095 /// done for simple assignments, as well as initialization, return from
9096 /// function, argument passing, etc. The query is phrased in terms of a
9097 /// source and destination type.
9098 enum AssignConvertType {
9099 /// Compatible - the types are compatible according to the standard.
9102 /// PointerToInt - The assignment converts a pointer to an int, which we
9103 /// accept as an extension.
9106 /// IntToPointer - The assignment converts an int to a pointer, which we
9107 /// accept as an extension.
9110 /// FunctionVoidPointer - The assignment is between a function pointer and
9111 /// void*, which the standard doesn't allow, but we accept as an extension.
9112 FunctionVoidPointer,
9114 /// IncompatiblePointer - The assignment is between two pointers types that
9115 /// are not compatible, but we accept them as an extension.
9116 IncompatiblePointer,
9118 /// IncompatiblePointerSign - The assignment is between two pointers types
9119 /// which point to integers which have a different sign, but are otherwise
9120 /// identical. This is a subset of the above, but broken out because it's by
9121 /// far the most common case of incompatible pointers.
9122 IncompatiblePointerSign,
9124 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9125 /// c/v/r qualifiers, which we accept as an extension.
9126 CompatiblePointerDiscardsQualifiers,
9128 /// IncompatiblePointerDiscardsQualifiers - The assignment
9129 /// discards qualifiers that we don't permit to be discarded,
9130 /// like address spaces.
9131 IncompatiblePointerDiscardsQualifiers,
9133 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9134 /// nested pointer types, and the qualifiers other than the first two
9135 /// levels differ e.g. char ** -> const char **, but we accept them as an
9137 IncompatibleNestedPointerQualifiers,
9139 /// IncompatibleVectors - The assignment is between two vector types that
9140 /// have the same size, which we accept as an extension.
9141 IncompatibleVectors,
9143 /// IntToBlockPointer - The assignment converts an int to a block
9144 /// pointer. We disallow this.
9147 /// IncompatibleBlockPointer - The assignment is between two block
9148 /// pointers types that are not compatible.
9149 IncompatibleBlockPointer,
9151 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9152 /// id type and something else (that is incompatible with it). For example,
9153 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9154 IncompatibleObjCQualifiedId,
9156 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9157 /// object with __weak qualifier.
9158 IncompatibleObjCWeakRef,
9160 /// Incompatible - We reject this conversion outright, it is invalid to
9161 /// represent it in the AST.
9165 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9166 /// assignment conversion type specified by ConvTy. This returns true if the
9167 /// conversion was invalid or false if the conversion was accepted.
9168 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9170 QualType DstType, QualType SrcType,
9171 Expr *SrcExpr, AssignmentAction Action,
9172 bool *Complained = nullptr);
9174 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9175 /// enum. If AllowMask is true, then we also allow the complement of a valid
9176 /// value, to be used as a mask.
9177 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9178 bool AllowMask) const;
9180 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9181 /// integer not in the range of enum values.
9182 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9185 /// CheckAssignmentConstraints - Perform type checking for assignment,
9186 /// argument passing, variable initialization, and function return values.
9188 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9192 /// Check assignment constraints and optionally prepare for a conversion of
9193 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9195 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9198 bool ConvertRHS = true);
9200 /// Check assignment constraints for an assignment of RHS to LHSType.
9202 /// \param LHSType The destination type for the assignment.
9203 /// \param RHS The source expression for the assignment.
9204 /// \param Diagnose If \c true, diagnostics may be produced when checking
9205 /// for assignability. If a diagnostic is produced, \p RHS will be
9206 /// set to ExprError(). Note that this function may still return
9207 /// without producing a diagnostic, even for an invalid assignment.
9208 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9209 /// in an audited Core Foundation API and does not need to be checked
9210 /// for ARC retain issues.
9211 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9212 /// conversions necessary to perform the assignment. If \c false,
9213 /// \p Diagnose must also be \c false.
9214 AssignConvertType CheckSingleAssignmentConstraints(
9215 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9216 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9218 // \brief If the lhs type is a transparent union, check whether we
9219 // can initialize the transparent union with the given expression.
9220 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9223 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9225 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9227 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9228 AssignmentAction Action,
9229 bool AllowExplicit = false);
9230 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9231 AssignmentAction Action,
9233 ImplicitConversionSequence& ICS);
9234 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9235 const ImplicitConversionSequence& ICS,
9236 AssignmentAction Action,
9237 CheckedConversionKind CCK
9238 = CCK_ImplicitConversion);
9239 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9240 const StandardConversionSequence& SCS,
9241 AssignmentAction Action,
9242 CheckedConversionKind CCK);
9244 /// the following "Check" methods will return a valid/converted QualType
9245 /// or a null QualType (indicating an error diagnostic was issued).
9247 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9248 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9250 QualType CheckPointerToMemberOperands( // C++ 5.5
9251 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9252 SourceLocation OpLoc, bool isIndirect);
9253 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9254 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9256 QualType CheckRemainderOperands( // C99 6.5.5
9257 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9258 bool IsCompAssign = false);
9259 QualType CheckAdditionOperands( // C99 6.5.6
9260 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9261 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9262 QualType CheckSubtractionOperands( // C99 6.5.6
9263 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9264 QualType* CompLHSTy = nullptr);
9265 QualType CheckShiftOperands( // C99 6.5.7
9266 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9267 BinaryOperatorKind Opc, bool IsCompAssign = false);
9268 QualType CheckCompareOperands( // C99 6.5.8/9
9269 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9270 BinaryOperatorKind Opc, bool isRelational);
9271 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9272 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9273 BinaryOperatorKind Opc);
9274 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9275 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9276 BinaryOperatorKind Opc);
9277 // CheckAssignmentOperands is used for both simple and compound assignment.
9278 // For simple assignment, pass both expressions and a null converted type.
9279 // For compound assignment, pass both expressions and the converted type.
9280 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9281 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9283 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9284 UnaryOperatorKind Opcode, Expr *Op);
9285 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9286 BinaryOperatorKind Opcode,
9287 Expr *LHS, Expr *RHS);
9288 ExprResult checkPseudoObjectRValue(Expr *E);
9289 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9291 QualType CheckConditionalOperands( // C99 6.5.15
9292 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9293 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9294 QualType CXXCheckConditionalOperands( // C++ 5.16
9295 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9296 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9297 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9298 bool ConvertArgs = true);
9299 QualType FindCompositePointerType(SourceLocation Loc,
9300 ExprResult &E1, ExprResult &E2,
9301 bool ConvertArgs = true) {
9302 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9303 QualType Composite =
9304 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9310 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9311 SourceLocation QuestionLoc);
9313 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9314 SourceLocation QuestionLoc);
9316 void DiagnoseAlwaysNonNullPointer(Expr *E,
9317 Expr::NullPointerConstantKind NullType,
9318 bool IsEqual, SourceRange Range);
9320 /// type checking for vector binary operators.
9321 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9322 SourceLocation Loc, bool IsCompAssign,
9323 bool AllowBothBool, bool AllowBoolConversion);
9324 QualType GetSignedVectorType(QualType V);
9325 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9326 SourceLocation Loc, bool isRelational);
9327 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9328 SourceLocation Loc);
9330 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9331 bool isLaxVectorConversion(QualType srcType, QualType destType);
9333 /// type checking declaration initializers (C99 6.7.8)
9334 bool CheckForConstantInitializer(Expr *e, QualType t);
9336 // type checking C++ declaration initializers (C++ [dcl.init]).
9338 /// ReferenceCompareResult - Expresses the result of comparing two
9339 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9340 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9341 enum ReferenceCompareResult {
9342 /// Ref_Incompatible - The two types are incompatible, so direct
9343 /// reference binding is not possible.
9344 Ref_Incompatible = 0,
9345 /// Ref_Related - The two types are reference-related, which means
9346 /// that their unqualified forms (T1 and T2) are either the same
9347 /// or T1 is a base class of T2.
9349 /// Ref_Compatible - The two types are reference-compatible.
9353 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9354 QualType T1, QualType T2,
9355 bool &DerivedToBase,
9356 bool &ObjCConversion,
9357 bool &ObjCLifetimeConversion);
9359 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9360 Expr *CastExpr, CastKind &CastKind,
9361 ExprValueKind &VK, CXXCastPath &Path);
9363 /// \brief Force an expression with unknown-type to an expression of the
9365 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9367 /// \brief Type-check an expression that's being passed to an
9368 /// __unknown_anytype parameter.
9369 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9370 Expr *result, QualType ¶mType);
9372 // CheckVectorCast - check type constraints for vectors.
9373 // Since vectors are an extension, there are no C standard reference for this.
9374 // We allow casting between vectors and integer datatypes of the same size.
9375 // returns true if the cast is invalid
9376 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9379 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9380 /// implicit casts if necessary.
9381 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9383 // CheckExtVectorCast - check type constraints for extended vectors.
9384 // Since vectors are an extension, there are no C standard reference for this.
9385 // We allow casting between vectors and integer datatypes of the same size,
9386 // or vectors and the element type of that vector.
9387 // returns the cast expr
9388 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9391 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9392 SourceLocation LParenLoc,
9394 SourceLocation RParenLoc);
9396 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9398 /// \brief Checks for invalid conversions and casts between
9399 /// retainable pointers and other pointer kinds for ARC and Weak.
9400 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9401 QualType castType, Expr *&op,
9402 CheckedConversionKind CCK,
9403 bool Diagnose = true,
9404 bool DiagnoseCFAudited = false,
9405 BinaryOperatorKind Opc = BO_PtrMemD
9408 Expr *stripARCUnbridgedCast(Expr *e);
9409 void diagnoseARCUnbridgedCast(Expr *e);
9411 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9414 /// checkRetainCycles - Check whether an Objective-C message send
9415 /// might create an obvious retain cycle.
9416 void checkRetainCycles(ObjCMessageExpr *msg);
9417 void checkRetainCycles(Expr *receiver, Expr *argument);
9418 void checkRetainCycles(VarDecl *Var, Expr *Init);
9420 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9421 /// to weak/__unsafe_unretained type.
9422 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9424 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9425 /// to weak/__unsafe_unretained expression.
9426 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9428 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9429 /// \param Method - May be null.
9430 /// \param [out] ReturnType - The return type of the send.
9431 /// \return true iff there were any incompatible types.
9432 bool CheckMessageArgumentTypes(QualType ReceiverType,
9433 MultiExprArg Args, Selector Sel,
9434 ArrayRef<SourceLocation> SelectorLocs,
9435 ObjCMethodDecl *Method, bool isClassMessage,
9436 bool isSuperMessage,
9437 SourceLocation lbrac, SourceLocation rbrac,
9438 SourceRange RecRange,
9439 QualType &ReturnType, ExprValueKind &VK);
9441 /// \brief Determine the result of a message send expression based on
9442 /// the type of the receiver, the method expected to receive the message,
9443 /// and the form of the message send.
9444 QualType getMessageSendResultType(QualType ReceiverType,
9445 ObjCMethodDecl *Method,
9446 bool isClassMessage, bool isSuperMessage);
9448 /// \brief If the given expression involves a message send to a method
9449 /// with a related result type, emit a note describing what happened.
9450 void EmitRelatedResultTypeNote(const Expr *E);
9452 /// \brief Given that we had incompatible pointer types in a return
9453 /// statement, check whether we're in a method with a related result
9454 /// type, and if so, emit a note describing what happened.
9455 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9457 class ConditionResult {
9459 FullExprArg Condition;
9465 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9467 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9468 HasKnownValue(IsConstexpr && Condition.get() &&
9469 !Condition.get()->isValueDependent()),
9470 KnownValue(HasKnownValue &&
9471 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9472 explicit ConditionResult(bool Invalid)
9473 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9474 HasKnownValue(false), KnownValue(false) {}
9477 ConditionResult() : ConditionResult(false) {}
9478 bool isInvalid() const { return Invalid; }
9479 std::pair<VarDecl *, Expr *> get() const {
9480 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9483 llvm::Optional<bool> getKnownValue() const {
9489 static ConditionResult ConditionError() { return ConditionResult(true); }
9491 enum class ConditionKind {
9492 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9493 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9494 Switch ///< An integral condition for a 'switch' statement.
9497 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9498 Expr *SubExpr, ConditionKind CK);
9500 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9501 SourceLocation StmtLoc,
9504 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9506 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9507 SourceLocation StmtLoc,
9509 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9511 /// CheckBooleanCondition - Diagnose problems involving the use of
9512 /// the given expression as a boolean condition (e.g. in an if
9513 /// statement). Also performs the standard function and array
9514 /// decays, possibly changing the input variable.
9516 /// \param Loc - A location associated with the condition, e.g. the
9518 /// \return true iff there were any errors
9519 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9520 bool IsConstexpr = false);
9522 /// DiagnoseAssignmentAsCondition - Given that an expression is
9523 /// being used as a boolean condition, warn if it's an assignment.
9524 void DiagnoseAssignmentAsCondition(Expr *E);
9526 /// \brief Redundant parentheses over an equality comparison can indicate
9527 /// that the user intended an assignment used as condition.
9528 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9530 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9531 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9533 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9534 /// the specified width and sign. If an overflow occurs, detect it and emit
9535 /// the specified diagnostic.
9536 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9537 unsigned NewWidth, bool NewSign,
9538 SourceLocation Loc, unsigned DiagID);
9540 /// Checks that the Objective-C declaration is declared in the global scope.
9541 /// Emits an error and marks the declaration as invalid if it's not declared
9542 /// in the global scope.
9543 bool CheckObjCDeclScope(Decl *D);
9545 /// \brief Abstract base class used for diagnosing integer constant
9546 /// expression violations.
9547 class VerifyICEDiagnoser {
9551 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9553 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9554 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9555 virtual ~VerifyICEDiagnoser() { }
9558 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9559 /// and reports the appropriate diagnostics. Returns false on success.
9560 /// Can optionally return the value of the expression.
9561 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9562 VerifyICEDiagnoser &Diagnoser,
9563 bool AllowFold = true);
9564 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9566 bool AllowFold = true);
9567 ExprResult VerifyIntegerConstantExpression(Expr *E,
9568 llvm::APSInt *Result = nullptr);
9570 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9571 /// the correct width, and that the field type is valid.
9572 /// Returns false on success.
9573 /// Can optionally return whether the bit-field is of width 0
9574 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9575 QualType FieldTy, bool IsMsStruct,
9576 Expr *BitWidth, bool *ZeroWidth = nullptr);
9579 unsigned ForceCUDAHostDeviceDepth = 0;
9582 /// Increments our count of the number of times we've seen a pragma forcing
9583 /// functions to be __host__ __device__. So long as this count is greater
9584 /// than zero, all functions encountered will be __host__ __device__.
9585 void PushForceCUDAHostDevice();
9587 /// Decrements our count of the number of times we've seen a pragma forcing
9588 /// functions to be __host__ __device__. Returns false if the count is 0
9589 /// before incrementing, so you can emit an error.
9590 bool PopForceCUDAHostDevice();
9592 /// Diagnostics that are emitted only if we discover that the given function
9593 /// must be codegen'ed. Because handling these correctly adds overhead to
9594 /// compilation, this is currently only enabled for CUDA compilations.
9595 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9596 std::vector<PartialDiagnosticAt>>
9599 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9600 /// key in a hashtable, both the FD and location are hashed.
9601 struct FunctionDeclAndLoc {
9602 CanonicalDeclPtr<FunctionDecl> FD;
9606 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9607 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9608 /// same deferred diag twice.
9609 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9611 /// An inverse call graph, mapping known-emitted functions to one of their
9612 /// known-emitted callers (plus the location of the call).
9614 /// Functions that we can tell a priori must be emitted aren't added to this
9616 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9617 /* Caller = */ FunctionDeclAndLoc>
9618 CUDAKnownEmittedFns;
9620 /// A partial call graph maintained during CUDA compilation to support
9621 /// deferred diagnostics.
9623 /// Functions are only added here if, at the time they're considered, they are
9624 /// not known-emitted. As soon as we discover that a function is
9625 /// known-emitted, we remove it and everything it transitively calls from this
9626 /// set and add those functions to CUDAKnownEmittedFns.
9627 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9628 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9632 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9634 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9635 /// which are not allowed to appear inside __device__ functions and are
9636 /// allowed to appear in __host__ __device__ functions only if the host+device
9637 /// function is never codegen'ed.
9639 /// To handle this, we use the notion of "deferred diagnostics", where we
9640 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9642 /// This class lets you emit either a regular diagnostic, a deferred
9643 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9644 /// its constructor, thus simplifying the process of creating these "maybe
9645 /// deferred" diagnostics.
9646 class CUDADiagBuilder {
9649 /// Emit no diagnostics.
9651 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9653 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9654 /// emit a call stack showing how this function can be reached by an a
9655 /// priori known-emitted function.
9656 K_ImmediateWithCallStack,
9657 /// Create a deferred diagnostic, which is emitted only if the function
9658 /// it's attached to is codegen'ed. Also emit a call stack as with
9659 /// K_ImmediateWithCallStack.
9663 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9664 FunctionDecl *Fn, Sema &S);
9667 /// Convertible to bool: True if we immediately emitted an error, false if
9668 /// we didn't emit an error or we created a deferred error.
9672 /// if (CUDADiagBuilder(...) << foo << bar)
9673 /// return ExprError();
9675 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9676 /// want to use these instead of creating a CUDADiagBuilder yourself.
9677 operator bool() const { return ImmediateDiag.hasValue(); }
9679 template <typename T>
9680 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9682 if (Diag.ImmediateDiag.hasValue())
9683 *Diag.ImmediateDiag << Value;
9684 else if (Diag.PartialDiag.hasValue())
9685 *Diag.PartialDiag << Value;
9696 // Invariant: At most one of these Optionals has a value.
9697 // FIXME: Switch these to a Variant once that exists.
9698 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9699 llvm::Optional<PartialDiagnostic> PartialDiag;
9702 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9703 /// is "used as device code".
9705 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9706 /// - If CurContext is a __device__ or __global__ function, emits the
9707 /// diagnostics immediately.
9708 /// - If CurContext is a __host__ __device__ function and we are compiling for
9709 /// the device, creates a diagnostic which is emitted if and when we realize
9710 /// that the function will be codegen'ed.
9714 /// // Variable-length arrays are not allowed in CUDA device code.
9715 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9716 /// return ExprError();
9717 /// // Otherwise, continue parsing as normal.
9718 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9720 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9721 /// is "used as host code".
9723 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9724 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9726 enum CUDAFunctionTarget {
9734 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9737 /// Use this rather than examining the function's attributes yourself -- you
9738 /// will get it wrong. Returns CFT_Host if D is null.
9739 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9740 bool IgnoreImplicitHDAttr = false);
9741 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9743 /// Gets the CUDA target for the current context.
9744 CUDAFunctionTarget CurrentCUDATarget() {
9745 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9748 // CUDA function call preference. Must be ordered numerically from
9750 enum CUDAFunctionPreference {
9751 CFP_Never, // Invalid caller/callee combination.
9752 CFP_WrongSide, // Calls from host-device to host or device
9753 // function that do not match current compilation
9755 CFP_HostDevice, // Any calls to host/device functions.
9756 CFP_SameSide, // Calls from host-device to host or device
9757 // function matching current compilation mode.
9758 CFP_Native, // host-to-host or device-to-device calls.
9761 /// Identifies relative preference of a given Caller/Callee
9762 /// combination, based on their host/device attributes.
9763 /// \param Caller function which needs address of \p Callee.
9764 /// nullptr in case of global context.
9765 /// \param Callee target function
9767 /// \returns preference value for particular Caller/Callee combination.
9768 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9769 const FunctionDecl *Callee);
9771 /// Determines whether Caller may invoke Callee, based on their CUDA
9772 /// host/device attributes. Returns false if the call is not allowed.
9774 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9775 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9776 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9777 const FunctionDecl *Callee) {
9778 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9781 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9782 /// depending on FD and the current compilation settings.
9783 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9784 const LookupResult &Previous);
9787 /// Check whether we're allowed to call Callee from the current context.
9789 /// - If the call is never allowed in a semantically-correct program
9790 /// (CFP_Never), emits an error and returns false.
9792 /// - If the call is allowed in semantically-correct programs, but only if
9793 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9794 /// be emitted if and when the caller is codegen'ed, and returns true.
9796 /// Will only create deferred diagnostics for a given SourceLocation once,
9797 /// so you can safely call this multiple times without generating duplicate
9798 /// deferred errors.
9800 /// - Otherwise, returns true without emitting any diagnostics.
9801 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9803 /// Set __device__ or __host__ __device__ attributes on the given lambda
9804 /// operator() method.
9806 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9807 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9808 /// functions become __host__ __device__ themselves.
9809 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9811 /// Finds a function in \p Matches with highest calling priority
9812 /// from \p Caller context and erases all functions with lower
9813 /// calling priority.
9814 void EraseUnwantedCUDAMatches(
9815 const FunctionDecl *Caller,
9816 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9818 /// Given a implicit special member, infer its CUDA target from the
9819 /// calls it needs to make to underlying base/field special members.
9820 /// \param ClassDecl the class for which the member is being created.
9821 /// \param CSM the kind of special member.
9822 /// \param MemberDecl the special member itself.
9823 /// \param ConstRHS true if this is a copy operation with a const object on
9825 /// \param Diagnose true if this call should emit diagnostics.
9826 /// \return true if there was an error inferring.
9827 /// The result of this call is implicit CUDA target attribute(s) attached to
9828 /// the member declaration.
9829 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9830 CXXSpecialMember CSM,
9831 CXXMethodDecl *MemberDecl,
9835 /// \return true if \p CD can be considered empty according to CUDA
9836 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9837 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9838 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9840 /// Check whether NewFD is a valid overload for CUDA. Emits
9841 /// diagnostics and invalidates NewFD if not.
9842 void checkCUDATargetOverload(FunctionDecl *NewFD,
9843 const LookupResult &Previous);
9844 /// Copies target attributes from the template TD to the function FD.
9845 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9847 /// \name Code completion
9849 /// \brief Describes the context in which code completion occurs.
9850 enum ParserCompletionContext {
9851 /// \brief Code completion occurs at top-level or namespace context.
9853 /// \brief Code completion occurs within a class, struct, or union.
9855 /// \brief Code completion occurs within an Objective-C interface, protocol,
9858 /// \brief Code completion occurs within an Objective-C implementation or
9859 /// category implementation
9860 PCC_ObjCImplementation,
9861 /// \brief Code completion occurs within the list of instance variables
9862 /// in an Objective-C interface, protocol, category, or implementation.
9863 PCC_ObjCInstanceVariableList,
9864 /// \brief Code completion occurs following one or more template
9867 /// \brief Code completion occurs following one or more template
9868 /// headers within a class.
9870 /// \brief Code completion occurs within an expression.
9872 /// \brief Code completion occurs within a statement, which may
9873 /// also be an expression or a declaration.
9875 /// \brief Code completion occurs at the beginning of the
9876 /// initialization statement (or expression) in a for loop.
9878 /// \brief Code completion occurs within the condition of an if,
9879 /// while, switch, or for statement.
9881 /// \brief Code completion occurs within the body of a function on a
9882 /// recovery path, where we do not have a specific handle on our position
9884 PCC_RecoveryInFunction,
9885 /// \brief Code completion occurs where only a type is permitted.
9887 /// \brief Code completion occurs in a parenthesized expression, which
9888 /// might also be a type cast.
9889 PCC_ParenthesizedExpression,
9890 /// \brief Code completion occurs within a sequence of declaration
9891 /// specifiers within a function, method, or block.
9892 PCC_LocalDeclarationSpecifiers
9895 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9896 void CodeCompleteOrdinaryName(Scope *S,
9897 ParserCompletionContext CompletionContext);
9898 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9899 bool AllowNonIdentifiers,
9900 bool AllowNestedNameSpecifiers);
9902 struct CodeCompleteExpressionData;
9903 void CodeCompleteExpression(Scope *S,
9904 const CodeCompleteExpressionData &Data);
9905 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9906 SourceLocation OpLoc, bool IsArrow,
9907 bool IsBaseExprStatement);
9908 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9909 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9910 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9911 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9912 const VirtSpecifiers *VS = nullptr);
9913 void CodeCompleteBracketDeclarator(Scope *S);
9914 void CodeCompleteCase(Scope *S);
9915 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9916 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9917 ArrayRef<Expr *> Args);
9918 void CodeCompleteInitializer(Scope *S, Decl *D);
9919 void CodeCompleteReturn(Scope *S);
9920 void CodeCompleteAfterIf(Scope *S);
9921 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9923 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9924 bool EnteringContext);
9925 void CodeCompleteUsing(Scope *S);
9926 void CodeCompleteUsingDirective(Scope *S);
9927 void CodeCompleteNamespaceDecl(Scope *S);
9928 void CodeCompleteNamespaceAliasDecl(Scope *S);
9929 void CodeCompleteOperatorName(Scope *S);
9930 void CodeCompleteConstructorInitializer(
9932 ArrayRef<CXXCtorInitializer *> Initializers);
9934 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9935 bool AfterAmpersand);
9937 void CodeCompleteObjCAtDirective(Scope *S);
9938 void CodeCompleteObjCAtVisibility(Scope *S);
9939 void CodeCompleteObjCAtStatement(Scope *S);
9940 void CodeCompleteObjCAtExpression(Scope *S);
9941 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9942 void CodeCompleteObjCPropertyGetter(Scope *S);
9943 void CodeCompleteObjCPropertySetter(Scope *S);
9944 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9946 void CodeCompleteObjCMessageReceiver(Scope *S);
9947 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9948 ArrayRef<IdentifierInfo *> SelIdents,
9949 bool AtArgumentExpression);
9950 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9951 ArrayRef<IdentifierInfo *> SelIdents,
9952 bool AtArgumentExpression,
9953 bool IsSuper = false);
9954 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9955 ArrayRef<IdentifierInfo *> SelIdents,
9956 bool AtArgumentExpression,
9957 ObjCInterfaceDecl *Super = nullptr);
9958 void CodeCompleteObjCForCollection(Scope *S,
9959 DeclGroupPtrTy IterationVar);
9960 void CodeCompleteObjCSelector(Scope *S,
9961 ArrayRef<IdentifierInfo *> SelIdents);
9962 void CodeCompleteObjCProtocolReferences(
9963 ArrayRef<IdentifierLocPair> Protocols);
9964 void CodeCompleteObjCProtocolDecl(Scope *S);
9965 void CodeCompleteObjCInterfaceDecl(Scope *S);
9966 void CodeCompleteObjCSuperclass(Scope *S,
9967 IdentifierInfo *ClassName,
9968 SourceLocation ClassNameLoc);
9969 void CodeCompleteObjCImplementationDecl(Scope *S);
9970 void CodeCompleteObjCInterfaceCategory(Scope *S,
9971 IdentifierInfo *ClassName,
9972 SourceLocation ClassNameLoc);
9973 void CodeCompleteObjCImplementationCategory(Scope *S,
9974 IdentifierInfo *ClassName,
9975 SourceLocation ClassNameLoc);
9976 void CodeCompleteObjCPropertyDefinition(Scope *S);
9977 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9978 IdentifierInfo *PropertyName);
9979 void CodeCompleteObjCMethodDecl(Scope *S,
9980 bool IsInstanceMethod,
9981 ParsedType ReturnType);
9982 void CodeCompleteObjCMethodDeclSelector(Scope *S,
9983 bool IsInstanceMethod,
9984 bool AtParameterName,
9985 ParsedType ReturnType,
9986 ArrayRef<IdentifierInfo *> SelIdents);
9987 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
9988 SourceLocation ClassNameLoc,
9989 bool IsBaseExprStatement);
9990 void CodeCompletePreprocessorDirective(bool InConditional);
9991 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9992 void CodeCompletePreprocessorMacroName(bool IsDefinition);
9993 void CodeCompletePreprocessorExpression();
9994 void CodeCompletePreprocessorMacroArgument(Scope *S,
9995 IdentifierInfo *Macro,
9996 MacroInfo *MacroInfo,
9998 void CodeCompleteNaturalLanguage();
9999 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10000 CodeCompletionTUInfo &CCTUInfo,
10001 SmallVectorImpl<CodeCompletionResult> &Results);
10004 //===--------------------------------------------------------------------===//
10005 // Extra semantic analysis beyond the C type system
10008 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10009 unsigned ByteNo) const;
10012 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10013 const ArraySubscriptExpr *ASE=nullptr,
10014 bool AllowOnePastEnd=true, bool IndexNegated=false);
10015 void CheckArrayAccess(const Expr *E);
10016 // Used to grab the relevant information from a FormatAttr and a
10017 // FunctionDeclaration.
10018 struct FormatStringInfo {
10019 unsigned FormatIdx;
10020 unsigned FirstDataArg;
10024 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10025 FormatStringInfo *FSI);
10026 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10027 const FunctionProtoType *Proto);
10028 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10029 ArrayRef<const Expr *> Args);
10030 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10031 const FunctionProtoType *Proto);
10032 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10033 void CheckConstructorCall(FunctionDecl *FDecl,
10034 ArrayRef<const Expr *> Args,
10035 const FunctionProtoType *Proto,
10036 SourceLocation Loc);
10038 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10039 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10040 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10041 VariadicCallType CallType);
10043 bool CheckObjCString(Expr *Arg);
10044 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10046 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10047 unsigned BuiltinID, CallExpr *TheCall);
10049 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10050 unsigned MaxWidth);
10051 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10052 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10054 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10055 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10056 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10057 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10058 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10059 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10060 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10062 bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
10063 bool SemaBuiltinVAStart(CallExpr *TheCall);
10064 bool SemaBuiltinMSVAStart(CallExpr *TheCall);
10065 bool SemaBuiltinVAStartARM(CallExpr *Call);
10066 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10067 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10068 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10071 // Used by C++ template instantiation.
10072 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10073 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10074 SourceLocation BuiltinLoc,
10075 SourceLocation RParenLoc);
10078 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10079 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10080 bool SemaBuiltinAssume(CallExpr *TheCall);
10081 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10082 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10083 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10084 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10085 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10086 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10087 AtomicExpr::AtomicOp Op);
10088 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10089 llvm::APSInt &Result);
10090 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10091 int Low, int High);
10092 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10093 unsigned Multiple);
10094 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10095 int ArgNum, unsigned ExpectedFieldNum,
10098 enum FormatStringType {
10105 FST_FreeBSDKPrintf,
10110 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10112 bool FormatStringHasSArg(const StringLiteral *FExpr);
10114 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10117 bool CheckFormatArguments(const FormatAttr *Format,
10118 ArrayRef<const Expr *> Args,
10120 VariadicCallType CallType,
10121 SourceLocation Loc, SourceRange Range,
10122 llvm::SmallBitVector &CheckedVarArgs);
10123 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10124 bool HasVAListArg, unsigned format_idx,
10125 unsigned firstDataArg, FormatStringType Type,
10126 VariadicCallType CallType,
10127 SourceLocation Loc, SourceRange range,
10128 llvm::SmallBitVector &CheckedVarArgs);
10130 void CheckAbsoluteValueFunction(const CallExpr *Call,
10131 const FunctionDecl *FDecl);
10133 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10135 void CheckMemaccessArguments(const CallExpr *Call,
10137 IdentifierInfo *FnName);
10139 void CheckStrlcpycatArguments(const CallExpr *Call,
10140 IdentifierInfo *FnName);
10142 void CheckStrncatArguments(const CallExpr *Call,
10143 IdentifierInfo *FnName);
10145 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10146 SourceLocation ReturnLoc,
10147 bool isObjCMethod = false,
10148 const AttrVec *Attrs = nullptr,
10149 const FunctionDecl *FD = nullptr);
10151 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10152 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10153 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10154 void CheckForIntOverflow(Expr *E);
10155 void CheckUnsequencedOperations(Expr *E);
10157 /// \brief Perform semantic checks on a completed expression. This will either
10158 /// be a full-expression or a default argument expression.
10159 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10160 bool IsConstexpr = false);
10162 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10165 /// Check if there is a field shadowing.
10166 void CheckShadowInheritedFields(const SourceLocation &Loc,
10167 DeclarationName FieldName,
10168 const CXXRecordDecl *RD);
10170 /// \brief Check if the given expression contains 'break' or 'continue'
10171 /// statement that produces control flow different from GCC.
10172 void CheckBreakContinueBinding(Expr *E);
10174 /// \brief Check whether receiver is mutable ObjC container which
10175 /// attempts to add itself into the container
10176 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10178 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10179 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10180 bool DeleteWasArrayForm);
10182 /// \brief Register a magic integral constant to be used as a type tag.
10183 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10184 uint64_t MagicValue, QualType Type,
10185 bool LayoutCompatible, bool MustBeNull);
10187 struct TypeTagData {
10190 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10191 Type(Type), LayoutCompatible(LayoutCompatible),
10192 MustBeNull(MustBeNull)
10197 /// If true, \c Type should be compared with other expression's types for
10198 /// layout-compatibility.
10199 unsigned LayoutCompatible : 1;
10200 unsigned MustBeNull : 1;
10203 /// A pair of ArgumentKind identifier and magic value. This uniquely
10204 /// identifies the magic value.
10205 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10208 /// \brief A map from magic value to type information.
10209 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10210 TypeTagForDatatypeMagicValues;
10212 /// \brief Peform checks on a call of a function with argument_with_type_tag
10213 /// or pointer_with_type_tag attributes.
10214 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10215 const Expr * const *ExprArgs);
10217 /// \brief Check if we are taking the address of a packed field
10218 /// as this may be a problem if the pointer value is dereferenced.
10219 void CheckAddressOfPackedMember(Expr *rhs);
10221 /// \brief The parser's current scope.
10223 /// The parser maintains this state here.
10226 mutable IdentifierInfo *Ident_super;
10227 mutable IdentifierInfo *Ident___float128;
10229 /// Nullability type specifiers.
10230 IdentifierInfo *Ident__Nonnull = nullptr;
10231 IdentifierInfo *Ident__Nullable = nullptr;
10232 IdentifierInfo *Ident__Null_unspecified = nullptr;
10234 IdentifierInfo *Ident_NSError = nullptr;
10237 friend class Parser;
10238 friend class InitializationSequence;
10239 friend class ASTReader;
10240 friend class ASTDeclReader;
10241 friend class ASTWriter;
10244 /// Retrieve the keyword associated
10245 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10247 /// The struct behind the CFErrorRef pointer.
10248 RecordDecl *CFError = nullptr;
10250 /// Retrieve the identifier "NSError".
10251 IdentifierInfo *getNSErrorIdent();
10253 /// \brief Retrieve the parser's current scope.
10255 /// This routine must only be used when it is certain that semantic analysis
10256 /// and the parser are in precisely the same context, which is not the case
10257 /// when, e.g., we are performing any kind of template instantiation.
10258 /// Therefore, the only safe places to use this scope are in the parser
10259 /// itself and in routines directly invoked from the parser and *never* from
10260 /// template substitution or instantiation.
10261 Scope *getCurScope() const { return CurScope; }
10263 void incrementMSManglingNumber() const {
10264 return CurScope->incrementMSManglingNumber();
10267 IdentifierInfo *getSuperIdentifier() const;
10268 IdentifierInfo *getFloat128Identifier() const;
10270 Decl *getObjCDeclContext() const;
10272 DeclContext *getCurLexicalContext() const {
10273 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10276 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10278 /// \param D The declaration to check. Note that this may be altered to point
10279 /// to another declaration that \c D gets it's availability from. i.e., we
10280 /// walk the list of typedefs to find an availability attribute.
10282 /// \param Message If non-null, this will be populated with the message from
10283 /// the availability attribute that is selected.
10284 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10285 std::string *Message);
10287 const DeclContext *getCurObjCLexicalContext() const {
10288 const DeclContext *DC = getCurLexicalContext();
10289 // A category implicitly has the attribute of the interface.
10290 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10291 DC = CatD->getClassInterface();
10295 /// \brief To be used for checking whether the arguments being passed to
10296 /// function exceeds the number of parameters expected for it.
10297 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10298 bool PartialOverloading = false) {
10299 // We check whether we're just after a comma in code-completion.
10300 if (NumArgs > 0 && PartialOverloading)
10301 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10302 return NumArgs > NumParams;
10305 // Emitting members of dllexported classes is delayed until the class
10306 // (including field initializers) is fully parsed.
10307 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10310 /// \brief Helper class that collects misaligned member designations and
10311 /// their location info for delayed diagnostics.
10312 struct MisalignedMember {
10316 CharUnits Alignment;
10318 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10319 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10320 CharUnits Alignment)
10321 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10322 explicit MisalignedMember(Expr *E)
10323 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10325 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10327 /// \brief Small set of gathered accesses to potentially misaligned members
10328 /// due to the packed attribute.
10329 SmallVector<MisalignedMember, 4> MisalignedMembers;
10331 /// \brief Adds an expression to the set of gathered misaligned members.
10332 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10333 CharUnits Alignment);
10336 /// \brief Diagnoses the current set of gathered accesses. This typically
10337 /// happens at full expression level. The set is cleared after emitting the
10339 void DiagnoseMisalignedMembers();
10341 /// \brief This function checks if the expression is in the sef of potentially
10342 /// misaligned members and it is converted to some pointer type T with lower
10343 /// or equal alignment requirements. If so it removes it. This is used when
10344 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10346 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10348 /// \brief This function calls Action when it determines that E designates a
10349 /// misaligned member due to the packed attribute. This is used to emit
10350 /// local diagnostics like in reference binding.
10351 void RefersToMemberWithReducedAlignment(
10353 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10357 /// \brief RAII object that enters a new expression evaluation context.
10358 class EnterExpressionEvaluationContext {
10360 bool Entered = true;
10364 EnterExpressionEvaluationContext(Sema &Actions,
10365 Sema::ExpressionEvaluationContext NewContext,
10366 Decl *LambdaContextDecl = nullptr,
10367 bool IsDecltype = false,
10368 bool ShouldEnter = true)
10369 : Actions(Actions), Entered(ShouldEnter) {
10371 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10374 EnterExpressionEvaluationContext(Sema &Actions,
10375 Sema::ExpressionEvaluationContext NewContext,
10376 Sema::ReuseLambdaContextDecl_t,
10377 bool IsDecltype = false)
10378 : Actions(Actions) {
10379 Actions.PushExpressionEvaluationContext(NewContext,
10380 Sema::ReuseLambdaContextDecl,
10384 enum InitListTag { InitList };
10385 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10386 bool ShouldEnter = true)
10387 : Actions(Actions), Entered(false) {
10388 // In C++11 onwards, narrowing checks are performed on the contents of
10389 // braced-init-lists, even when they occur within unevaluated operands.
10390 // Therefore we still need to instantiate constexpr functions used in such
10392 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10393 Actions.getLangOpts().CPlusPlus11) {
10394 Actions.PushExpressionEvaluationContext(
10395 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10400 ~EnterExpressionEvaluationContext() {
10402 Actions.PopExpressionEvaluationContext();
10406 DeductionFailureInfo
10407 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10408 sema::TemplateDeductionInfo &Info);
10410 /// \brief Contains a late templated function.
10411 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10412 struct LateParsedTemplate {
10414 /// \brief The template function declaration to be late parsed.
10418 } // end namespace clang
10421 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10423 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10424 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10425 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10427 static FunctionDeclAndLoc getEmptyKey() {
10428 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10431 static FunctionDeclAndLoc getTombstoneKey() {
10432 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10435 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10436 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10437 FDL.Loc.getRawEncoding());
10440 static bool isEqual(const FunctionDeclAndLoc &LHS,
10441 const FunctionDeclAndLoc &RHS) {
10442 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10445 } // namespace llvm