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 ModuleLoc, ModuleDeclKind MDK,
1940 /// \brief The parser has processed a module import declaration.
1942 /// \param AtLoc The location of the '@' symbol, if any.
1944 /// \param ImportLoc The location of the 'import' keyword.
1946 /// \param Path The module access path.
1947 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1950 /// \brief The parser has processed a module import translated from a
1951 /// #include or similar preprocessing directive.
1952 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1953 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1955 /// \brief The parsed has entered a submodule.
1956 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1957 /// \brief The parser has left a submodule.
1958 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1960 /// \brief Create an implicit import of the given module at the given
1961 /// source location, for error recovery, if possible.
1963 /// This routine is typically used when an entity found by name lookup
1964 /// is actually hidden within a module that we know about but the user
1965 /// has forgotten to import.
1966 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1969 /// Kinds of missing import. Note, the values of these enumerators correspond
1970 /// to %select values in diagnostics.
1971 enum class MissingImportKind {
1975 ExplicitSpecialization,
1976 PartialSpecialization
1979 /// \brief Diagnose that the specified declaration needs to be visible but
1980 /// isn't, and suggest a module import that would resolve the problem.
1981 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1982 MissingImportKind MIK, bool Recover = true);
1983 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1984 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1985 MissingImportKind MIK, bool Recover);
1987 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
1988 SourceLocation LBraceLoc);
1989 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
1990 SourceLocation RBraceLoc);
1992 /// \brief We've found a use of a templated declaration that would trigger an
1993 /// implicit instantiation. Check that any relevant explicit specializations
1994 /// and partial specializations are visible, and diagnose if not.
1995 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1997 /// \brief We've found a use of a template specialization that would select a
1998 /// partial specialization. Check that the partial specialization is visible,
1999 /// and diagnose if not.
2000 void checkPartialSpecializationVisibility(SourceLocation Loc,
2003 /// \brief Retrieve a suitable printing policy.
2004 PrintingPolicy getPrintingPolicy() const {
2005 return getPrintingPolicy(Context, PP);
2008 /// \brief Retrieve a suitable printing policy.
2009 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2010 const Preprocessor &PP);
2013 void ActOnPopScope(SourceLocation Loc, Scope *S);
2014 void ActOnTranslationUnitScope(Scope *S);
2016 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2017 RecordDecl *&AnonRecord);
2018 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2019 MultiTemplateParamsArg TemplateParams,
2020 bool IsExplicitInstantiation,
2021 RecordDecl *&AnonRecord);
2023 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2026 const PrintingPolicy &Policy);
2028 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2029 RecordDecl *Record);
2031 /// Common ways to introduce type names without a tag for use in diagnostics.
2032 /// Keep in sync with err_tag_reference_non_tag.
2041 NTK_TypeAliasTemplate,
2042 NTK_TemplateTemplateArgument,
2045 /// Given a non-tag type declaration, returns an enum useful for indicating
2046 /// what kind of non-tag type this is.
2047 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2049 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2050 TagTypeKind NewTag, bool isDefinition,
2051 SourceLocation NewTagLoc,
2052 const IdentifierInfo *Name);
2055 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2056 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2057 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2058 TUK_Friend // Friend declaration: 'friend struct foo;'
2061 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2062 SourceLocation KWLoc, CXXScopeSpec &SS,
2063 IdentifierInfo *Name, SourceLocation NameLoc,
2064 AttributeList *Attr, AccessSpecifier AS,
2065 SourceLocation ModulePrivateLoc,
2066 MultiTemplateParamsArg TemplateParameterLists,
2067 bool &OwnedDecl, bool &IsDependent,
2068 SourceLocation ScopedEnumKWLoc,
2069 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2070 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2072 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2073 unsigned TagSpec, SourceLocation TagLoc,
2075 IdentifierInfo *Name, SourceLocation NameLoc,
2076 AttributeList *Attr,
2077 MultiTemplateParamsArg TempParamLists);
2079 TypeResult ActOnDependentTag(Scope *S,
2082 const CXXScopeSpec &SS,
2083 IdentifierInfo *Name,
2084 SourceLocation TagLoc,
2085 SourceLocation NameLoc);
2087 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2088 IdentifierInfo *ClassName,
2089 SmallVectorImpl<Decl *> &Decls);
2090 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2091 Declarator &D, Expr *BitfieldWidth);
2093 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2094 Declarator &D, Expr *BitfieldWidth,
2095 InClassInitStyle InitStyle,
2096 AccessSpecifier AS);
2097 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2098 SourceLocation DeclStart,
2099 Declarator &D, Expr *BitfieldWidth,
2100 InClassInitStyle InitStyle,
2102 AttributeList *MSPropertyAttr);
2104 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2105 TypeSourceInfo *TInfo,
2106 RecordDecl *Record, SourceLocation Loc,
2107 bool Mutable, Expr *BitfieldWidth,
2108 InClassInitStyle InitStyle,
2109 SourceLocation TSSL,
2110 AccessSpecifier AS, NamedDecl *PrevDecl,
2111 Declarator *D = nullptr);
2113 bool CheckNontrivialField(FieldDecl *FD);
2114 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2115 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2116 bool Diagnose = false);
2117 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2118 void ActOnLastBitfield(SourceLocation DeclStart,
2119 SmallVectorImpl<Decl *> &AllIvarDecls);
2120 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2121 Declarator &D, Expr *BitfieldWidth,
2122 tok::ObjCKeywordKind visibility);
2124 // This is used for both record definitions and ObjC interface declarations.
2125 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2126 ArrayRef<Decl *> Fields,
2127 SourceLocation LBrac, SourceLocation RBrac,
2128 AttributeList *AttrList);
2130 /// ActOnTagStartDefinition - Invoked when we have entered the
2131 /// scope of a tag's definition (e.g., for an enumeration, class,
2132 /// struct, or union).
2133 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2135 typedef void *SkippedDefinitionContext;
2137 /// \brief Invoked when we enter a tag definition that we're skipping.
2138 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2140 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2142 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2143 /// C++ record definition's base-specifiers clause and are starting its
2144 /// member declarations.
2145 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2146 SourceLocation FinalLoc,
2147 bool IsFinalSpelledSealed,
2148 SourceLocation LBraceLoc);
2150 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2151 /// the definition of a tag (enumeration, class, struct, or union).
2152 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2153 SourceRange BraceRange);
2155 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2157 void ActOnObjCContainerFinishDefinition();
2159 /// \brief Invoked when we must temporarily exit the objective-c container
2160 /// scope for parsing/looking-up C constructs.
2162 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2163 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2164 void ActOnObjCReenterContainerContext(DeclContext *DC);
2166 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2167 /// error parsing the definition of a tag.
2168 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2170 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2171 EnumConstantDecl *LastEnumConst,
2172 SourceLocation IdLoc,
2175 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2176 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2177 QualType EnumUnderlyingTy,
2178 bool EnumUnderlyingIsImplicit,
2179 const EnumDecl *Prev);
2181 /// Determine whether the body of an anonymous enumeration should be skipped.
2182 /// \param II The name of the first enumerator.
2183 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2184 SourceLocation IILoc);
2186 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2187 SourceLocation IdLoc, IdentifierInfo *Id,
2188 AttributeList *Attrs,
2189 SourceLocation EqualLoc, Expr *Val);
2190 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2192 ArrayRef<Decl *> Elements,
2193 Scope *S, AttributeList *Attr);
2195 DeclContext *getContainingDC(DeclContext *DC);
2197 /// Set the current declaration context until it gets popped.
2198 void PushDeclContext(Scope *S, DeclContext *DC);
2199 void PopDeclContext();
2201 /// EnterDeclaratorContext - Used when we must lookup names in the context
2202 /// of a declarator's nested name specifier.
2203 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2204 void ExitDeclaratorContext(Scope *S);
2206 /// Push the parameters of D, which must be a function, into scope.
2207 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2208 void ActOnExitFunctionContext();
2210 DeclContext *getFunctionLevelDeclContext();
2212 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2213 /// to the function decl for the function being parsed. If we're currently
2214 /// in a 'block', this returns the containing context.
2215 FunctionDecl *getCurFunctionDecl();
2217 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2218 /// the method decl for the method being parsed. If we're currently
2219 /// in a 'block', this returns the containing context.
2220 ObjCMethodDecl *getCurMethodDecl();
2222 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2223 /// or C function we're in, otherwise return null. If we're currently
2224 /// in a 'block', this returns the containing context.
2225 NamedDecl *getCurFunctionOrMethodDecl();
2227 /// Add this decl to the scope shadowed decl chains.
2228 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2230 /// \brief Make the given externally-produced declaration visible at the
2231 /// top level scope.
2233 /// \param D The externally-produced declaration to push.
2235 /// \param Name The name of the externally-produced declaration.
2236 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2238 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2239 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2240 /// true if 'D' belongs to the given declaration context.
2242 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2243 /// enclosing namespace set of the context, rather than contained
2244 /// directly within it.
2245 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2246 bool AllowInlineNamespace = false);
2248 /// Finds the scope corresponding to the given decl context, if it
2249 /// happens to be an enclosing scope. Otherwise return NULL.
2250 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2252 /// Subroutines of ActOnDeclarator().
2253 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2254 TypeSourceInfo *TInfo);
2255 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2257 /// \brief Describes the kind of merge to perform for availability
2258 /// attributes (including "deprecated", "unavailable", and "availability").
2259 enum AvailabilityMergeKind {
2260 /// \brief Don't merge availability attributes at all.
2262 /// \brief Merge availability attributes for a redeclaration, which requires
2265 /// \brief Merge availability attributes for an override, which requires
2266 /// an exact match or a weakening of constraints.
2268 /// \brief Merge availability attributes for an implementation of
2269 /// a protocol requirement.
2270 AMK_ProtocolImplementation,
2273 /// Attribute merging methods. Return true if a new attribute was added.
2274 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2275 IdentifierInfo *Platform,
2277 VersionTuple Introduced,
2278 VersionTuple Deprecated,
2279 VersionTuple Obsoleted,
2282 bool IsStrict, StringRef Replacement,
2283 AvailabilityMergeKind AMK,
2284 unsigned AttrSpellingListIndex);
2285 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2286 TypeVisibilityAttr::VisibilityType Vis,
2287 unsigned AttrSpellingListIndex);
2288 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2289 VisibilityAttr::VisibilityType Vis,
2290 unsigned AttrSpellingListIndex);
2291 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2292 unsigned AttrSpellingListIndex, StringRef Uuid);
2293 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2294 unsigned AttrSpellingListIndex);
2295 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2296 unsigned AttrSpellingListIndex);
2298 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2299 unsigned AttrSpellingListIndex,
2300 MSInheritanceAttr::Spelling SemanticSpelling);
2301 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2302 IdentifierInfo *Format, int FormatIdx,
2303 int FirstArg, unsigned AttrSpellingListIndex);
2304 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2305 unsigned AttrSpellingListIndex);
2306 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2307 IdentifierInfo *Ident,
2308 unsigned AttrSpellingListIndex);
2309 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2310 unsigned AttrSpellingListIndex);
2311 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2312 unsigned AttrSpellingListIndex);
2313 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2314 IdentifierInfo *Ident,
2315 unsigned AttrSpellingListIndex);
2316 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2317 unsigned AttrSpellingListIndex);
2319 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2320 AvailabilityMergeKind AMK = AMK_Redeclaration);
2321 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2322 LookupResult &OldDecls);
2323 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2324 bool MergeTypeWithOld);
2325 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2326 Scope *S, bool MergeTypeWithOld);
2327 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2328 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2329 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2330 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2331 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2332 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2334 // AssignmentAction - This is used by all the assignment diagnostic functions
2335 // to represent what is actually causing the operation
2336 enum AssignmentAction {
2344 AA_Passing_CFAudited
2347 /// C++ Overloading.
2349 /// This is a legitimate overload: the existing declarations are
2350 /// functions or function templates with different signatures.
2353 /// This is not an overload because the signature exactly matches
2354 /// an existing declaration.
2357 /// This is not an overload because the lookup results contain a
2361 OverloadKind CheckOverload(Scope *S,
2363 const LookupResult &OldDecls,
2364 NamedDecl *&OldDecl,
2365 bool IsForUsingDecl);
2366 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2367 bool ConsiderCudaAttrs = true);
2369 /// \brief Checks availability of the function depending on the current
2370 /// function context.Inside an unavailable function,unavailability is ignored.
2372 /// \returns true if \p FD is unavailable and current context is inside
2373 /// an available function, false otherwise.
2374 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2376 ImplicitConversionSequence
2377 TryImplicitConversion(Expr *From, QualType ToType,
2378 bool SuppressUserConversions,
2380 bool InOverloadResolution,
2382 bool AllowObjCWritebackConversion);
2384 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2385 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2386 bool IsComplexPromotion(QualType FromType, QualType ToType);
2387 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2388 bool InOverloadResolution,
2389 QualType& ConvertedType, bool &IncompatibleObjC);
2390 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2391 QualType& ConvertedType, bool &IncompatibleObjC);
2392 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2393 QualType &ConvertedType);
2394 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2395 QualType& ConvertedType);
2396 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2397 const FunctionProtoType *NewType,
2398 unsigned *ArgPos = nullptr);
2399 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2400 QualType FromType, QualType ToType);
2402 void maybeExtendBlockObject(ExprResult &E);
2403 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2404 bool CheckPointerConversion(Expr *From, QualType ToType,
2406 CXXCastPath& BasePath,
2407 bool IgnoreBaseAccess,
2408 bool Diagnose = true);
2409 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2410 bool InOverloadResolution,
2411 QualType &ConvertedType);
2412 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2414 CXXCastPath &BasePath,
2415 bool IgnoreBaseAccess);
2416 bool IsQualificationConversion(QualType FromType, QualType ToType,
2417 bool CStyle, bool &ObjCLifetimeConversion);
2418 bool IsFunctionConversion(QualType FromType, QualType ToType,
2419 QualType &ResultTy);
2420 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2421 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2423 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2424 const VarDecl *NRVOCandidate,
2425 QualType ResultType,
2427 bool AllowNRVO = true);
2429 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2431 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2432 SourceLocation EqualLoc,
2434 bool TopLevelOfInitList = false,
2435 bool AllowExplicit = false);
2436 ExprResult PerformObjectArgumentInitialization(Expr *From,
2437 NestedNameSpecifier *Qualifier,
2438 NamedDecl *FoundDecl,
2439 CXXMethodDecl *Method);
2441 ExprResult PerformContextuallyConvertToBool(Expr *From);
2442 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2444 /// Contexts in which a converted constant expression is required.
2446 CCEK_CaseValue, ///< Expression in a case label.
2447 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2448 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2449 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2450 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2452 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2453 llvm::APSInt &Value, CCEKind CCE);
2454 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2455 APValue &Value, CCEKind CCE);
2457 /// \brief Abstract base class used to perform a contextual implicit
2458 /// conversion from an expression to any type passing a filter.
2459 class ContextualImplicitConverter {
2462 bool SuppressConversion;
2464 ContextualImplicitConverter(bool Suppress = false,
2465 bool SuppressConversion = false)
2466 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2468 /// \brief Determine whether the specified type is a valid destination type
2469 /// for this conversion.
2470 virtual bool match(QualType T) = 0;
2472 /// \brief Emits a diagnostic complaining that the expression does not have
2473 /// integral or enumeration type.
2474 virtual SemaDiagnosticBuilder
2475 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2477 /// \brief Emits a diagnostic when the expression has incomplete class type.
2478 virtual SemaDiagnosticBuilder
2479 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2481 /// \brief Emits a diagnostic when the only matching conversion function
2483 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2484 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2486 /// \brief Emits a note for the explicit conversion function.
2487 virtual SemaDiagnosticBuilder
2488 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2490 /// \brief Emits a diagnostic when there are multiple possible conversion
2492 virtual SemaDiagnosticBuilder
2493 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2495 /// \brief Emits a note for one of the candidate conversions.
2496 virtual SemaDiagnosticBuilder
2497 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2499 /// \brief Emits a diagnostic when we picked a conversion function
2500 /// (for cases when we are not allowed to pick a conversion function).
2501 virtual SemaDiagnosticBuilder diagnoseConversion(
2502 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2504 virtual ~ContextualImplicitConverter() {}
2507 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2508 bool AllowScopedEnumerations;
2511 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2512 bool Suppress, bool SuppressConversion)
2513 : ContextualImplicitConverter(Suppress, SuppressConversion),
2514 AllowScopedEnumerations(AllowScopedEnumerations) {}
2516 /// Match an integral or (possibly scoped) enumeration type.
2517 bool match(QualType T) override;
2519 SemaDiagnosticBuilder
2520 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2521 return diagnoseNotInt(S, Loc, T);
2524 /// \brief Emits a diagnostic complaining that the expression does not have
2525 /// integral or enumeration type.
2526 virtual SemaDiagnosticBuilder
2527 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2530 /// Perform a contextual implicit conversion.
2531 ExprResult PerformContextualImplicitConversion(
2532 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2535 enum ObjCSubscriptKind {
2540 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2542 // Note that LK_String is intentionally after the other literals, as
2543 // this is used for diagnostics logic.
2544 enum ObjCLiteralKind {
2553 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2555 ExprResult PerformObjectMemberConversion(Expr *From,
2556 NestedNameSpecifier *Qualifier,
2557 NamedDecl *FoundDecl,
2560 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2561 // TODO: make this is a typesafe union.
2562 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2563 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2565 void AddOverloadCandidate(FunctionDecl *Function,
2566 DeclAccessPair FoundDecl,
2567 ArrayRef<Expr *> Args,
2568 OverloadCandidateSet &CandidateSet,
2569 bool SuppressUserConversions = false,
2570 bool PartialOverloading = false,
2571 bool AllowExplicit = false,
2572 ConversionSequenceList EarlyConversions = None);
2573 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2574 ArrayRef<Expr *> Args,
2575 OverloadCandidateSet &CandidateSet,
2576 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2577 bool SuppressUserConversions = false,
2578 bool PartialOverloading = false);
2579 void AddMethodCandidate(DeclAccessPair FoundDecl,
2580 QualType ObjectType,
2581 Expr::Classification ObjectClassification,
2582 ArrayRef<Expr *> Args,
2583 OverloadCandidateSet& CandidateSet,
2584 bool SuppressUserConversion = false);
2585 void AddMethodCandidate(CXXMethodDecl *Method,
2586 DeclAccessPair FoundDecl,
2587 CXXRecordDecl *ActingContext, QualType ObjectType,
2588 Expr::Classification ObjectClassification,
2589 ArrayRef<Expr *> Args,
2590 OverloadCandidateSet& CandidateSet,
2591 bool SuppressUserConversions = false,
2592 bool PartialOverloading = false,
2593 ConversionSequenceList EarlyConversions = None);
2594 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2595 DeclAccessPair FoundDecl,
2596 CXXRecordDecl *ActingContext,
2597 TemplateArgumentListInfo *ExplicitTemplateArgs,
2598 QualType ObjectType,
2599 Expr::Classification ObjectClassification,
2600 ArrayRef<Expr *> Args,
2601 OverloadCandidateSet& CandidateSet,
2602 bool SuppressUserConversions = false,
2603 bool PartialOverloading = false);
2604 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2605 DeclAccessPair FoundDecl,
2606 TemplateArgumentListInfo *ExplicitTemplateArgs,
2607 ArrayRef<Expr *> Args,
2608 OverloadCandidateSet& CandidateSet,
2609 bool SuppressUserConversions = false,
2610 bool PartialOverloading = false);
2611 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2612 ArrayRef<QualType> ParamTypes,
2613 ArrayRef<Expr *> Args,
2614 OverloadCandidateSet &CandidateSet,
2615 ConversionSequenceList &Conversions,
2616 bool SuppressUserConversions,
2617 CXXRecordDecl *ActingContext = nullptr,
2618 QualType ObjectType = QualType(),
2619 Expr::Classification
2620 ObjectClassification = {});
2621 void AddConversionCandidate(CXXConversionDecl *Conversion,
2622 DeclAccessPair FoundDecl,
2623 CXXRecordDecl *ActingContext,
2624 Expr *From, QualType ToType,
2625 OverloadCandidateSet& CandidateSet,
2626 bool AllowObjCConversionOnExplicit);
2627 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2628 DeclAccessPair FoundDecl,
2629 CXXRecordDecl *ActingContext,
2630 Expr *From, QualType ToType,
2631 OverloadCandidateSet &CandidateSet,
2632 bool AllowObjCConversionOnExplicit);
2633 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2634 DeclAccessPair FoundDecl,
2635 CXXRecordDecl *ActingContext,
2636 const FunctionProtoType *Proto,
2637 Expr *Object, ArrayRef<Expr *> Args,
2638 OverloadCandidateSet& CandidateSet);
2639 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2640 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2641 OverloadCandidateSet& CandidateSet,
2642 SourceRange OpRange = SourceRange());
2643 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2644 ArrayRef<Expr *> Args,
2645 OverloadCandidateSet& CandidateSet,
2646 bool IsAssignmentOperator = false,
2647 unsigned NumContextualBoolArguments = 0);
2648 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2649 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2650 OverloadCandidateSet& CandidateSet);
2651 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2653 ArrayRef<Expr *> Args,
2654 TemplateArgumentListInfo *ExplicitTemplateArgs,
2655 OverloadCandidateSet& CandidateSet,
2656 bool PartialOverloading = false);
2658 // Emit as a 'note' the specific overload candidate
2659 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2660 QualType DestType = QualType(),
2661 bool TakingAddress = false);
2663 // Emit as a series of 'note's all template and non-templates identified by
2664 // the expression Expr
2665 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2666 bool TakingAddress = false);
2668 /// Check the enable_if expressions on the given function. Returns the first
2669 /// failing attribute, or NULL if they were all successful.
2670 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2671 bool MissingImplicitThis = false);
2673 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2674 /// non-ArgDependent DiagnoseIfAttrs.
2676 /// Argument-dependent diagnose_if attributes should be checked each time a
2677 /// function is used as a direct callee of a function call.
2679 /// Returns true if any errors were emitted.
2680 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2681 const Expr *ThisArg,
2682 ArrayRef<const Expr *> Args,
2683 SourceLocation Loc);
2685 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2686 /// ArgDependent DiagnoseIfAttrs.
2688 /// Argument-independent diagnose_if attributes should be checked on every use
2691 /// Returns true if any errors were emitted.
2692 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2693 SourceLocation Loc);
2695 /// Returns whether the given function's address can be taken or not,
2696 /// optionally emitting a diagnostic if the address can't be taken.
2698 /// Returns false if taking the address of the function is illegal.
2699 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2700 bool Complain = false,
2701 SourceLocation Loc = SourceLocation());
2703 // [PossiblyAFunctionType] --> [Return]
2704 // NonFunctionType --> NonFunctionType
2706 // R (*)(A) --> R (A)
2707 // R (&)(A) --> R (A)
2708 // R (S::*)(A) --> R (A)
2709 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2712 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2713 QualType TargetType,
2715 DeclAccessPair &Found,
2716 bool *pHadMultipleCandidates = nullptr);
2719 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2720 DeclAccessPair &FoundResult);
2722 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2725 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2726 bool Complain = false,
2727 DeclAccessPair *Found = nullptr);
2729 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2730 ExprResult &SrcExpr,
2731 bool DoFunctionPointerConverion = false,
2732 bool Complain = false,
2733 SourceRange OpRangeForComplaining = SourceRange(),
2734 QualType DestTypeForComplaining = QualType(),
2735 unsigned DiagIDForComplaining = 0);
2738 Expr *FixOverloadedFunctionReference(Expr *E,
2739 DeclAccessPair FoundDecl,
2741 ExprResult FixOverloadedFunctionReference(ExprResult,
2742 DeclAccessPair FoundDecl,
2745 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2746 ArrayRef<Expr *> Args,
2747 OverloadCandidateSet &CandidateSet,
2748 bool PartialOverloading = false);
2750 // An enum used to represent the different possible results of building a
2751 // range-based for loop.
2752 enum ForRangeStatus {
2754 FRS_NoViableFunction,
2755 FRS_DiagnosticIssued
2758 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2759 SourceLocation RangeLoc,
2760 const DeclarationNameInfo &NameInfo,
2761 LookupResult &MemberLookup,
2762 OverloadCandidateSet *CandidateSet,
2763 Expr *Range, ExprResult *CallExpr);
2765 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2766 UnresolvedLookupExpr *ULE,
2767 SourceLocation LParenLoc,
2769 SourceLocation RParenLoc,
2771 bool AllowTypoCorrection=true,
2772 bool CalleesAddressIsTaken=false);
2774 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2775 MultiExprArg Args, SourceLocation RParenLoc,
2776 OverloadCandidateSet *CandidateSet,
2777 ExprResult *Result);
2779 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2780 UnaryOperatorKind Opc,
2781 const UnresolvedSetImpl &Fns,
2784 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2785 BinaryOperatorKind Opc,
2786 const UnresolvedSetImpl &Fns,
2787 Expr *LHS, Expr *RHS);
2789 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2790 SourceLocation RLoc,
2791 Expr *Base,Expr *Idx);
2794 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2795 SourceLocation LParenLoc,
2797 SourceLocation RParenLoc);
2799 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2801 SourceLocation RParenLoc);
2803 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2804 SourceLocation OpLoc,
2805 bool *NoArrowOperatorFound = nullptr);
2807 /// CheckCallReturnType - Checks that a call expression's return type is
2808 /// complete. Returns true on failure. The location passed in is the location
2809 /// that best represents the call.
2810 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2811 CallExpr *CE, FunctionDecl *FD);
2813 /// Helpers for dealing with blocks and functions.
2814 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2815 bool CheckParameterNames);
2816 void CheckCXXDefaultArguments(FunctionDecl *FD);
2817 void CheckExtraCXXDefaultArguments(Declarator &D);
2818 Scope *getNonFieldDeclScope(Scope *S);
2820 /// \name Name lookup
2822 /// These routines provide name lookup that is used during semantic
2823 /// analysis to resolve the various kinds of names (identifiers,
2824 /// overloaded operator names, constructor names, etc.) into zero or
2825 /// more declarations within a particular scope. The major entry
2826 /// points are LookupName, which performs unqualified name lookup,
2827 /// and LookupQualifiedName, which performs qualified name lookup.
2829 /// All name lookup is performed based on some specific criteria,
2830 /// which specify what names will be visible to name lookup and how
2831 /// far name lookup should work. These criteria are important both
2832 /// for capturing language semantics (certain lookups will ignore
2833 /// certain names, for example) and for performance, since name
2834 /// lookup is often a bottleneck in the compilation of C++. Name
2835 /// lookup criteria is specified via the LookupCriteria enumeration.
2837 /// The results of name lookup can vary based on the kind of name
2838 /// lookup performed, the current language, and the translation
2839 /// unit. In C, for example, name lookup will either return nothing
2840 /// (no entity found) or a single declaration. In C++, name lookup
2841 /// can additionally refer to a set of overloaded functions or
2842 /// result in an ambiguity. All of the possible results of name
2843 /// lookup are captured by the LookupResult class, which provides
2844 /// the ability to distinguish among them.
2847 /// @brief Describes the kind of name lookup to perform.
2848 enum LookupNameKind {
2849 /// Ordinary name lookup, which finds ordinary names (functions,
2850 /// variables, typedefs, etc.) in C and most kinds of names
2851 /// (functions, variables, members, types, etc.) in C++.
2852 LookupOrdinaryName = 0,
2853 /// Tag name lookup, which finds the names of enums, classes,
2854 /// structs, and unions.
2856 /// Label name lookup.
2858 /// Member name lookup, which finds the names of
2859 /// class/struct/union members.
2861 /// Look up of an operator name (e.g., operator+) for use with
2862 /// operator overloading. This lookup is similar to ordinary name
2863 /// lookup, but will ignore any declarations that are class members.
2865 /// Look up of a name that precedes the '::' scope resolution
2866 /// operator in C++. This lookup completely ignores operator, object,
2867 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2868 LookupNestedNameSpecifierName,
2869 /// Look up a namespace name within a C++ using directive or
2870 /// namespace alias definition, ignoring non-namespace names (C++
2871 /// [basic.lookup.udir]p1).
2872 LookupNamespaceName,
2873 /// Look up all declarations in a scope with the given name,
2874 /// including resolved using declarations. This is appropriate
2875 /// for checking redeclarations for a using declaration.
2876 LookupUsingDeclName,
2877 /// Look up an ordinary name that is going to be redeclared as a
2878 /// name with linkage. This lookup ignores any declarations that
2879 /// are outside of the current scope unless they have linkage. See
2880 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2881 LookupRedeclarationWithLinkage,
2882 /// Look up a friend of a local class. This lookup does not look
2883 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2884 LookupLocalFriendName,
2885 /// Look up the name of an Objective-C protocol.
2886 LookupObjCProtocolName,
2887 /// Look up implicit 'self' parameter of an objective-c method.
2888 LookupObjCImplicitSelfParam,
2889 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2890 LookupOMPReductionName,
2891 /// \brief Look up any declaration with any name.
2895 /// \brief Specifies whether (or how) name lookup is being performed for a
2896 /// redeclaration (vs. a reference).
2897 enum RedeclarationKind {
2898 /// \brief The lookup is a reference to this name that is not for the
2899 /// purpose of redeclaring the name.
2900 NotForRedeclaration = 0,
2901 /// \brief The lookup results will be used for redeclaration of a name,
2902 /// if an entity by that name already exists.
2906 /// \brief The possible outcomes of name lookup for a literal operator.
2907 enum LiteralOperatorLookupResult {
2908 /// \brief The lookup resulted in an error.
2910 /// \brief The lookup found a single 'cooked' literal operator, which
2911 /// expects a normal literal to be built and passed to it.
2913 /// \brief The lookup found a single 'raw' literal operator, which expects
2914 /// a string literal containing the spelling of the literal token.
2916 /// \brief The lookup found an overload set of literal operator templates,
2917 /// which expect the characters of the spelling of the literal token to be
2918 /// passed as a non-type template argument pack.
2920 /// \brief The lookup found an overload set of literal operator templates,
2921 /// which expect the character type and characters of the spelling of the
2922 /// string literal token to be passed as template arguments.
2926 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2927 CXXSpecialMember SM,
2934 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2935 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2936 TypoRecoveryCallback;
2939 bool CppLookupName(LookupResult &R, Scope *S);
2941 struct TypoExprState {
2942 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2943 TypoDiagnosticGenerator DiagHandler;
2944 TypoRecoveryCallback RecoveryHandler;
2946 TypoExprState(TypoExprState &&other) noexcept;
2947 TypoExprState &operator=(TypoExprState &&other) noexcept;
2950 /// \brief The set of unhandled TypoExprs and their associated state.
2951 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2953 /// \brief Creates a new TypoExpr AST node.
2954 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2955 TypoDiagnosticGenerator TDG,
2956 TypoRecoveryCallback TRC);
2958 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2960 // The boolean value will be true to indicate that the namespace was loaded
2961 // from an AST/PCH file, or false otherwise.
2962 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2964 /// \brief Whether we have already loaded known namespaces from an extenal
2966 bool LoadedExternalKnownNamespaces;
2968 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2969 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2970 /// should be skipped entirely.
2971 std::unique_ptr<TypoCorrectionConsumer>
2972 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2973 Sema::LookupNameKind LookupKind, Scope *S,
2975 std::unique_ptr<CorrectionCandidateCallback> CCC,
2976 DeclContext *MemberContext, bool EnteringContext,
2977 const ObjCObjectPointerType *OPT,
2978 bool ErrorRecovery);
2981 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2983 /// \brief Clears the state of the given TypoExpr.
2984 void clearDelayedTypo(TypoExpr *TE);
2986 /// \brief Look up a name, looking for a single declaration. Return
2987 /// null if the results were absent, ambiguous, or overloaded.
2989 /// It is preferable to use the elaborated form and explicitly handle
2990 /// ambiguity and overloaded.
2991 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2993 LookupNameKind NameKind,
2994 RedeclarationKind Redecl
2995 = NotForRedeclaration);
2996 bool LookupName(LookupResult &R, Scope *S,
2997 bool AllowBuiltinCreation = false);
2998 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2999 bool InUnqualifiedLookup = false);
3000 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3002 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3003 bool AllowBuiltinCreation = false,
3004 bool EnteringContext = false);
3005 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3006 RedeclarationKind Redecl
3007 = NotForRedeclaration);
3008 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3010 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3011 QualType T1, QualType T2,
3012 UnresolvedSetImpl &Functions);
3014 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3015 SourceLocation GnuLabelLoc = SourceLocation());
3017 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3018 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3019 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3021 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3022 bool RValueThis, unsigned ThisQuals);
3023 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3025 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3026 bool RValueThis, unsigned ThisQuals);
3027 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3029 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3030 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3031 ArrayRef<QualType> ArgTys,
3034 bool AllowStringTemplate);
3035 bool isKnownName(StringRef name);
3037 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3038 ArrayRef<Expr *> Args, ADLResult &Functions);
3040 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3041 VisibleDeclConsumer &Consumer,
3042 bool IncludeGlobalScope = true);
3043 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3044 VisibleDeclConsumer &Consumer,
3045 bool IncludeGlobalScope = true);
3047 enum CorrectTypoKind {
3048 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3049 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3052 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3053 Sema::LookupNameKind LookupKind,
3054 Scope *S, CXXScopeSpec *SS,
3055 std::unique_ptr<CorrectionCandidateCallback> CCC,
3056 CorrectTypoKind Mode,
3057 DeclContext *MemberContext = nullptr,
3058 bool EnteringContext = false,
3059 const ObjCObjectPointerType *OPT = nullptr,
3060 bool RecordFailure = true);
3062 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3063 Sema::LookupNameKind LookupKind, Scope *S,
3065 std::unique_ptr<CorrectionCandidateCallback> CCC,
3066 TypoDiagnosticGenerator TDG,
3067 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3068 DeclContext *MemberContext = nullptr,
3069 bool EnteringContext = false,
3070 const ObjCObjectPointerType *OPT = nullptr);
3072 /// \brief Process any TypoExprs in the given Expr and its children,
3073 /// generating diagnostics as appropriate and returning a new Expr if there
3074 /// were typos that were all successfully corrected and ExprError if one or
3075 /// more typos could not be corrected.
3077 /// \param E The Expr to check for TypoExprs.
3079 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3082 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3083 /// it is an acceptable/usable result from a single combination of typo
3084 /// corrections. As long as the filter returns ExprError, different
3085 /// combinations of corrections will be tried until all are exhausted.
3087 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3088 llvm::function_ref<ExprResult(Expr *)> Filter =
3089 [](Expr *E) -> ExprResult { return E; });
3092 CorrectDelayedTyposInExpr(Expr *E,
3093 llvm::function_ref<ExprResult(Expr *)> Filter) {
3094 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3098 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3099 llvm::function_ref<ExprResult(Expr *)> Filter =
3100 [](Expr *E) -> ExprResult { return E; }) {
3101 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3105 CorrectDelayedTyposInExpr(ExprResult ER,
3106 llvm::function_ref<ExprResult(Expr *)> Filter) {
3107 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3110 void diagnoseTypo(const TypoCorrection &Correction,
3111 const PartialDiagnostic &TypoDiag,
3112 bool ErrorRecovery = true);
3114 void diagnoseTypo(const TypoCorrection &Correction,
3115 const PartialDiagnostic &TypoDiag,
3116 const PartialDiagnostic &PrevNote,
3117 bool ErrorRecovery = true);
3119 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3120 ArrayRef<Expr *> Args,
3121 AssociatedNamespaceSet &AssociatedNamespaces,
3122 AssociatedClassSet &AssociatedClasses);
3124 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3125 bool ConsiderLinkage, bool AllowInlineNamespace);
3127 void DiagnoseAmbiguousLookup(LookupResult &Result);
3130 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3131 SourceLocation IdLoc,
3132 bool TypoCorrection = false);
3133 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3134 Scope *S, bool ForRedeclaration,
3135 SourceLocation Loc);
3136 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3138 void AddKnownFunctionAttributes(FunctionDecl *FD);
3140 // More parsing and symbol table subroutines.
3142 void ProcessPragmaWeak(Scope *S, Decl *D);
3143 // Decl attributes - this routine is the top level dispatcher.
3144 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3145 // Helper for delayed proccessing of attributes.
3146 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3147 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3148 bool IncludeCXX11Attributes = true);
3149 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3150 const AttributeList *AttrList);
3152 void checkUnusedDeclAttributes(Declarator &D);
3154 /// Determine if type T is a valid subject for a nonnull and similar
3155 /// attributes. By default, we look through references (the behavior used by
3156 /// nonnull), but if the second parameter is true, then we treat a reference
3158 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3160 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3161 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3162 const FunctionDecl *FD = nullptr);
3163 bool CheckNoReturnAttr(const AttributeList &attr);
3164 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3165 unsigned ArgNum, StringRef &Str,
3166 SourceLocation *ArgLocation = nullptr);
3167 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3168 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3169 bool checkMSInheritanceAttrOnDefinition(
3170 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3171 MSInheritanceAttr::Spelling SemanticSpelling);
3173 void CheckAlignasUnderalignment(Decl *D);
3175 /// Adjust the calling convention of a method to be the ABI default if it
3176 /// wasn't specified explicitly. This handles method types formed from
3177 /// function type typedefs and typename template arguments.
3178 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3179 SourceLocation Loc);
3181 // Check if there is an explicit attribute, but only look through parens.
3182 // The intent is to look for an attribute on the current declarator, but not
3183 // one that came from a typedef.
3184 bool hasExplicitCallingConv(QualType &T);
3186 /// Get the outermost AttributedType node that sets a calling convention.
3187 /// Valid types should not have multiple attributes with different CCs.
3188 const AttributedType *getCallingConvAttributedType(QualType T) const;
3190 /// Check whether a nullability type specifier can be added to the given
3193 /// \param type The type to which the nullability specifier will be
3194 /// added. On success, this type will be updated appropriately.
3196 /// \param nullability The nullability specifier to add.
3198 /// \param nullabilityLoc The location of the nullability specifier.
3200 /// \param isContextSensitive Whether this nullability specifier was
3201 /// written as a context-sensitive keyword (in an Objective-C
3202 /// method) or an Objective-C property attribute, rather than as an
3203 /// underscored type specifier.
3205 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3206 /// array type (e.g., because it will decay to a pointer).
3208 /// \returns true if nullability cannot be applied, false otherwise.
3209 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3210 SourceLocation nullabilityLoc,
3211 bool isContextSensitive,
3212 bool allowArrayTypes);
3214 /// \brief Stmt attributes - this routine is the top level dispatcher.
3215 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3218 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3219 ObjCMethodDecl *MethodDecl,
3220 bool IsProtocolMethodDecl);
3222 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3223 ObjCMethodDecl *Overridden,
3224 bool IsProtocolMethodDecl);
3226 /// WarnExactTypedMethods - This routine issues a warning if method
3227 /// implementation declaration matches exactly that of its declaration.
3228 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3229 ObjCMethodDecl *MethodDecl,
3230 bool IsProtocolMethodDecl);
3232 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3234 /// CheckImplementationIvars - This routine checks if the instance variables
3235 /// listed in the implelementation match those listed in the interface.
3236 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3237 ObjCIvarDecl **Fields, unsigned nIvars,
3238 SourceLocation Loc);
3240 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3241 /// remains unimplemented in the class or category \@implementation.
3242 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3243 ObjCContainerDecl* IDecl,
3244 bool IncompleteImpl = false);
3246 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3247 /// which must be implemented by this implementation.
3248 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3249 ObjCContainerDecl *CDecl,
3250 bool SynthesizeProperties);
3252 /// Diagnose any null-resettable synthesized setters.
3253 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3255 /// DefaultSynthesizeProperties - This routine default synthesizes all
3256 /// properties which must be synthesized in the class's \@implementation.
3257 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3258 ObjCInterfaceDecl *IDecl);
3259 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3261 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3262 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3263 /// declared in class 'IFace'.
3264 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3265 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3267 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3268 /// backs the property is not used in the property's accessor.
3269 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3270 const ObjCImplementationDecl *ImplD);
3272 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3273 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3274 /// It also returns ivar's property on success.
3275 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3276 const ObjCPropertyDecl *&PDecl) const;
3278 /// Called by ActOnProperty to handle \@property declarations in
3279 /// class extensions.
3280 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3281 SourceLocation AtLoc,
3282 SourceLocation LParenLoc,
3283 FieldDeclarator &FD,
3285 SourceLocation GetterNameLoc,
3287 SourceLocation SetterNameLoc,
3288 const bool isReadWrite,
3289 unsigned &Attributes,
3290 const unsigned AttributesAsWritten,
3292 TypeSourceInfo *TSI,
3293 tok::ObjCKeywordKind MethodImplKind);
3295 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3296 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3297 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3298 ObjCContainerDecl *CDecl,
3299 SourceLocation AtLoc,
3300 SourceLocation LParenLoc,
3301 FieldDeclarator &FD,
3303 SourceLocation GetterNameLoc,
3305 SourceLocation SetterNameLoc,
3306 const bool isReadWrite,
3307 const unsigned Attributes,
3308 const unsigned AttributesAsWritten,
3310 TypeSourceInfo *TSI,
3311 tok::ObjCKeywordKind MethodImplKind,
3312 DeclContext *lexicalDC = nullptr);
3314 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3315 /// warning) when atomic property has one but not the other user-declared
3316 /// setter or getter.
3317 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3318 ObjCInterfaceDecl* IDecl);
3320 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3322 void DiagnoseMissingDesignatedInitOverrides(
3323 const ObjCImplementationDecl *ImplD,
3324 const ObjCInterfaceDecl *IFD);
3326 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3328 enum MethodMatchStrategy {
3333 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3334 /// true, or false, accordingly.
3335 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3336 const ObjCMethodDecl *PrevMethod,
3337 MethodMatchStrategy strategy = MMS_strict);
3339 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3340 /// or protocol against those declared in their implementations.
3341 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3342 const SelectorSet &ClsMap,
3343 SelectorSet &InsMapSeen,
3344 SelectorSet &ClsMapSeen,
3345 ObjCImplDecl* IMPDecl,
3346 ObjCContainerDecl* IDecl,
3347 bool &IncompleteImpl,
3348 bool ImmediateClass,
3349 bool WarnCategoryMethodImpl=false);
3351 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3352 /// category matches with those implemented in its primary class and
3353 /// warns each time an exact match is found.
3354 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3356 /// \brief Add the given method to the list of globally-known methods.
3357 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3360 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3361 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3362 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3364 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3365 /// optionally warns if there are multiple signatures.
3366 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3367 bool receiverIdOrClass,
3371 /// \brief - Returns instance or factory methods in global method pool for
3372 /// given selector. It checks the desired kind first, if none is found, and
3373 /// parameter checkTheOther is set, it then checks the other kind. If no such
3374 /// method or only one method is found, function returns false; otherwise, it
3377 CollectMultipleMethodsInGlobalPool(Selector Sel,
3378 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3379 bool InstanceFirst, bool CheckTheOther,
3380 const ObjCObjectType *TypeBound = nullptr);
3383 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3384 SourceRange R, bool receiverIdOrClass,
3385 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3388 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3389 Selector Sel, SourceRange R,
3390 bool receiverIdOrClass);
3393 /// \brief - Returns a selector which best matches given argument list or
3394 /// nullptr if none could be found
3395 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3397 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3400 /// \brief Record the typo correction failure and return an empty correction.
3401 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3402 bool RecordFailure = true) {
3404 TypoCorrectionFailures[Typo].insert(TypoLoc);
3405 return TypoCorrection();
3409 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3410 /// unit are added to a global pool. This allows us to efficiently associate
3411 /// a selector with a method declaraation for purposes of typechecking
3412 /// messages sent to "id" (where the class of the object is unknown).
3413 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3414 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3417 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3418 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3419 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3422 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3424 void AddAnyMethodToGlobalPool(Decl *D);
3426 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3427 /// there are multiple signatures.
3428 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3429 bool receiverIdOrClass=false) {
3430 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3434 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3435 /// there are multiple signatures.
3436 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3437 bool receiverIdOrClass=false) {
3438 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3442 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3443 QualType ObjectType=QualType());
3444 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3446 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3448 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3450 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3451 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3453 //===--------------------------------------------------------------------===//
3454 // Statement Parsing Callbacks: SemaStmt.cpp.
3458 FullExprArg() : E(nullptr) { }
3459 FullExprArg(Sema &actions) : E(nullptr) { }
3461 ExprResult release() {
3465 Expr *get() const { return E; }
3467 Expr *operator->() {
3472 // FIXME: No need to make the entire Sema class a friend when it's just
3473 // Sema::MakeFullExpr that needs access to the constructor below.
3476 explicit FullExprArg(Expr *expr) : E(expr) {}
3481 FullExprArg MakeFullExpr(Expr *Arg) {
3482 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3484 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3485 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3487 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3489 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3490 /*DiscardedValue*/ true);
3491 return FullExprArg(FE.get());
3494 StmtResult ActOnExprStmt(ExprResult Arg);
3495 StmtResult ActOnExprStmtError();
3497 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3498 bool HasLeadingEmptyMacro = false);
3500 void ActOnStartOfCompoundStmt();
3501 void ActOnFinishOfCompoundStmt();
3502 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3503 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3505 /// \brief A RAII object to enter scope of a compound statement.
3506 class CompoundScopeRAII {
3508 CompoundScopeRAII(Sema &S): S(S) {
3509 S.ActOnStartOfCompoundStmt();
3512 ~CompoundScopeRAII() {
3513 S.ActOnFinishOfCompoundStmt();
3520 /// An RAII helper that pops function a function scope on exit.
3521 struct FunctionScopeRAII {
3524 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3525 ~FunctionScopeRAII() {
3527 S.PopFunctionScopeInfo();
3529 void disable() { Active = false; }
3532 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3533 SourceLocation StartLoc,
3534 SourceLocation EndLoc);
3535 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3536 StmtResult ActOnForEachLValueExpr(Expr *E);
3537 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3538 SourceLocation DotDotDotLoc, Expr *RHSVal,
3539 SourceLocation ColonLoc);
3540 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3542 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3543 SourceLocation ColonLoc,
3544 Stmt *SubStmt, Scope *CurScope);
3545 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3546 SourceLocation ColonLoc, Stmt *SubStmt);
3548 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3549 ArrayRef<const Attr*> Attrs,
3552 class ConditionResult;
3553 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3555 ConditionResult Cond, Stmt *ThenVal,
3556 SourceLocation ElseLoc, Stmt *ElseVal);
3557 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3559 ConditionResult Cond, Stmt *ThenVal,
3560 SourceLocation ElseLoc, Stmt *ElseVal);
3561 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3563 ConditionResult Cond);
3564 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3565 Stmt *Switch, Stmt *Body);
3566 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3568 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3569 SourceLocation WhileLoc, SourceLocation CondLParen,
3570 Expr *Cond, SourceLocation CondRParen);
3572 StmtResult ActOnForStmt(SourceLocation ForLoc,
3573 SourceLocation LParenLoc,
3575 ConditionResult Second,
3577 SourceLocation RParenLoc,
3579 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3581 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3582 Stmt *First, Expr *collection,
3583 SourceLocation RParenLoc);
3584 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3586 enum BuildForRangeKind {
3587 /// Initial building of a for-range statement.
3589 /// Instantiation or recovery rebuild of a for-range statement. Don't
3590 /// attempt any typo-correction.
3592 /// Determining whether a for-range statement could be built. Avoid any
3593 /// unnecessary or irreversible actions.
3597 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3598 SourceLocation CoawaitLoc,
3600 SourceLocation ColonLoc, Expr *Collection,
3601 SourceLocation RParenLoc,
3602 BuildForRangeKind Kind);
3603 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3604 SourceLocation CoawaitLoc,
3605 SourceLocation ColonLoc,
3606 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3607 Expr *Cond, Expr *Inc,
3609 SourceLocation RParenLoc,
3610 BuildForRangeKind Kind);
3611 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3613 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3614 SourceLocation LabelLoc,
3615 LabelDecl *TheDecl);
3616 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3617 SourceLocation StarLoc,
3619 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3620 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3622 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3623 CapturedRegionKind Kind, unsigned NumParams);
3624 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3625 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3626 CapturedRegionKind Kind,
3627 ArrayRef<CapturedParamNameType> Params);
3628 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3629 void ActOnCapturedRegionError();
3630 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3632 unsigned NumParams);
3633 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3634 bool AllowParamOrMoveConstructible);
3635 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3636 bool AllowParamOrMoveConstructible);
3638 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3640 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3641 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3643 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3644 bool IsVolatile, unsigned NumOutputs,
3645 unsigned NumInputs, IdentifierInfo **Names,
3646 MultiExprArg Constraints, MultiExprArg Exprs,
3647 Expr *AsmString, MultiExprArg Clobbers,
3648 SourceLocation RParenLoc);
3650 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3651 SourceLocation TemplateKWLoc,
3653 llvm::InlineAsmIdentifierInfo &Info,
3654 bool IsUnevaluatedContext);
3655 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3656 unsigned &Offset, SourceLocation AsmLoc);
3657 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3658 llvm::InlineAsmIdentifierInfo &Info,
3659 SourceLocation AsmLoc);
3660 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3661 ArrayRef<Token> AsmToks,
3662 StringRef AsmString,
3663 unsigned NumOutputs, unsigned NumInputs,
3664 ArrayRef<StringRef> Constraints,
3665 ArrayRef<StringRef> Clobbers,
3666 ArrayRef<Expr*> Exprs,
3667 SourceLocation EndLoc);
3668 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3669 SourceLocation Location,
3672 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3673 SourceLocation StartLoc,
3674 SourceLocation IdLoc, IdentifierInfo *Id,
3675 bool Invalid = false);
3677 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3679 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3680 Decl *Parm, Stmt *Body);
3682 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3684 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3685 MultiStmtArg Catch, Stmt *Finally);
3687 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3688 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3690 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3692 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3696 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3698 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3699 SourceLocation StartLoc,
3700 SourceLocation IdLoc,
3701 IdentifierInfo *Id);
3703 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3705 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3706 Decl *ExDecl, Stmt *HandlerBlock);
3707 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3708 ArrayRef<Stmt *> Handlers);
3710 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3711 SourceLocation TryLoc, Stmt *TryBlock,
3713 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3716 void ActOnStartSEHFinallyBlock();
3717 void ActOnAbortSEHFinallyBlock();
3718 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3719 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3721 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3723 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3725 /// \brief If it's a file scoped decl that must warn if not used, keep track
3727 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3729 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3730 /// whose result is unused, warn.
3731 void DiagnoseUnusedExprResult(const Stmt *S);
3732 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3733 void DiagnoseUnusedDecl(const NamedDecl *ND);
3735 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3736 /// statement as a \p Body, and it is located on the same line.
3738 /// This helps prevent bugs due to typos, such as:
3741 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3745 /// Warn if a for/while loop statement \p S, which is followed by
3746 /// \p PossibleBody, has a suspicious null statement as a body.
3747 void DiagnoseEmptyLoopBody(const Stmt *S,
3748 const Stmt *PossibleBody);
3750 /// Warn if a value is moved to itself.
3751 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3752 SourceLocation OpLoc);
3754 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3756 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3757 SourceLocation Loc);
3759 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3760 return DelayedDiagnostics.push(pool);
3762 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3764 typedef ProcessingContextState ParsingClassState;
3765 ParsingClassState PushParsingClass() {
3766 return DelayedDiagnostics.pushUndelayed();
3768 void PopParsingClass(ParsingClassState state) {
3769 DelayedDiagnostics.popUndelayed(state);
3772 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3774 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3775 StringRef Message, SourceLocation Loc,
3776 const ObjCInterfaceDecl *UnknownObjCClass,
3777 const ObjCPropertyDecl *ObjCProperty,
3778 bool ObjCPropertyAccess);
3780 bool makeUnavailableInSystemHeader(SourceLocation loc,
3781 UnavailableAttr::ImplicitReason reason);
3783 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3784 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3786 //===--------------------------------------------------------------------===//
3787 // Expression Parsing Callbacks: SemaExpr.cpp.
3789 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3790 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3791 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3792 bool ObjCPropertyAccess=false);
3793 void NoteDeletedFunction(FunctionDecl *FD);
3794 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3795 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3796 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3797 ObjCMethodDecl *Getter,
3798 SourceLocation Loc);
3799 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3800 ArrayRef<Expr *> Args);
3802 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3803 Decl *LambdaContextDecl = nullptr,
3804 bool IsDecltype = false);
3805 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3806 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3807 ReuseLambdaContextDecl_t,
3808 bool IsDecltype = false);
3809 void PopExpressionEvaluationContext();
3811 void DiscardCleanupsInEvaluationContext();
3813 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3814 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3816 ExprResult ActOnConstantExpression(ExprResult Res);
3818 // Functions for marking a declaration referenced. These functions also
3819 // contain the relevant logic for marking if a reference to a function or
3820 // variable is an odr-use (in the C++11 sense). There are separate variants
3821 // for expressions referring to a decl; these exist because odr-use marking
3822 // needs to be delayed for some constant variables when we build one of the
3823 // named expressions.
3825 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3826 // should usually be true. This only needs to be set to false if the lack of
3827 // odr-use cannot be determined from the current context (for instance,
3828 // because the name denotes a virtual function and was written without an
3829 // explicit nested-name-specifier).
3830 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3831 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3832 bool MightBeOdrUse = true);
3833 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3834 void MarkDeclRefReferenced(DeclRefExpr *E);
3835 void MarkMemberReferenced(MemberExpr *E);
3837 void UpdateMarkingForLValueToRValue(Expr *E);
3838 void CleanupVarDeclMarking();
3840 enum TryCaptureKind {
3841 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3844 /// \brief Try to capture the given variable.
3846 /// \param Var The variable to capture.
3848 /// \param Loc The location at which the capture occurs.
3850 /// \param Kind The kind of capture, which may be implicit (for either a
3851 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3853 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3854 /// an explicit lambda capture.
3856 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3857 /// captures or diagnose errors. If false, this routine merely check whether
3858 /// the capture can occur without performing the capture itself or complaining
3859 /// if the variable cannot be captured.
3861 /// \param CaptureType Will be set to the type of the field used to capture
3862 /// this variable in the innermost block or lambda. Only valid when the
3863 /// variable can be captured.
3865 /// \param DeclRefType Will be set to the type of a reference to the capture
3866 /// from within the current scope. Only valid when the variable can be
3869 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3870 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3871 /// This is useful when enclosing lambdas must speculatively capture
3872 /// variables that may or may not be used in certain specializations of
3873 /// a nested generic lambda.
3875 /// \returns true if an error occurred (i.e., the variable cannot be
3876 /// captured) and false if the capture succeeded.
3877 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3878 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3879 QualType &CaptureType,
3880 QualType &DeclRefType,
3881 const unsigned *const FunctionScopeIndexToStopAt);
3883 /// \brief Try to capture the given variable.
3884 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3885 TryCaptureKind Kind = TryCapture_Implicit,
3886 SourceLocation EllipsisLoc = SourceLocation());
3888 /// \brief Checks if the variable must be captured.
3889 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3891 /// \brief Given a variable, determine the type that a reference to that
3892 /// variable will have in the given scope.
3893 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3895 /// Mark all of the declarations referenced within a particular AST node as
3896 /// referenced. Used when template instantiation instantiates a non-dependent
3897 /// type -- entities referenced by the type are now referenced.
3898 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3899 void MarkDeclarationsReferencedInExpr(Expr *E,
3900 bool SkipLocalVariables = false);
3902 /// \brief Try to recover by turning the given expression into a
3903 /// call. Returns true if recovery was attempted or an error was
3904 /// emitted; this may also leave the ExprResult invalid.
3905 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3906 bool ForceComplain = false,
3907 bool (*IsPlausibleResult)(QualType) = nullptr);
3909 /// \brief Figure out if an expression could be turned into a call.
3910 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3911 UnresolvedSetImpl &NonTemplateOverloads);
3913 /// \brief Conditionally issue a diagnostic based on the current
3914 /// evaluation context.
3916 /// \param Statement If Statement is non-null, delay reporting the
3917 /// diagnostic until the function body is parsed, and then do a basic
3918 /// reachability analysis to determine if the statement is reachable.
3919 /// If it is unreachable, the diagnostic will not be emitted.
3920 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3921 const PartialDiagnostic &PD);
3923 // Primary Expressions.
3924 SourceRange getExprRange(Expr *E) const;
3926 ExprResult ActOnIdExpression(
3927 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3928 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3929 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3930 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3932 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3933 TemplateArgumentListInfo &Buffer,
3934 DeclarationNameInfo &NameInfo,
3935 const TemplateArgumentListInfo *&TemplateArgs);
3938 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3939 std::unique_ptr<CorrectionCandidateCallback> CCC,
3940 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3941 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3943 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3945 bool AllowBuiltinCreation=false);
3947 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3948 SourceLocation TemplateKWLoc,
3949 const DeclarationNameInfo &NameInfo,
3950 bool isAddressOfOperand,
3951 const TemplateArgumentListInfo *TemplateArgs);
3953 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3956 const CXXScopeSpec *SS = nullptr);
3958 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3959 const DeclarationNameInfo &NameInfo,
3960 const CXXScopeSpec *SS = nullptr,
3961 NamedDecl *FoundD = nullptr,
3962 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3964 BuildAnonymousStructUnionMemberReference(
3965 const CXXScopeSpec &SS,
3966 SourceLocation nameLoc,
3967 IndirectFieldDecl *indirectField,
3968 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3969 Expr *baseObjectExpr = nullptr,
3970 SourceLocation opLoc = SourceLocation());
3972 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3973 SourceLocation TemplateKWLoc,
3975 const TemplateArgumentListInfo *TemplateArgs,
3977 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3978 SourceLocation TemplateKWLoc,
3980 const TemplateArgumentListInfo *TemplateArgs,
3981 bool IsDefiniteInstance,
3983 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3984 const LookupResult &R,
3985 bool HasTrailingLParen);
3988 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3989 const DeclarationNameInfo &NameInfo,
3990 bool IsAddressOfOperand, const Scope *S,
3991 TypeSourceInfo **RecoveryTSI = nullptr);
3993 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3994 SourceLocation TemplateKWLoc,
3995 const DeclarationNameInfo &NameInfo,
3996 const TemplateArgumentListInfo *TemplateArgs);
3998 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4001 bool AcceptInvalidDecl = false);
4002 ExprResult BuildDeclarationNameExpr(
4003 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4004 NamedDecl *FoundD = nullptr,
4005 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4006 bool AcceptInvalidDecl = false);
4008 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4009 DeclarationNameInfo &SuffixInfo,
4010 ArrayRef<Expr *> Args,
4011 SourceLocation LitEndLoc,
4012 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4014 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4015 PredefinedExpr::IdentType IT);
4016 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4017 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4019 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4021 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4022 ExprResult ActOnCharacterConstant(const Token &Tok,
4023 Scope *UDLScope = nullptr);
4024 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4025 ExprResult ActOnParenListExpr(SourceLocation L,
4029 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4030 /// fragments (e.g. "foo" "bar" L"baz").
4031 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4032 Scope *UDLScope = nullptr);
4034 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4035 SourceLocation DefaultLoc,
4036 SourceLocation RParenLoc,
4037 Expr *ControllingExpr,
4038 ArrayRef<ParsedType> ArgTypes,
4039 ArrayRef<Expr *> ArgExprs);
4040 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4041 SourceLocation DefaultLoc,
4042 SourceLocation RParenLoc,
4043 Expr *ControllingExpr,
4044 ArrayRef<TypeSourceInfo *> Types,
4045 ArrayRef<Expr *> Exprs);
4047 // Binary/Unary Operators. 'Tok' is the token for the operator.
4048 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4050 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4051 UnaryOperatorKind Opc, Expr *Input);
4052 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4053 tok::TokenKind Op, Expr *Input);
4055 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4057 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4058 SourceLocation OpLoc,
4059 UnaryExprOrTypeTrait ExprKind,
4061 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4062 UnaryExprOrTypeTrait ExprKind);
4064 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4065 UnaryExprOrTypeTrait ExprKind,
4066 bool IsType, void *TyOrEx,
4067 SourceRange ArgRange);
4069 ExprResult CheckPlaceholderExpr(Expr *E);
4070 bool CheckVecStepExpr(Expr *E);
4072 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4073 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4074 SourceRange ExprRange,
4075 UnaryExprOrTypeTrait ExprKind);
4076 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4077 SourceLocation OpLoc,
4078 IdentifierInfo &Name,
4079 SourceLocation NameLoc,
4080 SourceLocation RParenLoc);
4081 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4082 tok::TokenKind Kind, Expr *Input);
4084 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4085 Expr *Idx, SourceLocation RLoc);
4086 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4087 Expr *Idx, SourceLocation RLoc);
4088 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4089 Expr *LowerBound, SourceLocation ColonLoc,
4090 Expr *Length, SourceLocation RBLoc);
4092 // This struct is for use by ActOnMemberAccess to allow
4093 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4094 // changing the access operator from a '.' to a '->' (to see if that is the
4095 // change needed to fix an error about an unknown member, e.g. when the class
4096 // defines a custom operator->).
4097 struct ActOnMemberAccessExtraArgs {
4103 ExprResult BuildMemberReferenceExpr(
4104 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4105 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4106 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4107 const TemplateArgumentListInfo *TemplateArgs,
4109 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4112 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4113 bool IsArrow, const CXXScopeSpec &SS,
4114 SourceLocation TemplateKWLoc,
4115 NamedDecl *FirstQualifierInScope, LookupResult &R,
4116 const TemplateArgumentListInfo *TemplateArgs,
4118 bool SuppressQualifierCheck = false,
4119 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4121 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4122 SourceLocation OpLoc,
4123 const CXXScopeSpec &SS, FieldDecl *Field,
4124 DeclAccessPair FoundDecl,
4125 const DeclarationNameInfo &MemberNameInfo);
4127 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4129 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4130 const CXXScopeSpec &SS,
4131 const LookupResult &R);
4133 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4134 bool IsArrow, SourceLocation OpLoc,
4135 const CXXScopeSpec &SS,
4136 SourceLocation TemplateKWLoc,
4137 NamedDecl *FirstQualifierInScope,
4138 const DeclarationNameInfo &NameInfo,
4139 const TemplateArgumentListInfo *TemplateArgs);
4141 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4142 SourceLocation OpLoc,
4143 tok::TokenKind OpKind,
4145 SourceLocation TemplateKWLoc,
4146 UnqualifiedId &Member,
4149 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4150 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4151 FunctionDecl *FDecl,
4152 const FunctionProtoType *Proto,
4153 ArrayRef<Expr *> Args,
4154 SourceLocation RParenLoc,
4155 bool ExecConfig = false);
4156 void CheckStaticArrayArgument(SourceLocation CallLoc,
4158 const Expr *ArgExpr);
4160 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4161 /// This provides the location of the left/right parens and a list of comma
4163 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4164 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4165 Expr *ExecConfig = nullptr,
4166 bool IsExecConfig = false);
4167 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4168 SourceLocation LParenLoc,
4169 ArrayRef<Expr *> Arg,
4170 SourceLocation RParenLoc,
4171 Expr *Config = nullptr,
4172 bool IsExecConfig = false);
4174 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4175 MultiExprArg ExecConfig,
4176 SourceLocation GGGLoc);
4178 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4179 Declarator &D, ParsedType &Ty,
4180 SourceLocation RParenLoc, Expr *CastExpr);
4181 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4183 SourceLocation RParenLoc,
4185 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4187 /// \brief Build an altivec or OpenCL literal.
4188 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4189 SourceLocation RParenLoc, Expr *E,
4190 TypeSourceInfo *TInfo);
4192 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4194 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4196 SourceLocation RParenLoc,
4199 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4200 TypeSourceInfo *TInfo,
4201 SourceLocation RParenLoc,
4204 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4205 MultiExprArg InitArgList,
4206 SourceLocation RBraceLoc);
4208 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4214 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4217 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4218 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4219 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4220 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4221 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4222 Expr *LHSExpr, Expr *RHSExpr);
4224 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4226 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4227 /// in the case of a the GNU conditional expr extension.
4228 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4229 SourceLocation ColonLoc,
4230 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4232 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4233 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4234 LabelDecl *TheDecl);
4236 void ActOnStartStmtExpr();
4237 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4238 SourceLocation RPLoc); // "({..})"
4239 void ActOnStmtExprError();
4241 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4242 struct OffsetOfComponent {
4243 SourceLocation LocStart, LocEnd;
4244 bool isBrackets; // true if [expr], false if .ident
4246 IdentifierInfo *IdentInfo;
4251 /// __builtin_offsetof(type, a.b[123][456].c)
4252 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4253 TypeSourceInfo *TInfo,
4254 ArrayRef<OffsetOfComponent> Components,
4255 SourceLocation RParenLoc);
4256 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4257 SourceLocation BuiltinLoc,
4258 SourceLocation TypeLoc,
4259 ParsedType ParsedArgTy,
4260 ArrayRef<OffsetOfComponent> Components,
4261 SourceLocation RParenLoc);
4263 // __builtin_choose_expr(constExpr, expr1, expr2)
4264 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4265 Expr *CondExpr, Expr *LHSExpr,
4266 Expr *RHSExpr, SourceLocation RPLoc);
4268 // __builtin_va_arg(expr, type)
4269 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4270 SourceLocation RPLoc);
4271 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4272 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4275 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4277 bool CheckCaseExpression(Expr *E);
4279 /// \brief Describes the result of an "if-exists" condition check.
4280 enum IfExistsResult {
4281 /// \brief The symbol exists.
4284 /// \brief The symbol does not exist.
4287 /// \brief The name is a dependent name, so the results will differ
4288 /// from one instantiation to the next.
4291 /// \brief An error occurred.
4296 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4297 const DeclarationNameInfo &TargetNameInfo);
4300 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4301 bool IsIfExists, CXXScopeSpec &SS,
4302 UnqualifiedId &Name);
4304 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4306 NestedNameSpecifierLoc QualifierLoc,
4307 DeclarationNameInfo NameInfo,
4309 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4311 CXXScopeSpec &SS, UnqualifiedId &Name,
4314 //===------------------------- "Block" Extension ------------------------===//
4316 /// ActOnBlockStart - This callback is invoked when a block literal is
4318 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4320 /// ActOnBlockArguments - This callback allows processing of block arguments.
4321 /// If there are no arguments, this is still invoked.
4322 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4325 /// ActOnBlockError - If there is an error parsing a block, this callback
4326 /// is invoked to pop the information about the block from the action impl.
4327 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4329 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4330 /// literal was successfully completed. ^(int x){...}
4331 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4334 //===---------------------------- Clang Extensions ----------------------===//
4336 /// __builtin_convertvector(...)
4337 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4338 SourceLocation BuiltinLoc,
4339 SourceLocation RParenLoc);
4341 //===---------------------------- OpenCL Features -----------------------===//
4343 /// __builtin_astype(...)
4344 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4345 SourceLocation BuiltinLoc,
4346 SourceLocation RParenLoc);
4348 //===---------------------------- C++ Features --------------------------===//
4350 // Act on C++ namespaces
4351 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4352 SourceLocation NamespaceLoc,
4353 SourceLocation IdentLoc,
4354 IdentifierInfo *Ident,
4355 SourceLocation LBrace,
4356 AttributeList *AttrList,
4357 UsingDirectiveDecl * &UsingDecl);
4358 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4360 NamespaceDecl *getStdNamespace() const;
4361 NamespaceDecl *getOrCreateStdNamespace();
4363 NamespaceDecl *lookupStdExperimentalNamespace();
4365 CXXRecordDecl *getStdBadAlloc() const;
4366 EnumDecl *getStdAlignValT() const;
4368 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4369 /// it is and Element is not NULL, assigns the element type to Element.
4370 bool isStdInitializerList(QualType Ty, QualType *Element);
4372 /// \brief Looks for the std::initializer_list template and instantiates it
4373 /// with Element, or emits an error if it's not found.
4375 /// \returns The instantiated template, or null on error.
4376 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4378 /// \brief Determine whether Ctor is an initializer-list constructor, as
4379 /// defined in [dcl.init.list]p2.
4380 bool isInitListConstructor(const FunctionDecl *Ctor);
4382 Decl *ActOnUsingDirective(Scope *CurScope,
4383 SourceLocation UsingLoc,
4384 SourceLocation NamespcLoc,
4386 SourceLocation IdentLoc,
4387 IdentifierInfo *NamespcName,
4388 AttributeList *AttrList);
4390 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4392 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4393 SourceLocation NamespaceLoc,
4394 SourceLocation AliasLoc,
4395 IdentifierInfo *Alias,
4397 SourceLocation IdentLoc,
4398 IdentifierInfo *Ident);
4400 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4401 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4402 const LookupResult &PreviousDecls,
4403 UsingShadowDecl *&PrevShadow);
4404 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4406 UsingShadowDecl *PrevDecl);
4408 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4409 bool HasTypenameKeyword,
4410 const CXXScopeSpec &SS,
4411 SourceLocation NameLoc,
4412 const LookupResult &Previous);
4413 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4415 const CXXScopeSpec &SS,
4416 const DeclarationNameInfo &NameInfo,
4417 SourceLocation NameLoc);
4419 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4420 SourceLocation UsingLoc,
4421 bool HasTypenameKeyword,
4422 SourceLocation TypenameLoc,
4424 DeclarationNameInfo NameInfo,
4425 SourceLocation EllipsisLoc,
4426 AttributeList *AttrList,
4427 bool IsInstantiation);
4428 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4429 ArrayRef<NamedDecl *> Expansions);
4431 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4433 /// Given a derived-class using shadow declaration for a constructor and the
4434 /// correspnding base class constructor, find or create the implicit
4435 /// synthesized derived class constructor to use for this initialization.
4436 CXXConstructorDecl *
4437 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4438 ConstructorUsingShadowDecl *DerivedShadow);
4440 Decl *ActOnUsingDeclaration(Scope *CurScope,
4442 SourceLocation UsingLoc,
4443 SourceLocation TypenameLoc,
4445 UnqualifiedId &Name,
4446 SourceLocation EllipsisLoc,
4447 AttributeList *AttrList);
4448 Decl *ActOnAliasDeclaration(Scope *CurScope,
4450 MultiTemplateParamsArg TemplateParams,
4451 SourceLocation UsingLoc,
4452 UnqualifiedId &Name,
4453 AttributeList *AttrList,
4455 Decl *DeclFromDeclSpec);
4457 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4458 /// including handling of its default argument expressions.
4460 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4462 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4463 NamedDecl *FoundDecl,
4464 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4465 bool HadMultipleCandidates, bool IsListInitialization,
4466 bool IsStdInitListInitialization,
4467 bool RequiresZeroInit, unsigned ConstructKind,
4468 SourceRange ParenRange);
4470 /// Build a CXXConstructExpr whose constructor has already been resolved if
4471 /// it denotes an inherited constructor.
4473 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4474 CXXConstructorDecl *Constructor, bool Elidable,
4476 bool HadMultipleCandidates, bool IsListInitialization,
4477 bool IsStdInitListInitialization,
4478 bool RequiresZeroInit, unsigned ConstructKind,
4479 SourceRange ParenRange);
4481 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4482 // the constructor can be elidable?
4484 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4485 NamedDecl *FoundDecl,
4486 CXXConstructorDecl *Constructor, bool Elidable,
4487 MultiExprArg Exprs, bool HadMultipleCandidates,
4488 bool IsListInitialization,
4489 bool IsStdInitListInitialization, bool RequiresZeroInit,
4490 unsigned ConstructKind, SourceRange ParenRange);
4492 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4495 /// Instantiate or parse a C++ default argument expression as necessary.
4496 /// Return true on error.
4497 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4498 ParmVarDecl *Param);
4500 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4501 /// the default expr if needed.
4502 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4504 ParmVarDecl *Param);
4506 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4507 /// constructed variable.
4508 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4510 /// \brief Helper class that collects exception specifications for
4511 /// implicitly-declared special member functions.
4512 class ImplicitExceptionSpecification {
4513 // Pointer to allow copying
4515 // We order exception specifications thus:
4516 // noexcept is the most restrictive, but is only used in C++11.
4517 // throw() comes next.
4518 // Then a throw(collected exceptions)
4519 // Finally no specification, which is expressed as noexcept(false).
4520 // throw(...) is used instead if any called function uses it.
4521 ExceptionSpecificationType ComputedEST;
4522 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4523 SmallVector<QualType, 4> Exceptions;
4525 void ClearExceptions() {
4526 ExceptionsSeen.clear();
4531 explicit ImplicitExceptionSpecification(Sema &Self)
4532 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4533 if (!Self.getLangOpts().CPlusPlus11)
4534 ComputedEST = EST_DynamicNone;
4537 /// \brief Get the computed exception specification type.
4538 ExceptionSpecificationType getExceptionSpecType() const {
4539 assert(ComputedEST != EST_ComputedNoexcept &&
4540 "noexcept(expr) should not be a possible result");
4544 /// \brief The number of exceptions in the exception specification.
4545 unsigned size() const { return Exceptions.size(); }
4547 /// \brief The set of exceptions in the exception specification.
4548 const QualType *data() const { return Exceptions.data(); }
4550 /// \brief Integrate another called method into the collected data.
4551 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4553 /// \brief Integrate an invoked expression into the collected data.
4554 void CalledExpr(Expr *E);
4556 /// \brief Overwrite an EPI's exception specification with this
4557 /// computed exception specification.
4558 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4559 FunctionProtoType::ExceptionSpecInfo ESI;
4560 ESI.Type = getExceptionSpecType();
4561 if (ESI.Type == EST_Dynamic) {
4562 ESI.Exceptions = Exceptions;
4563 } else if (ESI.Type == EST_None) {
4564 /// C++11 [except.spec]p14:
4565 /// The exception-specification is noexcept(false) if the set of
4566 /// potential exceptions of the special member function contains "any"
4567 ESI.Type = EST_ComputedNoexcept;
4568 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4569 tok::kw_false).get();
4575 /// \brief Determine what sort of exception specification a defaulted
4576 /// copy constructor of a class will have.
4577 ImplicitExceptionSpecification
4578 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4581 /// \brief Determine what sort of exception specification a defaulted
4582 /// default constructor of a class will have, and whether the parameter
4584 ImplicitExceptionSpecification
4585 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4587 /// \brief Determine what sort of exception specification a defautled
4588 /// copy assignment operator of a class will have, and whether the
4589 /// parameter will be const.
4590 ImplicitExceptionSpecification
4591 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4593 /// \brief Determine what sort of exception specification a defaulted move
4594 /// constructor of a class will have.
4595 ImplicitExceptionSpecification
4596 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4598 /// \brief Determine what sort of exception specification a defaulted move
4599 /// assignment operator of a class will have.
4600 ImplicitExceptionSpecification
4601 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4603 /// \brief Determine what sort of exception specification a defaulted
4604 /// destructor of a class will have.
4605 ImplicitExceptionSpecification
4606 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4608 /// \brief Determine what sort of exception specification an inheriting
4609 /// constructor of a class will have.
4610 ImplicitExceptionSpecification
4611 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4612 CXXConstructorDecl *CD);
4614 /// \brief Evaluate the implicit exception specification for a defaulted
4615 /// special member function.
4616 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4618 /// \brief Check the given exception-specification and update the
4619 /// exception specification information with the results.
4620 void checkExceptionSpecification(bool IsTopLevel,
4621 ExceptionSpecificationType EST,
4622 ArrayRef<ParsedType> DynamicExceptions,
4623 ArrayRef<SourceRange> DynamicExceptionRanges,
4625 SmallVectorImpl<QualType> &Exceptions,
4626 FunctionProtoType::ExceptionSpecInfo &ESI);
4628 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4629 /// parse an exception specification to work around a libstdc++ bug.
4630 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4632 /// \brief Add an exception-specification to the given member function
4633 /// (or member function template). The exception-specification was parsed
4634 /// after the method itself was declared.
4635 void actOnDelayedExceptionSpecification(Decl *Method,
4636 ExceptionSpecificationType EST,
4637 SourceRange SpecificationRange,
4638 ArrayRef<ParsedType> DynamicExceptions,
4639 ArrayRef<SourceRange> DynamicExceptionRanges,
4640 Expr *NoexceptExpr);
4642 class InheritedConstructorInfo;
4644 /// \brief Determine if a special member function should have a deleted
4645 /// definition when it is defaulted.
4646 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4647 InheritedConstructorInfo *ICI = nullptr,
4648 bool Diagnose = false);
4650 /// \brief Declare the implicit default constructor for the given class.
4652 /// \param ClassDecl The class declaration into which the implicit
4653 /// default constructor will be added.
4655 /// \returns The implicitly-declared default constructor.
4656 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4657 CXXRecordDecl *ClassDecl);
4659 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4660 /// defining this constructor as the default constructor.
4661 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4662 CXXConstructorDecl *Constructor);
4664 /// \brief Declare the implicit destructor for the given class.
4666 /// \param ClassDecl The class declaration into which the implicit
4667 /// destructor will be added.
4669 /// \returns The implicitly-declared destructor.
4670 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4672 /// DefineImplicitDestructor - Checks for feasibility of
4673 /// defining this destructor as the default destructor.
4674 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4675 CXXDestructorDecl *Destructor);
4677 /// \brief Build an exception spec for destructors that don't have one.
4679 /// C++11 says that user-defined destructors with no exception spec get one
4680 /// that looks as if the destructor was implicitly declared.
4681 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4682 CXXDestructorDecl *Destructor);
4684 /// \brief Define the specified inheriting constructor.
4685 void DefineInheritingConstructor(SourceLocation UseLoc,
4686 CXXConstructorDecl *Constructor);
4688 /// \brief Declare the implicit copy constructor for the given class.
4690 /// \param ClassDecl The class declaration into which the implicit
4691 /// copy constructor will be added.
4693 /// \returns The implicitly-declared copy constructor.
4694 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4696 /// DefineImplicitCopyConstructor - Checks for feasibility of
4697 /// defining this constructor as the copy constructor.
4698 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4699 CXXConstructorDecl *Constructor);
4701 /// \brief Declare the implicit move constructor for the given class.
4703 /// \param ClassDecl The Class declaration into which the implicit
4704 /// move constructor will be added.
4706 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4708 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4710 /// DefineImplicitMoveConstructor - Checks for feasibility of
4711 /// defining this constructor as the move constructor.
4712 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4713 CXXConstructorDecl *Constructor);
4715 /// \brief Declare the implicit copy assignment operator for the given class.
4717 /// \param ClassDecl The class declaration into which the implicit
4718 /// copy assignment operator will be added.
4720 /// \returns The implicitly-declared copy assignment operator.
4721 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4723 /// \brief Defines an implicitly-declared copy assignment operator.
4724 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4725 CXXMethodDecl *MethodDecl);
4727 /// \brief Declare the implicit move assignment operator for the given class.
4729 /// \param ClassDecl The Class declaration into which the implicit
4730 /// move assignment operator will be added.
4732 /// \returns The implicitly-declared move assignment operator, or NULL if it
4733 /// wasn't declared.
4734 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4736 /// \brief Defines an implicitly-declared move assignment operator.
4737 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4738 CXXMethodDecl *MethodDecl);
4740 /// \brief Force the declaration of any implicitly-declared members of this
4742 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4744 /// \brief Check a completed declaration of an implicit special member.
4745 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4747 /// \brief Determine whether the given function is an implicitly-deleted
4748 /// special member function.
4749 bool isImplicitlyDeleted(FunctionDecl *FD);
4751 /// \brief Check whether 'this' shows up in the type of a static member
4752 /// function after the (naturally empty) cv-qualifier-seq would be.
4754 /// \returns true if an error occurred.
4755 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4757 /// \brief Whether this' shows up in the exception specification of a static
4758 /// member function.
4759 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4761 /// \brief Check whether 'this' shows up in the attributes of the given
4762 /// static member function.
4764 /// \returns true if an error occurred.
4765 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4767 /// MaybeBindToTemporary - If the passed in expression has a record type with
4768 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4769 /// it simply returns the passed in expression.
4770 ExprResult MaybeBindToTemporary(Expr *E);
4772 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4773 MultiExprArg ArgsPtr,
4775 SmallVectorImpl<Expr*> &ConvertedArgs,
4776 bool AllowExplicit = false,
4777 bool IsListInitialization = false);
4779 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4780 SourceLocation NameLoc,
4781 IdentifierInfo &Name);
4783 ParsedType getDestructorName(SourceLocation TildeLoc,
4784 IdentifierInfo &II, SourceLocation NameLoc,
4785 Scope *S, CXXScopeSpec &SS,
4786 ParsedType ObjectType,
4787 bool EnteringContext);
4789 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4790 ParsedType ObjectType);
4792 // Checks that reinterpret casts don't have undefined behavior.
4793 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4794 bool IsDereference, SourceRange Range);
4796 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4797 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4798 tok::TokenKind Kind,
4799 SourceLocation LAngleBracketLoc,
4801 SourceLocation RAngleBracketLoc,
4802 SourceLocation LParenLoc,
4804 SourceLocation RParenLoc);
4806 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4807 tok::TokenKind Kind,
4810 SourceRange AngleBrackets,
4811 SourceRange Parens);
4813 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4814 SourceLocation TypeidLoc,
4815 TypeSourceInfo *Operand,
4816 SourceLocation RParenLoc);
4817 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4818 SourceLocation TypeidLoc,
4820 SourceLocation RParenLoc);
4822 /// ActOnCXXTypeid - Parse typeid( something ).
4823 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4824 SourceLocation LParenLoc, bool isType,
4826 SourceLocation RParenLoc);
4828 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4829 SourceLocation TypeidLoc,
4830 TypeSourceInfo *Operand,
4831 SourceLocation RParenLoc);
4832 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4833 SourceLocation TypeidLoc,
4835 SourceLocation RParenLoc);
4837 /// ActOnCXXUuidof - Parse __uuidof( something ).
4838 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4839 SourceLocation LParenLoc, bool isType,
4841 SourceLocation RParenLoc);
4843 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4844 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4845 tok::TokenKind Operator,
4846 SourceLocation EllipsisLoc, Expr *RHS,
4847 SourceLocation RParenLoc);
4848 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4849 BinaryOperatorKind Operator,
4850 SourceLocation EllipsisLoc, Expr *RHS,
4851 SourceLocation RParenLoc);
4852 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4853 BinaryOperatorKind Operator);
4855 //// ActOnCXXThis - Parse 'this' pointer.
4856 ExprResult ActOnCXXThis(SourceLocation loc);
4858 /// \brief Try to retrieve the type of the 'this' pointer.
4860 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4861 QualType getCurrentThisType();
4863 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4864 /// current context not being a non-static member function. In such cases,
4865 /// this provides the type used for 'this'.
4866 QualType CXXThisTypeOverride;
4868 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4869 /// to be used, with the given qualifiers on the current class type.
4870 class CXXThisScopeRAII {
4872 QualType OldCXXThisTypeOverride;
4876 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4877 /// using the given declaration (which is either a class template or a
4878 /// class) along with the given qualifiers.
4879 /// along with the qualifiers placed on '*this'.
4880 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4881 bool Enabled = true);
4883 ~CXXThisScopeRAII();
4886 /// \brief Make sure the value of 'this' is actually available in the current
4887 /// context, if it is a potentially evaluated context.
4889 /// \param Loc The location at which the capture of 'this' occurs.
4891 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4894 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4895 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4896 /// This is useful when enclosing lambdas must speculatively capture
4897 /// 'this' that may or may not be used in certain specializations of
4898 /// a nested generic lambda (depending on whether the name resolves to
4899 /// a non-static member function or a static function).
4900 /// \return returns 'true' if failed, 'false' if success.
4901 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4902 bool BuildAndDiagnose = true,
4903 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4904 bool ByCopy = false);
4906 /// \brief Determine whether the given type is the type of *this that is used
4907 /// outside of the body of a member function for a type that is currently
4909 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4911 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4912 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4915 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4916 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4919 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4920 SourceLocation AtLoc, SourceLocation RParen);
4922 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4923 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4925 //// ActOnCXXThrow - Parse throw expressions.
4926 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4927 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4928 bool IsThrownVarInScope);
4929 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4931 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4932 /// Can be interpreted either as function-style casting ("int(x)")
4933 /// or class type construction ("ClassType(x,y,z)")
4934 /// or creation of a value-initialized type ("int()").
4935 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4936 SourceLocation LParenLoc,
4938 SourceLocation RParenLoc);
4940 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4941 SourceLocation LParenLoc,
4943 SourceLocation RParenLoc);
4945 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4946 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4947 SourceLocation PlacementLParen,
4948 MultiExprArg PlacementArgs,
4949 SourceLocation PlacementRParen,
4950 SourceRange TypeIdParens, Declarator &D,
4952 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4953 SourceLocation PlacementLParen,
4954 MultiExprArg PlacementArgs,
4955 SourceLocation PlacementRParen,
4956 SourceRange TypeIdParens,
4958 TypeSourceInfo *AllocTypeInfo,
4960 SourceRange DirectInitRange,
4963 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4965 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4966 bool UseGlobal, QualType AllocType, bool IsArray,
4967 bool &PassAlignment, MultiExprArg PlaceArgs,
4968 FunctionDecl *&OperatorNew,
4969 FunctionDecl *&OperatorDelete);
4970 void DeclareGlobalNewDelete();
4971 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4972 ArrayRef<QualType> Params);
4974 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4975 DeclarationName Name, FunctionDecl* &Operator,
4976 bool Diagnose = true);
4977 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4978 bool CanProvideSize,
4980 DeclarationName Name);
4981 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
4984 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4985 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4986 bool UseGlobal, bool ArrayForm,
4988 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4989 bool IsDelete, bool CallCanBeVirtual,
4990 bool WarnOnNonAbstractTypes,
4991 SourceLocation DtorLoc);
4993 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4994 Expr *Operand, SourceLocation RParen);
4995 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4996 SourceLocation RParen);
4998 /// \brief Parsed one of the type trait support pseudo-functions.
4999 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5000 ArrayRef<ParsedType> Args,
5001 SourceLocation RParenLoc);
5002 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5003 ArrayRef<TypeSourceInfo *> Args,
5004 SourceLocation RParenLoc);
5006 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5007 /// pseudo-functions.
5008 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5009 SourceLocation KWLoc,
5012 SourceLocation RParen);
5014 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5015 SourceLocation KWLoc,
5016 TypeSourceInfo *TSInfo,
5018 SourceLocation RParen);
5020 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5021 /// pseudo-functions.
5022 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5023 SourceLocation KWLoc,
5025 SourceLocation RParen);
5027 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5028 SourceLocation KWLoc,
5030 SourceLocation RParen);
5032 ExprResult ActOnStartCXXMemberReference(Scope *S,
5034 SourceLocation OpLoc,
5035 tok::TokenKind OpKind,
5036 ParsedType &ObjectType,
5037 bool &MayBePseudoDestructor);
5039 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5040 SourceLocation OpLoc,
5041 tok::TokenKind OpKind,
5042 const CXXScopeSpec &SS,
5043 TypeSourceInfo *ScopeType,
5044 SourceLocation CCLoc,
5045 SourceLocation TildeLoc,
5046 PseudoDestructorTypeStorage DestroyedType);
5048 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5049 SourceLocation OpLoc,
5050 tok::TokenKind OpKind,
5052 UnqualifiedId &FirstTypeName,
5053 SourceLocation CCLoc,
5054 SourceLocation TildeLoc,
5055 UnqualifiedId &SecondTypeName);
5057 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5058 SourceLocation OpLoc,
5059 tok::TokenKind OpKind,
5060 SourceLocation TildeLoc,
5061 const DeclSpec& DS);
5063 /// MaybeCreateExprWithCleanups - If the current full-expression
5064 /// requires any cleanups, surround it with a ExprWithCleanups node.
5065 /// Otherwise, just returns the passed-in expression.
5066 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5067 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5068 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5070 MaterializeTemporaryExpr *
5071 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5072 bool BoundToLvalueReference);
5074 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5075 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5076 : SourceLocation());
5078 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5079 bool DiscardedValue = false,
5080 bool IsConstexpr = false,
5081 bool IsLambdaInitCaptureInitializer = false);
5082 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5084 // Marks SS invalid if it represents an incomplete type.
5085 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5087 DeclContext *computeDeclContext(QualType T);
5088 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5089 bool EnteringContext = false);
5090 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5091 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5093 /// \brief The parser has parsed a global nested-name-specifier '::'.
5095 /// \param CCLoc The location of the '::'.
5097 /// \param SS The nested-name-specifier, which will be updated in-place
5098 /// to reflect the parsed nested-name-specifier.
5100 /// \returns true if an error occurred, false otherwise.
5101 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5103 /// \brief The parser has parsed a '__super' nested-name-specifier.
5105 /// \param SuperLoc The location of the '__super' keyword.
5107 /// \param ColonColonLoc The location of the '::'.
5109 /// \param SS The nested-name-specifier, which will be updated in-place
5110 /// to reflect the parsed nested-name-specifier.
5112 /// \returns true if an error occurred, false otherwise.
5113 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5114 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5116 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5117 bool *CanCorrect = nullptr);
5118 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5120 /// \brief Keeps information about an identifier in a nested-name-spec.
5122 struct NestedNameSpecInfo {
5123 /// \brief The type of the object, if we're parsing nested-name-specifier in
5124 /// a member access expression.
5125 ParsedType ObjectType;
5127 /// \brief The identifier preceding the '::'.
5128 IdentifierInfo *Identifier;
5130 /// \brief The location of the identifier.
5131 SourceLocation IdentifierLoc;
5133 /// \brief The location of the '::'.
5134 SourceLocation CCLoc;
5136 /// \brief Creates info object for the most typical case.
5137 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5138 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5139 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5140 CCLoc(ColonColonLoc) {
5143 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5144 SourceLocation ColonColonLoc, QualType ObjectType)
5145 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5146 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5150 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5151 NestedNameSpecInfo &IdInfo);
5153 bool BuildCXXNestedNameSpecifier(Scope *S,
5154 NestedNameSpecInfo &IdInfo,
5155 bool EnteringContext,
5157 NamedDecl *ScopeLookupResult,
5158 bool ErrorRecoveryLookup,
5159 bool *IsCorrectedToColon = nullptr,
5160 bool OnlyNamespace = false);
5162 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5164 /// \param S The scope in which this nested-name-specifier occurs.
5166 /// \param IdInfo Parser information about an identifier in the
5167 /// nested-name-spec.
5169 /// \param EnteringContext Whether we're entering the context nominated by
5170 /// this nested-name-specifier.
5172 /// \param SS The nested-name-specifier, which is both an input
5173 /// parameter (the nested-name-specifier before this type) and an
5174 /// output parameter (containing the full nested-name-specifier,
5175 /// including this new type).
5177 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5178 /// error recovery. In this case do not emit error message.
5180 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5181 /// are allowed. The bool value pointed by this parameter is set to 'true'
5182 /// if the identifier is treated as if it was followed by ':', not '::'.
5184 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5186 /// \returns true if an error occurred, false otherwise.
5187 bool ActOnCXXNestedNameSpecifier(Scope *S,
5188 NestedNameSpecInfo &IdInfo,
5189 bool EnteringContext,
5191 bool ErrorRecoveryLookup = false,
5192 bool *IsCorrectedToColon = nullptr,
5193 bool OnlyNamespace = false);
5195 ExprResult ActOnDecltypeExpression(Expr *E);
5197 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5199 SourceLocation ColonColonLoc);
5201 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5202 NestedNameSpecInfo &IdInfo,
5203 bool EnteringContext);
5205 /// \brief The parser has parsed a nested-name-specifier
5206 /// 'template[opt] template-name < template-args >::'.
5208 /// \param S The scope in which this nested-name-specifier occurs.
5210 /// \param SS The nested-name-specifier, which is both an input
5211 /// parameter (the nested-name-specifier before this type) and an
5212 /// output parameter (containing the full nested-name-specifier,
5213 /// including this new type).
5215 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5216 /// \param TemplateName the template name.
5217 /// \param TemplateNameLoc The location of the template name.
5218 /// \param LAngleLoc The location of the opening angle bracket ('<').
5219 /// \param TemplateArgs The template arguments.
5220 /// \param RAngleLoc The location of the closing angle bracket ('>').
5221 /// \param CCLoc The location of the '::'.
5223 /// \param EnteringContext Whether we're entering the context of the
5224 /// nested-name-specifier.
5227 /// \returns true if an error occurred, false otherwise.
5228 bool ActOnCXXNestedNameSpecifier(Scope *S,
5230 SourceLocation TemplateKWLoc,
5231 TemplateTy TemplateName,
5232 SourceLocation TemplateNameLoc,
5233 SourceLocation LAngleLoc,
5234 ASTTemplateArgsPtr TemplateArgs,
5235 SourceLocation RAngleLoc,
5236 SourceLocation CCLoc,
5237 bool EnteringContext);
5239 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5240 /// that the parser can use later to reconstruct the given
5241 /// nested-name-specifier.
5243 /// \param SS A nested-name-specifier.
5245 /// \returns A pointer containing all of the information in the
5246 /// nested-name-specifier \p SS.
5247 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5249 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5250 /// the nested-name-specifier structure.
5252 /// \param Annotation The annotation pointer, produced by
5253 /// \c SaveNestedNameSpecifierAnnotation().
5255 /// \param AnnotationRange The source range corresponding to the annotation.
5257 /// \param SS The nested-name-specifier that will be updated with the contents
5258 /// of the annotation pointer.
5259 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5260 SourceRange AnnotationRange,
5263 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5265 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5266 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5267 /// After this method is called, according to [C++ 3.4.3p3], names should be
5268 /// looked up in the declarator-id's scope, until the declarator is parsed and
5269 /// ActOnCXXExitDeclaratorScope is called.
5270 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5271 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5273 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5274 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5275 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5276 /// Used to indicate that names should revert to being looked up in the
5278 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5280 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5281 /// initializer for the declaration 'Dcl'.
5282 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5283 /// static data member of class X, names should be looked up in the scope of
5285 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5287 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5288 /// initializer for the declaration 'Dcl'.
5289 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5291 /// \brief Create a new lambda closure type.
5292 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5293 TypeSourceInfo *Info,
5294 bool KnownDependent,
5295 LambdaCaptureDefault CaptureDefault);
5297 /// \brief Start the definition of a lambda expression.
5298 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5299 SourceRange IntroducerRange,
5300 TypeSourceInfo *MethodType,
5301 SourceLocation EndLoc,
5302 ArrayRef<ParmVarDecl *> Params,
5303 bool IsConstexprSpecified);
5305 /// \brief Endow the lambda scope info with the relevant properties.
5306 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5307 CXXMethodDecl *CallOperator,
5308 SourceRange IntroducerRange,
5309 LambdaCaptureDefault CaptureDefault,
5310 SourceLocation CaptureDefaultLoc,
5311 bool ExplicitParams,
5312 bool ExplicitResultType,
5315 /// \brief Perform initialization analysis of the init-capture and perform
5316 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5317 /// not being used to initialize a reference.
5318 ParsedType actOnLambdaInitCaptureInitialization(
5319 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5320 LambdaCaptureInitKind InitKind, Expr *&Init) {
5321 return ParsedType::make(buildLambdaInitCaptureInitialization(
5322 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5324 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5326 bool DirectInit, Expr *&Init);
5328 /// \brief Create a dummy variable within the declcontext of the lambda's
5329 /// call operator, for name lookup purposes for a lambda init capture.
5331 /// CodeGen handles emission of lambda captures, ignoring these dummy
5332 /// variables appropriately.
5333 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5334 QualType InitCaptureType,
5336 unsigned InitStyle, Expr *Init);
5338 /// \brief Build the implicit field for an init-capture.
5339 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5341 /// \brief Note that we have finished the explicit captures for the
5343 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5345 /// \brief Introduce the lambda parameters into scope.
5346 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5348 /// \brief Deduce a block or lambda's return type based on the return
5349 /// statements present in the body.
5350 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5352 /// ActOnStartOfLambdaDefinition - This is called just before we start
5353 /// parsing the body of a lambda; it analyzes the explicit captures and
5354 /// arguments, and sets up various data-structures for the body of the
5356 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5357 Declarator &ParamInfo, Scope *CurScope);
5359 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5360 /// is invoked to pop the information about the lambda.
5361 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5362 bool IsInstantiation = false);
5364 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5365 /// was successfully completed.
5366 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5369 /// \brief Does copying/destroying the captured variable have side effects?
5370 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5372 /// \brief Diagnose if an explicit lambda capture is unused.
5373 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5375 /// \brief Complete a lambda-expression having processed and attached the
5377 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5378 sema::LambdaScopeInfo *LSI);
5380 /// \brief Define the "body" of the conversion from a lambda object to a
5381 /// function pointer.
5383 /// This routine doesn't actually define a sensible body; rather, it fills
5384 /// in the initialization expression needed to copy the lambda object into
5385 /// the block, and IR generation actually generates the real body of the
5386 /// block pointer conversion.
5387 void DefineImplicitLambdaToFunctionPointerConversion(
5388 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5390 /// \brief Define the "body" of the conversion from a lambda object to a
5393 /// This routine doesn't actually define a sensible body; rather, it fills
5394 /// in the initialization expression needed to copy the lambda object into
5395 /// the block, and IR generation actually generates the real body of the
5396 /// block pointer conversion.
5397 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5398 CXXConversionDecl *Conv);
5400 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5401 SourceLocation ConvLocation,
5402 CXXConversionDecl *Conv,
5405 // ParseObjCStringLiteral - Parse Objective-C string literals.
5406 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5407 ArrayRef<Expr *> Strings);
5409 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5411 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5412 /// numeric literal expression. Type of the expression will be "NSNumber *"
5413 /// or "id" if NSNumber is unavailable.
5414 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5415 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5417 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5419 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5420 /// '@' prefixed parenthesized expression. The type of the expression will
5421 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5422 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5423 /// "const char *" or C structure with attribute 'objc_boxable'.
5424 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5426 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5428 ObjCMethodDecl *getterMethod,
5429 ObjCMethodDecl *setterMethod);
5431 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5432 MutableArrayRef<ObjCDictionaryElement> Elements);
5434 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5435 TypeSourceInfo *EncodedTypeInfo,
5436 SourceLocation RParenLoc);
5437 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5438 CXXConversionDecl *Method,
5439 bool HadMultipleCandidates);
5441 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5442 SourceLocation EncodeLoc,
5443 SourceLocation LParenLoc,
5445 SourceLocation RParenLoc);
5447 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5448 ExprResult ParseObjCSelectorExpression(Selector Sel,
5449 SourceLocation AtLoc,
5450 SourceLocation SelLoc,
5451 SourceLocation LParenLoc,
5452 SourceLocation RParenLoc,
5453 bool WarnMultipleSelectors);
5455 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5456 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5457 SourceLocation AtLoc,
5458 SourceLocation ProtoLoc,
5459 SourceLocation LParenLoc,
5460 SourceLocation ProtoIdLoc,
5461 SourceLocation RParenLoc);
5463 //===--------------------------------------------------------------------===//
5466 Decl *ActOnStartLinkageSpecification(Scope *S,
5467 SourceLocation ExternLoc,
5469 SourceLocation LBraceLoc);
5470 Decl *ActOnFinishLinkageSpecification(Scope *S,
5472 SourceLocation RBraceLoc);
5475 //===--------------------------------------------------------------------===//
5478 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5479 const CXXScopeSpec *SS = nullptr);
5480 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5482 bool ActOnAccessSpecifier(AccessSpecifier Access,
5483 SourceLocation ASLoc,
5484 SourceLocation ColonLoc,
5485 AttributeList *Attrs = nullptr);
5487 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5489 MultiTemplateParamsArg TemplateParameterLists,
5490 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5491 InClassInitStyle InitStyle);
5493 void ActOnStartCXXInClassMemberInitializer();
5494 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5495 SourceLocation EqualLoc,
5498 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5501 IdentifierInfo *MemberOrBase,
5502 ParsedType TemplateTypeTy,
5504 SourceLocation IdLoc,
5505 SourceLocation LParenLoc,
5506 ArrayRef<Expr *> Args,
5507 SourceLocation RParenLoc,
5508 SourceLocation EllipsisLoc);
5510 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5513 IdentifierInfo *MemberOrBase,
5514 ParsedType TemplateTypeTy,
5516 SourceLocation IdLoc,
5518 SourceLocation EllipsisLoc);
5520 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5523 IdentifierInfo *MemberOrBase,
5524 ParsedType TemplateTypeTy,
5526 SourceLocation IdLoc,
5528 SourceLocation EllipsisLoc);
5530 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5532 SourceLocation IdLoc);
5534 MemInitResult BuildBaseInitializer(QualType BaseType,
5535 TypeSourceInfo *BaseTInfo,
5537 CXXRecordDecl *ClassDecl,
5538 SourceLocation EllipsisLoc);
5540 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5542 CXXRecordDecl *ClassDecl);
5544 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5545 CXXCtorInitializer *Initializer);
5547 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5548 ArrayRef<CXXCtorInitializer *> Initializers = None);
5550 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5553 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5554 /// mark all the non-trivial destructors of its members and bases as
5556 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5557 CXXRecordDecl *Record);
5559 /// \brief The list of classes whose vtables have been used within
5560 /// this translation unit, and the source locations at which the
5561 /// first use occurred.
5562 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5564 /// \brief The list of vtables that are required but have not yet been
5566 SmallVector<VTableUse, 16> VTableUses;
5568 /// \brief The set of classes whose vtables have been used within
5569 /// this translation unit, and a bit that will be true if the vtable is
5570 /// required to be emitted (otherwise, it should be emitted only if needed
5571 /// by code generation).
5572 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5574 /// \brief Load any externally-stored vtable uses.
5575 void LoadExternalVTableUses();
5577 /// \brief Note that the vtable for the given class was used at the
5579 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5580 bool DefinitionRequired = false);
5582 /// \brief Mark the exception specifications of all virtual member functions
5583 /// in the given class as needed.
5584 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5585 const CXXRecordDecl *RD);
5587 /// MarkVirtualMembersReferenced - Will mark all members of the given
5588 /// CXXRecordDecl referenced.
5589 void MarkVirtualMembersReferenced(SourceLocation Loc,
5590 const CXXRecordDecl *RD);
5592 /// \brief Define all of the vtables that have been used in this
5593 /// translation unit and reference any virtual members used by those
5596 /// \returns true if any work was done, false otherwise.
5597 bool DefineUsedVTables();
5599 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5601 void ActOnMemInitializers(Decl *ConstructorDecl,
5602 SourceLocation ColonLoc,
5603 ArrayRef<CXXCtorInitializer*> MemInits,
5606 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5607 /// ensure that referenceDLLExportedClassMethods is called some point later
5608 /// when all outer classes of Class are complete.
5609 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5611 void referenceDLLExportedClassMethods();
5613 void propagateDLLAttrToBaseClassTemplate(
5614 CXXRecordDecl *Class, Attr *ClassAttr,
5615 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5616 SourceLocation BaseLoc);
5618 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5619 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5621 SourceLocation LBrac,
5622 SourceLocation RBrac,
5623 AttributeList *AttrList);
5624 void ActOnFinishCXXMemberDecls();
5625 void ActOnFinishCXXNonNestedClass(Decl *D);
5627 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5628 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5629 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5630 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5631 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5632 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5633 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5634 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5635 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5636 CachedTokens &Toks);
5637 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5638 bool IsInsideALocalClassWithinATemplateFunction();
5640 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5642 Expr *AssertMessageExpr,
5643 SourceLocation RParenLoc);
5644 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5646 StringLiteral *AssertMessageExpr,
5647 SourceLocation RParenLoc,
5650 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5651 SourceLocation FriendLoc,
5652 TypeSourceInfo *TSInfo);
5653 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5654 MultiTemplateParamsArg TemplateParams);
5655 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5656 MultiTemplateParamsArg TemplateParams);
5658 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5660 void CheckConstructor(CXXConstructorDecl *Constructor);
5661 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5663 bool CheckDestructor(CXXDestructorDecl *Destructor);
5664 void CheckConversionDeclarator(Declarator &D, QualType &R,
5666 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5667 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5669 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5671 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5672 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5673 const FunctionProtoType *T);
5674 void CheckDelayedMemberExceptionSpecs();
5676 //===--------------------------------------------------------------------===//
5677 // C++ Derived Classes
5680 /// ActOnBaseSpecifier - Parsed a base specifier
5681 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5682 SourceRange SpecifierRange,
5683 bool Virtual, AccessSpecifier Access,
5684 TypeSourceInfo *TInfo,
5685 SourceLocation EllipsisLoc);
5687 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5688 SourceRange SpecifierRange,
5689 ParsedAttributes &Attrs,
5690 bool Virtual, AccessSpecifier Access,
5691 ParsedType basetype,
5692 SourceLocation BaseLoc,
5693 SourceLocation EllipsisLoc);
5695 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5696 MutableArrayRef<CXXBaseSpecifier *> Bases);
5697 void ActOnBaseSpecifiers(Decl *ClassDecl,
5698 MutableArrayRef<CXXBaseSpecifier *> Bases);
5700 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5701 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5702 CXXBasePaths &Paths);
5704 // FIXME: I don't like this name.
5705 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5707 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5708 SourceLocation Loc, SourceRange Range,
5709 CXXCastPath *BasePath = nullptr,
5710 bool IgnoreAccess = false);
5711 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5712 unsigned InaccessibleBaseID,
5713 unsigned AmbigiousBaseConvID,
5714 SourceLocation Loc, SourceRange Range,
5715 DeclarationName Name,
5716 CXXCastPath *BasePath,
5717 bool IgnoreAccess = false);
5719 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5721 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5722 const CXXMethodDecl *Old);
5724 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5725 /// covariant, according to C++ [class.virtual]p5.
5726 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5727 const CXXMethodDecl *Old);
5729 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5730 /// spec is a subset of base spec.
5731 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5732 const CXXMethodDecl *Old);
5734 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5736 /// CheckOverrideControl - Check C++11 override control semantics.
5737 void CheckOverrideControl(NamedDecl *D);
5739 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5740 /// not used in the declaration of an overriding method.
5741 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5743 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5744 /// overrides a virtual member function marked 'final', according to
5745 /// C++11 [class.virtual]p4.
5746 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5747 const CXXMethodDecl *Old);
5750 //===--------------------------------------------------------------------===//
5751 // C++ Access Control
5761 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5762 NamedDecl *PrevMemberDecl,
5763 AccessSpecifier LexicalAS);
5765 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5766 DeclAccessPair FoundDecl);
5767 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5768 DeclAccessPair FoundDecl);
5769 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5770 SourceRange PlacementRange,
5771 CXXRecordDecl *NamingClass,
5772 DeclAccessPair FoundDecl,
5773 bool Diagnose = true);
5774 AccessResult CheckConstructorAccess(SourceLocation Loc,
5775 CXXConstructorDecl *D,
5776 DeclAccessPair FoundDecl,
5777 const InitializedEntity &Entity,
5778 bool IsCopyBindingRefToTemp = false);
5779 AccessResult CheckConstructorAccess(SourceLocation Loc,
5780 CXXConstructorDecl *D,
5781 DeclAccessPair FoundDecl,
5782 const InitializedEntity &Entity,
5783 const PartialDiagnostic &PDiag);
5784 AccessResult CheckDestructorAccess(SourceLocation Loc,
5785 CXXDestructorDecl *Dtor,
5786 const PartialDiagnostic &PDiag,
5787 QualType objectType = QualType());
5788 AccessResult CheckFriendAccess(NamedDecl *D);
5789 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5790 CXXRecordDecl *NamingClass,
5791 DeclAccessPair Found);
5792 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5795 DeclAccessPair FoundDecl);
5796 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5797 DeclAccessPair FoundDecl);
5798 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5799 QualType Base, QualType Derived,
5800 const CXXBasePath &Path,
5802 bool ForceCheck = false,
5803 bool ForceUnprivileged = false);
5804 void CheckLookupAccess(const LookupResult &R);
5805 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5806 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5807 AccessSpecifier access,
5808 QualType objectType);
5810 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5811 const MultiLevelTemplateArgumentList &TemplateArgs);
5812 void PerformDependentDiagnostics(const DeclContext *Pattern,
5813 const MultiLevelTemplateArgumentList &TemplateArgs);
5815 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5817 /// \brief When true, access checking violations are treated as SFINAE
5818 /// failures rather than hard errors.
5819 bool AccessCheckingSFINAE;
5821 enum AbstractDiagSelID {
5825 AbstractVariableType,
5828 AbstractSynthesizedIvarType,
5832 bool isAbstractType(SourceLocation Loc, QualType T);
5833 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5834 TypeDiagnoser &Diagnoser);
5835 template <typename... Ts>
5836 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5837 const Ts &...Args) {
5838 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5839 return RequireNonAbstractType(Loc, T, Diagnoser);
5842 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5844 //===--------------------------------------------------------------------===//
5845 // C++ Overloaded Operators [C++ 13.5]
5848 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5850 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5852 //===--------------------------------------------------------------------===//
5853 // C++ Templates [C++ 14]
5855 void FilterAcceptableTemplateNames(LookupResult &R,
5856 bool AllowFunctionTemplates = true);
5857 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5858 bool AllowFunctionTemplates = true);
5860 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5861 QualType ObjectType, bool EnteringContext,
5862 bool &MemberOfUnknownSpecialization);
5864 TemplateNameKind isTemplateName(Scope *S,
5866 bool hasTemplateKeyword,
5867 UnqualifiedId &Name,
5868 ParsedType ObjectType,
5869 bool EnteringContext,
5870 TemplateTy &Template,
5871 bool &MemberOfUnknownSpecialization);
5873 /// Determine whether a particular identifier might be the name in a C++1z
5874 /// deduction-guide declaration.
5875 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5876 SourceLocation NameLoc,
5877 ParsedTemplateTy *Template = nullptr);
5879 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5880 SourceLocation IILoc,
5882 const CXXScopeSpec *SS,
5883 TemplateTy &SuggestedTemplate,
5884 TemplateNameKind &SuggestedKind);
5886 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5887 NamedDecl *Instantiation,
5888 bool InstantiatedFromMember,
5889 const NamedDecl *Pattern,
5890 const NamedDecl *PatternDef,
5891 TemplateSpecializationKind TSK,
5892 bool Complain = true);
5894 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5895 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5897 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5898 SourceLocation EllipsisLoc,
5899 SourceLocation KeyLoc,
5900 IdentifierInfo *ParamName,
5901 SourceLocation ParamNameLoc,
5902 unsigned Depth, unsigned Position,
5903 SourceLocation EqualLoc,
5904 ParsedType DefaultArg);
5906 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5907 SourceLocation Loc);
5908 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5910 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5913 SourceLocation EqualLoc,
5915 Decl *ActOnTemplateTemplateParameter(Scope *S,
5916 SourceLocation TmpLoc,
5917 TemplateParameterList *Params,
5918 SourceLocation EllipsisLoc,
5919 IdentifierInfo *ParamName,
5920 SourceLocation ParamNameLoc,
5923 SourceLocation EqualLoc,
5924 ParsedTemplateArgument DefaultArg);
5926 TemplateParameterList *
5927 ActOnTemplateParameterList(unsigned Depth,
5928 SourceLocation ExportLoc,
5929 SourceLocation TemplateLoc,
5930 SourceLocation LAngleLoc,
5931 ArrayRef<Decl *> Params,
5932 SourceLocation RAngleLoc,
5933 Expr *RequiresClause);
5935 /// \brief The context in which we are checking a template parameter list.
5936 enum TemplateParamListContext {
5939 TPC_FunctionTemplate,
5940 TPC_ClassTemplateMember,
5941 TPC_FriendClassTemplate,
5942 TPC_FriendFunctionTemplate,
5943 TPC_FriendFunctionTemplateDefinition,
5944 TPC_TypeAliasTemplate
5947 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5948 TemplateParameterList *OldParams,
5949 TemplateParamListContext TPC);
5950 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5951 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5952 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5953 ArrayRef<TemplateParameterList *> ParamLists,
5954 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5956 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5957 SourceLocation KWLoc, CXXScopeSpec &SS,
5958 IdentifierInfo *Name, SourceLocation NameLoc,
5959 AttributeList *Attr,
5960 TemplateParameterList *TemplateParams,
5962 SourceLocation ModulePrivateLoc,
5963 SourceLocation FriendLoc,
5964 unsigned NumOuterTemplateParamLists,
5965 TemplateParameterList **OuterTemplateParamLists,
5966 SkipBodyInfo *SkipBody = nullptr);
5968 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
5970 SourceLocation Loc);
5972 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5973 TemplateArgumentListInfo &Out);
5975 void NoteAllFoundTemplates(TemplateName Name);
5977 QualType CheckTemplateIdType(TemplateName Template,
5978 SourceLocation TemplateLoc,
5979 TemplateArgumentListInfo &TemplateArgs);
5982 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5983 TemplateTy Template, IdentifierInfo *TemplateII,
5984 SourceLocation TemplateIILoc,
5985 SourceLocation LAngleLoc,
5986 ASTTemplateArgsPtr TemplateArgs,
5987 SourceLocation RAngleLoc,
5988 bool IsCtorOrDtorName = false,
5989 bool IsClassName = false);
5991 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5992 /// such as \c class T::template apply<U>.
5993 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5994 TypeSpecifierType TagSpec,
5995 SourceLocation TagLoc,
5997 SourceLocation TemplateKWLoc,
5998 TemplateTy TemplateD,
5999 SourceLocation TemplateLoc,
6000 SourceLocation LAngleLoc,
6001 ASTTemplateArgsPtr TemplateArgsIn,
6002 SourceLocation RAngleLoc);
6004 DeclResult ActOnVarTemplateSpecialization(
6005 Scope *S, Declarator &D, TypeSourceInfo *DI,
6006 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6007 StorageClass SC, bool IsPartialSpecialization);
6009 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6010 SourceLocation TemplateLoc,
6011 SourceLocation TemplateNameLoc,
6012 const TemplateArgumentListInfo &TemplateArgs);
6014 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6015 const DeclarationNameInfo &NameInfo,
6016 VarTemplateDecl *Template,
6017 SourceLocation TemplateLoc,
6018 const TemplateArgumentListInfo *TemplateArgs);
6020 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6021 SourceLocation TemplateKWLoc,
6024 const TemplateArgumentListInfo *TemplateArgs);
6026 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6027 SourceLocation TemplateKWLoc,
6028 const DeclarationNameInfo &NameInfo,
6029 const TemplateArgumentListInfo *TemplateArgs);
6031 TemplateNameKind ActOnDependentTemplateName(
6032 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6033 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6034 TemplateTy &Template, bool AllowInjectedClassName = false);
6037 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6038 SourceLocation KWLoc,
6039 SourceLocation ModulePrivateLoc,
6040 TemplateIdAnnotation &TemplateId,
6041 AttributeList *Attr,
6042 MultiTemplateParamsArg TemplateParameterLists,
6043 SkipBodyInfo *SkipBody = nullptr);
6045 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6046 TemplateDecl *PrimaryTemplate,
6047 unsigned NumExplicitArgs,
6048 ArrayRef<TemplateArgument> Args);
6049 void CheckTemplatePartialSpecialization(
6050 ClassTemplatePartialSpecializationDecl *Partial);
6051 void CheckTemplatePartialSpecialization(
6052 VarTemplatePartialSpecializationDecl *Partial);
6054 Decl *ActOnTemplateDeclarator(Scope *S,
6055 MultiTemplateParamsArg TemplateParameterLists,
6059 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6060 TemplateSpecializationKind NewTSK,
6061 NamedDecl *PrevDecl,
6062 TemplateSpecializationKind PrevTSK,
6063 SourceLocation PrevPtOfInstantiation,
6066 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6067 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6068 LookupResult &Previous);
6070 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6071 TemplateArgumentListInfo *ExplicitTemplateArgs,
6072 LookupResult &Previous);
6073 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6076 ActOnExplicitInstantiation(Scope *S,
6077 SourceLocation ExternLoc,
6078 SourceLocation TemplateLoc,
6080 SourceLocation KWLoc,
6081 const CXXScopeSpec &SS,
6082 TemplateTy Template,
6083 SourceLocation TemplateNameLoc,
6084 SourceLocation LAngleLoc,
6085 ASTTemplateArgsPtr TemplateArgs,
6086 SourceLocation RAngleLoc,
6087 AttributeList *Attr);
6090 ActOnExplicitInstantiation(Scope *S,
6091 SourceLocation ExternLoc,
6092 SourceLocation TemplateLoc,
6094 SourceLocation KWLoc,
6096 IdentifierInfo *Name,
6097 SourceLocation NameLoc,
6098 AttributeList *Attr);
6100 DeclResult ActOnExplicitInstantiation(Scope *S,
6101 SourceLocation ExternLoc,
6102 SourceLocation TemplateLoc,
6106 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6107 SourceLocation TemplateLoc,
6108 SourceLocation RAngleLoc,
6110 SmallVectorImpl<TemplateArgument>
6112 bool &HasDefaultArg);
6114 /// \brief Specifies the context in which a particular template
6115 /// argument is being checked.
6116 enum CheckTemplateArgumentKind {
6117 /// \brief The template argument was specified in the code or was
6118 /// instantiated with some deduced template arguments.
6121 /// \brief The template argument was deduced via template argument
6125 /// \brief The template argument was deduced from an array bound
6126 /// via template argument deduction.
6127 CTAK_DeducedFromArrayBound
6130 bool CheckTemplateArgument(NamedDecl *Param,
6131 TemplateArgumentLoc &Arg,
6132 NamedDecl *Template,
6133 SourceLocation TemplateLoc,
6134 SourceLocation RAngleLoc,
6135 unsigned ArgumentPackIndex,
6136 SmallVectorImpl<TemplateArgument> &Converted,
6137 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6139 /// \brief Check that the given template arguments can be be provided to
6140 /// the given template, converting the arguments along the way.
6142 /// \param Template The template to which the template arguments are being
6145 /// \param TemplateLoc The location of the template name in the source.
6147 /// \param TemplateArgs The list of template arguments. If the template is
6148 /// a template template parameter, this function may extend the set of
6149 /// template arguments to also include substituted, defaulted template
6152 /// \param PartialTemplateArgs True if the list of template arguments is
6153 /// intentionally partial, e.g., because we're checking just the initial
6154 /// set of template arguments.
6156 /// \param Converted Will receive the converted, canonicalized template
6159 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6160 /// contain the converted forms of the template arguments as written.
6161 /// Otherwise, \p TemplateArgs will not be modified.
6163 /// \returns true if an error occurred, false otherwise.
6164 bool CheckTemplateArgumentList(TemplateDecl *Template,
6165 SourceLocation TemplateLoc,
6166 TemplateArgumentListInfo &TemplateArgs,
6167 bool PartialTemplateArgs,
6168 SmallVectorImpl<TemplateArgument> &Converted,
6169 bool UpdateArgsWithConversions = true);
6171 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6172 TemplateArgumentLoc &Arg,
6173 SmallVectorImpl<TemplateArgument> &Converted);
6175 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6176 TypeSourceInfo *Arg);
6177 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6178 QualType InstantiatedParamType, Expr *Arg,
6179 TemplateArgument &Converted,
6180 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6181 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6182 TemplateArgumentLoc &Arg,
6183 unsigned ArgumentPackIndex);
6186 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6188 SourceLocation Loc);
6190 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6191 SourceLocation Loc);
6193 /// \brief Enumeration describing how template parameter lists are compared
6195 enum TemplateParameterListEqualKind {
6196 /// \brief We are matching the template parameter lists of two templates
6197 /// that might be redeclarations.
6200 /// template<typename T> struct X;
6201 /// template<typename T> struct X;
6205 /// \brief We are matching the template parameter lists of two template
6206 /// template parameters as part of matching the template parameter lists
6207 /// of two templates that might be redeclarations.
6210 /// template<template<int I> class TT> struct X;
6211 /// template<template<int Value> class Other> struct X;
6213 TPL_TemplateTemplateParmMatch,
6215 /// \brief We are matching the template parameter lists of a template
6216 /// template argument against the template parameter lists of a template
6217 /// template parameter.
6220 /// template<template<int Value> class Metafun> struct X;
6221 /// template<int Value> struct integer_c;
6222 /// X<integer_c> xic;
6224 TPL_TemplateTemplateArgumentMatch
6227 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6228 TemplateParameterList *Old,
6230 TemplateParameterListEqualKind Kind,
6231 SourceLocation TemplateArgLoc
6232 = SourceLocation());
6234 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6236 /// \brief Called when the parser has parsed a C++ typename
6237 /// specifier, e.g., "typename T::type".
6239 /// \param S The scope in which this typename type occurs.
6240 /// \param TypenameLoc the location of the 'typename' keyword
6241 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6242 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6243 /// \param IdLoc the location of the identifier.
6245 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6246 const CXXScopeSpec &SS, const IdentifierInfo &II,
6247 SourceLocation IdLoc);
6249 /// \brief Called when the parser has parsed a C++ typename
6250 /// specifier that ends in a template-id, e.g.,
6251 /// "typename MetaFun::template apply<T1, T2>".
6253 /// \param S The scope in which this typename type occurs.
6254 /// \param TypenameLoc the location of the 'typename' keyword
6255 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6256 /// \param TemplateLoc the location of the 'template' keyword, if any.
6257 /// \param TemplateName The template name.
6258 /// \param TemplateII The identifier used to name the template.
6259 /// \param TemplateIILoc The location of the template name.
6260 /// \param LAngleLoc The location of the opening angle bracket ('<').
6261 /// \param TemplateArgs The template arguments.
6262 /// \param RAngleLoc The location of the closing angle bracket ('>').
6264 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6265 const CXXScopeSpec &SS,
6266 SourceLocation TemplateLoc,
6267 TemplateTy TemplateName,
6268 IdentifierInfo *TemplateII,
6269 SourceLocation TemplateIILoc,
6270 SourceLocation LAngleLoc,
6271 ASTTemplateArgsPtr TemplateArgs,
6272 SourceLocation RAngleLoc);
6274 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6275 SourceLocation KeywordLoc,
6276 NestedNameSpecifierLoc QualifierLoc,
6277 const IdentifierInfo &II,
6278 SourceLocation IILoc);
6280 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6282 DeclarationName Name);
6283 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6285 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6286 bool RebuildTemplateParamsInCurrentInstantiation(
6287 TemplateParameterList *Params);
6290 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6291 const TemplateArgumentList &Args);
6294 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6295 const TemplateArgument *Args,
6298 //===--------------------------------------------------------------------===//
6299 // C++ Variadic Templates (C++0x [temp.variadic])
6300 //===--------------------------------------------------------------------===//
6302 /// Determine whether an unexpanded parameter pack might be permitted in this
6303 /// location. Useful for error recovery.
6304 bool isUnexpandedParameterPackPermitted();
6306 /// \brief The context in which an unexpanded parameter pack is
6307 /// being diagnosed.
6309 /// Note that the values of this enumeration line up with the first
6310 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6311 enum UnexpandedParameterPackContext {
6312 /// \brief An arbitrary expression.
6313 UPPC_Expression = 0,
6315 /// \brief The base type of a class type.
6318 /// \brief The type of an arbitrary declaration.
6319 UPPC_DeclarationType,
6321 /// \brief The type of a data member.
6322 UPPC_DataMemberType,
6324 /// \brief The size of a bit-field.
6327 /// \brief The expression in a static assertion.
6328 UPPC_StaticAssertExpression,
6330 /// \brief The fixed underlying type of an enumeration.
6331 UPPC_FixedUnderlyingType,
6333 /// \brief The enumerator value.
6334 UPPC_EnumeratorValue,
6336 /// \brief A using declaration.
6337 UPPC_UsingDeclaration,
6339 /// \brief A friend declaration.
6340 UPPC_FriendDeclaration,
6342 /// \brief A declaration qualifier.
6343 UPPC_DeclarationQualifier,
6345 /// \brief An initializer.
6348 /// \brief A default argument.
6349 UPPC_DefaultArgument,
6351 /// \brief The type of a non-type template parameter.
6352 UPPC_NonTypeTemplateParameterType,
6354 /// \brief The type of an exception.
6357 /// \brief Partial specialization.
6358 UPPC_PartialSpecialization,
6360 /// \brief Microsoft __if_exists.
6363 /// \brief Microsoft __if_not_exists.
6366 /// \brief Lambda expression.
6369 /// \brief Block expression,
6373 /// \brief Diagnose unexpanded parameter packs.
6375 /// \param Loc The location at which we should emit the diagnostic.
6377 /// \param UPPC The context in which we are diagnosing unexpanded
6378 /// parameter packs.
6380 /// \param Unexpanded the set of unexpanded parameter packs.
6382 /// \returns true if an error occurred, false otherwise.
6383 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6384 UnexpandedParameterPackContext UPPC,
6385 ArrayRef<UnexpandedParameterPack> Unexpanded);
6387 /// \brief If the given type contains an unexpanded parameter pack,
6388 /// diagnose the error.
6390 /// \param Loc The source location where a diagnostc should be emitted.
6392 /// \param T The type that is being checked for unexpanded parameter
6395 /// \returns true if an error occurred, false otherwise.
6396 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6397 UnexpandedParameterPackContext UPPC);
6399 /// \brief If the given expression contains an unexpanded parameter
6400 /// pack, diagnose the error.
6402 /// \param E The expression that is being checked for unexpanded
6403 /// parameter packs.
6405 /// \returns true if an error occurred, false otherwise.
6406 bool DiagnoseUnexpandedParameterPack(Expr *E,
6407 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6409 /// \brief If the given nested-name-specifier contains an unexpanded
6410 /// parameter pack, diagnose the error.
6412 /// \param SS The nested-name-specifier that is being checked for
6413 /// unexpanded parameter packs.
6415 /// \returns true if an error occurred, false otherwise.
6416 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6417 UnexpandedParameterPackContext UPPC);
6419 /// \brief If the given name contains an unexpanded parameter pack,
6420 /// diagnose the error.
6422 /// \param NameInfo The name (with source location information) that
6423 /// is being checked for unexpanded parameter packs.
6425 /// \returns true if an error occurred, false otherwise.
6426 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6427 UnexpandedParameterPackContext UPPC);
6429 /// \brief If the given template name contains an unexpanded parameter pack,
6430 /// diagnose the error.
6432 /// \param Loc The location of the template name.
6434 /// \param Template The template name that is being checked for unexpanded
6435 /// parameter packs.
6437 /// \returns true if an error occurred, false otherwise.
6438 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6439 TemplateName Template,
6440 UnexpandedParameterPackContext UPPC);
6442 /// \brief If the given template argument contains an unexpanded parameter
6443 /// pack, diagnose the error.
6445 /// \param Arg The template argument that is being checked for unexpanded
6446 /// parameter packs.
6448 /// \returns true if an error occurred, false otherwise.
6449 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6450 UnexpandedParameterPackContext UPPC);
6452 /// \brief Collect the set of unexpanded parameter packs within the given
6453 /// template argument.
6455 /// \param Arg The template argument that will be traversed to find
6456 /// unexpanded parameter packs.
6457 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6458 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6460 /// \brief Collect the set of unexpanded parameter packs within the given
6461 /// template argument.
6463 /// \param Arg The template argument that will be traversed to find
6464 /// unexpanded parameter packs.
6465 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6466 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6468 /// \brief Collect the set of unexpanded parameter packs within the given
6471 /// \param T The type that will be traversed to find
6472 /// unexpanded parameter packs.
6473 void collectUnexpandedParameterPacks(QualType T,
6474 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6476 /// \brief Collect the set of unexpanded parameter packs within the given
6479 /// \param TL The type that will be traversed to find
6480 /// unexpanded parameter packs.
6481 void collectUnexpandedParameterPacks(TypeLoc TL,
6482 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6484 /// \brief Collect the set of unexpanded parameter packs within the given
6485 /// nested-name-specifier.
6487 /// \param NNS The nested-name-specifier that will be traversed to find
6488 /// unexpanded parameter packs.
6489 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6490 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6492 /// \brief Collect the set of unexpanded parameter packs within the given
6495 /// \param NameInfo The name that will be traversed to find
6496 /// unexpanded parameter packs.
6497 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6498 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6500 /// \brief Invoked when parsing a template argument followed by an
6501 /// ellipsis, which creates a pack expansion.
6503 /// \param Arg The template argument preceding the ellipsis, which
6504 /// may already be invalid.
6506 /// \param EllipsisLoc The location of the ellipsis.
6507 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6508 SourceLocation EllipsisLoc);
6510 /// \brief Invoked when parsing a type followed by an ellipsis, which
6511 /// creates a pack expansion.
6513 /// \param Type The type preceding the ellipsis, which will become
6514 /// the pattern of the pack expansion.
6516 /// \param EllipsisLoc The location of the ellipsis.
6517 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6519 /// \brief Construct a pack expansion type from the pattern of the pack
6521 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6522 SourceLocation EllipsisLoc,
6523 Optional<unsigned> NumExpansions);
6525 /// \brief Construct a pack expansion type from the pattern of the pack
6527 QualType CheckPackExpansion(QualType Pattern,
6528 SourceRange PatternRange,
6529 SourceLocation EllipsisLoc,
6530 Optional<unsigned> NumExpansions);
6532 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6533 /// creates a pack expansion.
6535 /// \param Pattern The expression preceding the ellipsis, which will become
6536 /// the pattern of the pack expansion.
6538 /// \param EllipsisLoc The location of the ellipsis.
6539 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6541 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6542 /// creates a pack expansion.
6544 /// \param Pattern The expression preceding the ellipsis, which will become
6545 /// the pattern of the pack expansion.
6547 /// \param EllipsisLoc The location of the ellipsis.
6548 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6549 Optional<unsigned> NumExpansions);
6551 /// \brief Determine whether we could expand a pack expansion with the
6552 /// given set of parameter packs into separate arguments by repeatedly
6553 /// transforming the pattern.
6555 /// \param EllipsisLoc The location of the ellipsis that identifies the
6558 /// \param PatternRange The source range that covers the entire pattern of
6559 /// the pack expansion.
6561 /// \param Unexpanded The set of unexpanded parameter packs within the
6564 /// \param ShouldExpand Will be set to \c true if the transformer should
6565 /// expand the corresponding pack expansions into separate arguments. When
6566 /// set, \c NumExpansions must also be set.
6568 /// \param RetainExpansion Whether the caller should add an unexpanded
6569 /// pack expansion after all of the expanded arguments. This is used
6570 /// when extending explicitly-specified template argument packs per
6571 /// C++0x [temp.arg.explicit]p9.
6573 /// \param NumExpansions The number of separate arguments that will be in
6574 /// the expanded form of the corresponding pack expansion. This is both an
6575 /// input and an output parameter, which can be set by the caller if the
6576 /// number of expansions is known a priori (e.g., due to a prior substitution)
6577 /// and will be set by the callee when the number of expansions is known.
6578 /// The callee must set this value when \c ShouldExpand is \c true; it may
6579 /// set this value in other cases.
6581 /// \returns true if an error occurred (e.g., because the parameter packs
6582 /// are to be instantiated with arguments of different lengths), false
6583 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6585 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6586 SourceRange PatternRange,
6587 ArrayRef<UnexpandedParameterPack> Unexpanded,
6588 const MultiLevelTemplateArgumentList &TemplateArgs,
6590 bool &RetainExpansion,
6591 Optional<unsigned> &NumExpansions);
6593 /// \brief Determine the number of arguments in the given pack expansion
6596 /// This routine assumes that the number of arguments in the expansion is
6597 /// consistent across all of the unexpanded parameter packs in its pattern.
6599 /// Returns an empty Optional if the type can't be expanded.
6600 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6601 const MultiLevelTemplateArgumentList &TemplateArgs);
6603 /// \brief Determine whether the given declarator contains any unexpanded
6604 /// parameter packs.
6606 /// This routine is used by the parser to disambiguate function declarators
6607 /// with an ellipsis prior to the ')', e.g.,
6613 /// To determine whether we have an (unnamed) function parameter pack or
6614 /// a variadic function.
6616 /// \returns true if the declarator contains any unexpanded parameter packs,
6617 /// false otherwise.
6618 bool containsUnexpandedParameterPacks(Declarator &D);
6620 /// \brief Returns the pattern of the pack expansion for a template argument.
6622 /// \param OrigLoc The template argument to expand.
6624 /// \param Ellipsis Will be set to the location of the ellipsis.
6626 /// \param NumExpansions Will be set to the number of expansions that will
6627 /// be generated from this pack expansion, if known a priori.
6628 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6629 TemplateArgumentLoc OrigLoc,
6630 SourceLocation &Ellipsis,
6631 Optional<unsigned> &NumExpansions) const;
6633 /// Given a template argument that contains an unexpanded parameter pack, but
6634 /// which has already been substituted, attempt to determine the number of
6635 /// elements that will be produced once this argument is fully-expanded.
6637 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6638 /// avoid actually expanding the pack where possible.
6639 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6641 //===--------------------------------------------------------------------===//
6642 // C++ Template Argument Deduction (C++ [temp.deduct])
6643 //===--------------------------------------------------------------------===//
6645 /// Adjust the type \p ArgFunctionType to match the calling convention,
6646 /// noreturn, and optionally the exception specification of \p FunctionType.
6647 /// Deduction often wants to ignore these properties when matching function
6649 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6650 bool AdjustExceptionSpec = false);
6652 /// \brief Describes the result of template argument deduction.
6654 /// The TemplateDeductionResult enumeration describes the result of
6655 /// template argument deduction, as returned from
6656 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6657 /// structure provides additional information about the results of
6658 /// template argument deduction, e.g., the deduced template argument
6659 /// list (if successful) or the specific template parameters or
6660 /// deduced arguments that were involved in the failure.
6661 enum TemplateDeductionResult {
6662 /// \brief Template argument deduction was successful.
6664 /// \brief The declaration was invalid; do nothing.
6666 /// \brief Template argument deduction exceeded the maximum template
6667 /// instantiation depth (which has already been diagnosed).
6668 TDK_InstantiationDepth,
6669 /// \brief Template argument deduction did not deduce a value
6670 /// for every template parameter.
6672 /// \brief Template argument deduction produced inconsistent
6673 /// deduced values for the given template parameter.
6675 /// \brief Template argument deduction failed due to inconsistent
6676 /// cv-qualifiers on a template parameter type that would
6677 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6678 /// but were given a non-const "X".
6680 /// \brief Substitution of the deduced template argument values
6681 /// resulted in an error.
6682 TDK_SubstitutionFailure,
6683 /// \brief After substituting deduced template arguments, a dependent
6684 /// parameter type did not match the corresponding argument.
6685 TDK_DeducedMismatch,
6686 /// \brief After substituting deduced template arguments, an element of
6687 /// a dependent parameter type did not match the corresponding element
6688 /// of the corresponding argument (when deducing from an initializer list).
6689 TDK_DeducedMismatchNested,
6690 /// \brief A non-depnedent component of the parameter did not match the
6691 /// corresponding component of the argument.
6692 TDK_NonDeducedMismatch,
6693 /// \brief When performing template argument deduction for a function
6694 /// template, there were too many call arguments.
6695 TDK_TooManyArguments,
6696 /// \brief When performing template argument deduction for a function
6697 /// template, there were too few call arguments.
6698 TDK_TooFewArguments,
6699 /// \brief The explicitly-specified template arguments were not valid
6700 /// template arguments for the given template.
6701 TDK_InvalidExplicitArguments,
6702 /// \brief Checking non-dependent argument conversions failed.
6703 TDK_NonDependentConversionFailure,
6704 /// \brief Deduction failed; that's all we know.
6705 TDK_MiscellaneousDeductionFailure,
6706 /// \brief CUDA Target attributes do not match.
6707 TDK_CUDATargetMismatch
6710 TemplateDeductionResult
6711 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6712 const TemplateArgumentList &TemplateArgs,
6713 sema::TemplateDeductionInfo &Info);
6715 TemplateDeductionResult
6716 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6717 const TemplateArgumentList &TemplateArgs,
6718 sema::TemplateDeductionInfo &Info);
6720 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6721 FunctionTemplateDecl *FunctionTemplate,
6722 TemplateArgumentListInfo &ExplicitTemplateArgs,
6723 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6724 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6725 sema::TemplateDeductionInfo &Info);
6727 /// brief A function argument from which we performed template argument
6728 // deduction for a call.
6729 struct OriginalCallArg {
6730 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6731 unsigned ArgIdx, QualType OriginalArgType)
6732 : OriginalParamType(OriginalParamType),
6733 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6734 OriginalArgType(OriginalArgType) {}
6736 QualType OriginalParamType;
6737 bool DecomposedParam;
6739 QualType OriginalArgType;
6742 TemplateDeductionResult FinishTemplateArgumentDeduction(
6743 FunctionTemplateDecl *FunctionTemplate,
6744 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6745 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6746 sema::TemplateDeductionInfo &Info,
6747 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6748 bool PartialOverloading = false,
6749 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6751 TemplateDeductionResult DeduceTemplateArguments(
6752 FunctionTemplateDecl *FunctionTemplate,
6753 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6754 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6755 bool PartialOverloading,
6756 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6758 TemplateDeductionResult
6759 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6760 TemplateArgumentListInfo *ExplicitTemplateArgs,
6761 QualType ArgFunctionType,
6762 FunctionDecl *&Specialization,
6763 sema::TemplateDeductionInfo &Info,
6764 bool IsAddressOfFunction = false);
6766 TemplateDeductionResult
6767 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6769 CXXConversionDecl *&Specialization,
6770 sema::TemplateDeductionInfo &Info);
6772 TemplateDeductionResult
6773 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6774 TemplateArgumentListInfo *ExplicitTemplateArgs,
6775 FunctionDecl *&Specialization,
6776 sema::TemplateDeductionInfo &Info,
6777 bool IsAddressOfFunction = false);
6779 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6780 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6781 /// \brief Substitute Replacement for auto in TypeWithAuto
6782 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6783 QualType Replacement);
6784 /// \brief Completely replace the \c auto in \p TypeWithAuto by
6785 /// \p Replacement. This does not retain any \c auto type sugar.
6786 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6788 /// \brief Result type of DeduceAutoType.
6789 enum DeduceAutoResult {
6792 DAR_FailedAlreadyDiagnosed
6796 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6797 Optional<unsigned> DependentDeductionDepth = None);
6799 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6800 Optional<unsigned> DependentDeductionDepth = None);
6801 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6802 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6803 bool Diagnose = true);
6805 /// \brief Declare implicit deduction guides for a class template if we've
6806 /// not already done so.
6807 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6808 SourceLocation Loc);
6810 QualType DeduceTemplateSpecializationFromInitializer(
6811 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6812 const InitializationKind &Kind, MultiExprArg Init);
6814 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6815 QualType Type, TypeSourceInfo *TSI,
6816 SourceRange Range, bool DirectInit,
6819 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6821 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6822 SourceLocation ReturnLoc,
6823 Expr *&RetExpr, AutoType *AT);
6825 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6826 FunctionTemplateDecl *FT2,
6828 TemplatePartialOrderingContext TPOC,
6829 unsigned NumCallArguments1,
6830 unsigned NumCallArguments2);
6831 UnresolvedSetIterator
6832 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6833 TemplateSpecCandidateSet &FailedCandidates,
6835 const PartialDiagnostic &NoneDiag,
6836 const PartialDiagnostic &AmbigDiag,
6837 const PartialDiagnostic &CandidateDiag,
6838 bool Complain = true, QualType TargetType = QualType());
6840 ClassTemplatePartialSpecializationDecl *
6841 getMoreSpecializedPartialSpecialization(
6842 ClassTemplatePartialSpecializationDecl *PS1,
6843 ClassTemplatePartialSpecializationDecl *PS2,
6844 SourceLocation Loc);
6846 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6847 sema::TemplateDeductionInfo &Info);
6849 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6850 VarTemplatePartialSpecializationDecl *PS1,
6851 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6853 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6854 sema::TemplateDeductionInfo &Info);
6856 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6857 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6859 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6862 llvm::SmallBitVector &Used);
6863 void MarkDeducedTemplateParameters(
6864 const FunctionTemplateDecl *FunctionTemplate,
6865 llvm::SmallBitVector &Deduced) {
6866 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6868 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6869 const FunctionTemplateDecl *FunctionTemplate,
6870 llvm::SmallBitVector &Deduced);
6872 //===--------------------------------------------------------------------===//
6873 // C++ Template Instantiation
6876 MultiLevelTemplateArgumentList
6877 getTemplateInstantiationArgs(NamedDecl *D,
6878 const TemplateArgumentList *Innermost = nullptr,
6879 bool RelativeToPrimary = false,
6880 const FunctionDecl *Pattern = nullptr);
6882 /// A context in which code is being synthesized (where a source location
6883 /// alone is not sufficient to identify the context). This covers template
6884 /// instantiation and various forms of implicitly-generated functions.
6885 struct CodeSynthesisContext {
6886 /// \brief The kind of template instantiation we are performing
6887 enum SynthesisKind {
6888 /// We are instantiating a template declaration. The entity is
6889 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6890 TemplateInstantiation,
6892 /// We are instantiating a default argument for a template
6893 /// parameter. The Entity is the template parameter whose argument is
6894 /// being instantiated, the Template is the template, and the
6895 /// TemplateArgs/NumTemplateArguments provide the template arguments as
6897 DefaultTemplateArgumentInstantiation,
6899 /// We are instantiating a default argument for a function.
6900 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6901 /// provides the template arguments as specified.
6902 DefaultFunctionArgumentInstantiation,
6904 /// We are substituting explicit template arguments provided for
6905 /// a function template. The entity is a FunctionTemplateDecl.
6906 ExplicitTemplateArgumentSubstitution,
6908 /// We are substituting template argument determined as part of
6909 /// template argument deduction for either a class template
6910 /// partial specialization or a function template. The
6911 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6913 DeducedTemplateArgumentSubstitution,
6915 /// We are substituting prior template arguments into a new
6916 /// template parameter. The template parameter itself is either a
6917 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6918 PriorTemplateArgumentSubstitution,
6920 /// We are checking the validity of a default template argument that
6921 /// has been used when naming a template-id.
6922 DefaultTemplateArgumentChecking,
6924 /// We are instantiating the exception specification for a function
6925 /// template which was deferred until it was needed.
6926 ExceptionSpecInstantiation,
6928 /// We are declaring an implicit special member function.
6929 DeclaringSpecialMember,
6932 /// \brief Was the enclosing context a non-instantiation SFINAE context?
6933 bool SavedInNonInstantiationSFINAEContext;
6935 /// \brief The point of instantiation or synthesis within the source code.
6936 SourceLocation PointOfInstantiation;
6938 /// \brief The entity that is being synthesized.
6941 /// \brief The template (or partial specialization) in which we are
6942 /// performing the instantiation, for substitutions of prior template
6944 NamedDecl *Template;
6946 /// \brief The list of template arguments we are substituting, if they
6947 /// are not part of the entity.
6948 const TemplateArgument *TemplateArgs;
6950 // FIXME: Wrap this union around more members, or perhaps store the
6951 // kind-specific members in the RAII object owning the context.
6953 /// \brief The number of template arguments in TemplateArgs.
6954 unsigned NumTemplateArgs;
6956 /// \brief The special member being declared or defined.
6957 CXXSpecialMember SpecialMember;
6960 ArrayRef<TemplateArgument> template_arguments() const {
6961 assert(Kind != DeclaringSpecialMember);
6962 return {TemplateArgs, NumTemplateArgs};
6965 /// \brief The template deduction info object associated with the
6966 /// substitution or checking of explicit or deduced template arguments.
6967 sema::TemplateDeductionInfo *DeductionInfo;
6969 /// \brief The source range that covers the construct that cause
6970 /// the instantiation, e.g., the template-id that causes a class
6971 /// template instantiation.
6972 SourceRange InstantiationRange;
6974 CodeSynthesisContext()
6975 : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
6976 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6978 /// \brief Determines whether this template is an actual instantiation
6979 /// that should be counted toward the maximum instantiation depth.
6980 bool isInstantiationRecord() const;
6983 /// \brief List of active code synthesis contexts.
6985 /// This vector is treated as a stack. As synthesis of one entity requires
6986 /// synthesis of another, additional contexts are pushed onto the stack.
6987 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
6989 /// Specializations whose definitions are currently being instantiated.
6990 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
6992 /// Non-dependent types used in templates that have already been instantiated
6993 /// by some template instantiation.
6994 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
6996 /// \brief Extra modules inspected when performing a lookup during a template
6997 /// instantiation. Computed lazily.
6998 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7000 /// \brief Cache of additional modules that should be used for name lookup
7001 /// within the current template instantiation. Computed lazily; use
7002 /// getLookupModules() to get a complete set.
7003 llvm::DenseSet<Module*> LookupModulesCache;
7005 /// \brief Get the set of additional modules that should be checked during
7006 /// name lookup. A module and its imports become visible when instanting a
7007 /// template defined within it.
7008 llvm::DenseSet<Module*> &getLookupModules();
7010 /// \brief Map from the most recent declaration of a namespace to the most
7011 /// recent visible declaration of that namespace.
7012 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7014 /// \brief Whether we are in a SFINAE context that is not associated with
7015 /// template instantiation.
7017 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7018 /// of a template instantiation or template argument deduction.
7019 bool InNonInstantiationSFINAEContext;
7021 /// \brief The number of \p CodeSynthesisContexts that are not template
7022 /// instantiations and, therefore, should not be counted as part of the
7023 /// instantiation depth.
7025 /// When the instantiation depth reaches the user-configurable limit
7026 /// \p LangOptions::InstantiationDepth we will abort instantiation.
7027 // FIXME: Should we have a similar limit for other forms of synthesis?
7028 unsigned NonInstantiationEntries;
7030 /// \brief The depth of the context stack at the point when the most recent
7031 /// error or warning was produced.
7033 /// This value is used to suppress printing of redundant context stacks
7034 /// when there are multiple errors or warnings in the same instantiation.
7035 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7036 unsigned LastEmittedCodeSynthesisContextDepth = 0;
7038 /// \brief The current index into pack expansion arguments that will be
7039 /// used for substitution of parameter packs.
7041 /// The pack expansion index will be -1 to indicate that parameter packs
7042 /// should be instantiated as themselves. Otherwise, the index specifies
7043 /// which argument within the parameter pack will be used for substitution.
7044 int ArgumentPackSubstitutionIndex;
7046 /// \brief RAII object used to change the argument pack substitution index
7047 /// within a \c Sema object.
7049 /// See \c ArgumentPackSubstitutionIndex for more information.
7050 class ArgumentPackSubstitutionIndexRAII {
7052 int OldSubstitutionIndex;
7055 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7056 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7057 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7060 ~ArgumentPackSubstitutionIndexRAII() {
7061 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7065 friend class ArgumentPackSubstitutionRAII;
7067 /// \brief For each declaration that involved template argument deduction, the
7068 /// set of diagnostics that were suppressed during that template argument
7071 /// FIXME: Serialize this structure to the AST file.
7072 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7073 SuppressedDiagnosticsMap;
7074 SuppressedDiagnosticsMap SuppressedDiagnostics;
7076 /// \brief A stack object to be created when performing template
7079 /// Construction of an object of type \c InstantiatingTemplate
7080 /// pushes the current instantiation onto the stack of active
7081 /// instantiations. If the size of this stack exceeds the maximum
7082 /// number of recursive template instantiations, construction
7083 /// produces an error and evaluates true.
7085 /// Destruction of this object will pop the named instantiation off
7087 struct InstantiatingTemplate {
7088 /// \brief Note that we are instantiating a class template,
7089 /// function template, variable template, alias template,
7090 /// or a member thereof.
7091 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7093 SourceRange InstantiationRange = SourceRange());
7095 struct ExceptionSpecification {};
7096 /// \brief Note that we are instantiating an exception specification
7097 /// of a function template.
7098 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7099 FunctionDecl *Entity, ExceptionSpecification,
7100 SourceRange InstantiationRange = SourceRange());
7102 /// \brief Note that we are instantiating a default argument in a
7104 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7105 TemplateParameter Param, TemplateDecl *Template,
7106 ArrayRef<TemplateArgument> TemplateArgs,
7107 SourceRange InstantiationRange = SourceRange());
7109 /// \brief Note that we are substituting either explicitly-specified or
7110 /// deduced template arguments during function template argument deduction.
7111 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7112 FunctionTemplateDecl *FunctionTemplate,
7113 ArrayRef<TemplateArgument> TemplateArgs,
7114 CodeSynthesisContext::SynthesisKind Kind,
7115 sema::TemplateDeductionInfo &DeductionInfo,
7116 SourceRange InstantiationRange = SourceRange());
7118 /// \brief Note that we are instantiating as part of template
7119 /// argument deduction for a class template declaration.
7120 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7121 TemplateDecl *Template,
7122 ArrayRef<TemplateArgument> TemplateArgs,
7123 sema::TemplateDeductionInfo &DeductionInfo,
7124 SourceRange InstantiationRange = SourceRange());
7126 /// \brief Note that we are instantiating as part of template
7127 /// argument deduction for a class template partial
7129 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7130 ClassTemplatePartialSpecializationDecl *PartialSpec,
7131 ArrayRef<TemplateArgument> TemplateArgs,
7132 sema::TemplateDeductionInfo &DeductionInfo,
7133 SourceRange InstantiationRange = SourceRange());
7135 /// \brief Note that we are instantiating as part of template
7136 /// argument deduction for a variable template partial
7138 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7139 VarTemplatePartialSpecializationDecl *PartialSpec,
7140 ArrayRef<TemplateArgument> TemplateArgs,
7141 sema::TemplateDeductionInfo &DeductionInfo,
7142 SourceRange InstantiationRange = SourceRange());
7144 /// \brief Note that we are instantiating a default argument for a function
7146 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7148 ArrayRef<TemplateArgument> TemplateArgs,
7149 SourceRange InstantiationRange = SourceRange());
7151 /// \brief Note that we are substituting prior template arguments into a
7152 /// non-type parameter.
7153 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7154 NamedDecl *Template,
7155 NonTypeTemplateParmDecl *Param,
7156 ArrayRef<TemplateArgument> TemplateArgs,
7157 SourceRange InstantiationRange);
7159 /// \brief Note that we are substituting prior template arguments into a
7160 /// template template parameter.
7161 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7162 NamedDecl *Template,
7163 TemplateTemplateParmDecl *Param,
7164 ArrayRef<TemplateArgument> TemplateArgs,
7165 SourceRange InstantiationRange);
7167 /// \brief Note that we are checking the default template argument
7168 /// against the template parameter for a given template-id.
7169 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7170 TemplateDecl *Template,
7172 ArrayRef<TemplateArgument> TemplateArgs,
7173 SourceRange InstantiationRange);
7176 /// \brief Note that we have finished instantiating this template.
7179 ~InstantiatingTemplate() { Clear(); }
7181 /// \brief Determines whether we have exceeded the maximum
7182 /// recursive template instantiations.
7183 bool isInvalid() const { return Invalid; }
7185 /// \brief Determine whether we are already instantiating this
7186 /// specialization in some surrounding active instantiation.
7187 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7192 bool AlreadyInstantiating;
7193 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7194 SourceRange InstantiationRange);
7196 InstantiatingTemplate(
7197 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7198 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7199 Decl *Entity, NamedDecl *Template = nullptr,
7200 ArrayRef<TemplateArgument> TemplateArgs = None,
7201 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7203 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7205 InstantiatingTemplate&
7206 operator=(const InstantiatingTemplate&) = delete;
7209 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7210 void popCodeSynthesisContext();
7212 /// Determine whether we are currently performing template instantiation.
7213 bool inTemplateInstantiation() const {
7214 return CodeSynthesisContexts.size() > NonInstantiationEntries;
7217 void PrintContextStack() {
7218 if (!CodeSynthesisContexts.empty() &&
7219 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7220 PrintInstantiationStack();
7221 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7223 if (PragmaAttributeCurrentTargetDecl)
7224 PrintPragmaAttributeInstantiationPoint();
7226 void PrintInstantiationStack();
7228 void PrintPragmaAttributeInstantiationPoint();
7230 /// \brief Determines whether we are currently in a context where
7231 /// template argument substitution failures are not considered
7234 /// \returns An empty \c Optional if we're not in a SFINAE context.
7235 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7236 /// template-deduction context object, which can be used to capture
7237 /// diagnostics that will be suppressed.
7238 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7240 /// \brief Determines whether we are currently in a context that
7241 /// is not evaluated as per C++ [expr] p5.
7242 bool isUnevaluatedContext() const {
7243 assert(!ExprEvalContexts.empty() &&
7244 "Must be in an expression evaluation context");
7245 return ExprEvalContexts.back().isUnevaluated();
7248 /// \brief RAII class used to determine whether SFINAE has
7249 /// trapped any errors that occur during template argument
7253 unsigned PrevSFINAEErrors;
7254 bool PrevInNonInstantiationSFINAEContext;
7255 bool PrevAccessCheckingSFINAE;
7258 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7259 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7260 PrevInNonInstantiationSFINAEContext(
7261 SemaRef.InNonInstantiationSFINAEContext),
7262 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7264 if (!SemaRef.isSFINAEContext())
7265 SemaRef.InNonInstantiationSFINAEContext = true;
7266 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7270 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7271 SemaRef.InNonInstantiationSFINAEContext
7272 = PrevInNonInstantiationSFINAEContext;
7273 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7276 /// \brief Determine whether any SFINAE errors have been trapped.
7277 bool hasErrorOccurred() const {
7278 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7282 /// \brief RAII class used to indicate that we are performing provisional
7283 /// semantic analysis to determine the validity of a construct, so
7284 /// typo-correction and diagnostics in the immediate context (not within
7285 /// implicitly-instantiated templates) should be suppressed.
7286 class TentativeAnalysisScope {
7288 // FIXME: Using a SFINAETrap for this is a hack.
7290 bool PrevDisableTypoCorrection;
7292 explicit TentativeAnalysisScope(Sema &SemaRef)
7293 : SemaRef(SemaRef), Trap(SemaRef, true),
7294 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7295 SemaRef.DisableTypoCorrection = true;
7297 ~TentativeAnalysisScope() {
7298 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7302 /// \brief The current instantiation scope used to store local
7304 LocalInstantiationScope *CurrentInstantiationScope;
7306 /// \brief Tracks whether we are in a context where typo correction is
7308 bool DisableTypoCorrection;
7310 /// \brief The number of typos corrected by CorrectTypo.
7311 unsigned TyposCorrected;
7313 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7314 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7316 /// \brief A cache containing identifiers for which typo correction failed and
7317 /// their locations, so that repeated attempts to correct an identifier in a
7318 /// given location are ignored if typo correction already failed for it.
7319 IdentifierSourceLocations TypoCorrectionFailures;
7321 /// \brief Worker object for performing CFG-based warnings.
7322 sema::AnalysisBasedWarnings AnalysisWarnings;
7323 threadSafety::BeforeSet *ThreadSafetyDeclCache;
7325 /// \brief An entity for which implicit template instantiation is required.
7327 /// The source location associated with the declaration is the first place in
7328 /// the source code where the declaration was "used". It is not necessarily
7329 /// the point of instantiation (which will be either before or after the
7330 /// namespace-scope declaration that triggered this implicit instantiation),
7331 /// However, it is the location that diagnostics should generally refer to,
7332 /// because users will need to know what code triggered the instantiation.
7333 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7335 /// \brief The queue of implicit template instantiations that are required
7336 /// but have not yet been performed.
7337 std::deque<PendingImplicitInstantiation> PendingInstantiations;
7339 class SavePendingInstantiationsAndVTableUsesRAII {
7341 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7342 : S(S), Enabled(Enabled) {
7343 if (!Enabled) return;
7345 SavedPendingInstantiations.swap(S.PendingInstantiations);
7346 SavedVTableUses.swap(S.VTableUses);
7349 ~SavePendingInstantiationsAndVTableUsesRAII() {
7350 if (!Enabled) return;
7352 // Restore the set of pending vtables.
7353 assert(S.VTableUses.empty() &&
7354 "VTableUses should be empty before it is discarded.");
7355 S.VTableUses.swap(SavedVTableUses);
7357 // Restore the set of pending implicit instantiations.
7358 assert(S.PendingInstantiations.empty() &&
7359 "PendingInstantiations should be empty before it is discarded.");
7360 S.PendingInstantiations.swap(SavedPendingInstantiations);
7365 SmallVector<VTableUse, 16> SavedVTableUses;
7366 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7370 /// \brief The queue of implicit template instantiations that are required
7371 /// and must be performed within the current local scope.
7373 /// This queue is only used for member functions of local classes in
7374 /// templates, which must be instantiated in the same scope as their
7375 /// enclosing function, so that they can reference function-local
7376 /// types, static variables, enumerators, etc.
7377 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7379 class SavePendingLocalImplicitInstantiationsRAII {
7381 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7382 SavedPendingLocalImplicitInstantiations.swap(
7383 S.PendingLocalImplicitInstantiations);
7386 ~SavePendingLocalImplicitInstantiationsRAII() {
7387 assert(S.PendingLocalImplicitInstantiations.empty() &&
7388 "there shouldn't be any pending local implicit instantiations");
7389 SavedPendingLocalImplicitInstantiations.swap(
7390 S.PendingLocalImplicitInstantiations);
7395 std::deque<PendingImplicitInstantiation>
7396 SavedPendingLocalImplicitInstantiations;
7399 /// A helper class for building up ExtParameterInfos.
7400 class ExtParameterInfoBuilder {
7401 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7402 bool HasInteresting = false;
7405 /// Set the ExtParameterInfo for the parameter at the given index,
7407 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7408 assert(Infos.size() <= index);
7409 Infos.resize(index);
7410 Infos.push_back(info);
7412 if (!HasInteresting)
7413 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7416 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7417 /// ExtParameterInfo array we've built up.
7418 const FunctionProtoType::ExtParameterInfo *
7419 getPointerOrNull(unsigned numParams) {
7420 if (!HasInteresting) return nullptr;
7421 Infos.resize(numParams);
7422 return Infos.data();
7426 void PerformPendingInstantiations(bool LocalOnly = false);
7428 TypeSourceInfo *SubstType(TypeSourceInfo *T,
7429 const MultiLevelTemplateArgumentList &TemplateArgs,
7430 SourceLocation Loc, DeclarationName Entity,
7431 bool AllowDeducedTST = false);
7433 QualType SubstType(QualType T,
7434 const MultiLevelTemplateArgumentList &TemplateArgs,
7435 SourceLocation Loc, DeclarationName Entity);
7437 TypeSourceInfo *SubstType(TypeLoc TL,
7438 const MultiLevelTemplateArgumentList &TemplateArgs,
7439 SourceLocation Loc, DeclarationName Entity);
7441 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7442 const MultiLevelTemplateArgumentList &TemplateArgs,
7444 DeclarationName Entity,
7445 CXXRecordDecl *ThisContext,
7446 unsigned ThisTypeQuals);
7447 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7448 const MultiLevelTemplateArgumentList &Args);
7449 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7450 const MultiLevelTemplateArgumentList &TemplateArgs,
7451 int indexAdjustment,
7452 Optional<unsigned> NumExpansions,
7453 bool ExpectParameterPack);
7454 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7455 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7456 const MultiLevelTemplateArgumentList &TemplateArgs,
7457 SmallVectorImpl<QualType> &ParamTypes,
7458 SmallVectorImpl<ParmVarDecl *> *OutParams,
7459 ExtParameterInfoBuilder &ParamInfos);
7460 ExprResult SubstExpr(Expr *E,
7461 const MultiLevelTemplateArgumentList &TemplateArgs);
7463 /// \brief Substitute the given template arguments into a list of
7464 /// expressions, expanding pack expansions if required.
7466 /// \param Exprs The list of expressions to substitute into.
7468 /// \param IsCall Whether this is some form of call, in which case
7469 /// default arguments will be dropped.
7471 /// \param TemplateArgs The set of template arguments to substitute.
7473 /// \param Outputs Will receive all of the substituted arguments.
7475 /// \returns true if an error occurred, false otherwise.
7476 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7477 const MultiLevelTemplateArgumentList &TemplateArgs,
7478 SmallVectorImpl<Expr *> &Outputs);
7480 StmtResult SubstStmt(Stmt *S,
7481 const MultiLevelTemplateArgumentList &TemplateArgs);
7483 Decl *SubstDecl(Decl *D, DeclContext *Owner,
7484 const MultiLevelTemplateArgumentList &TemplateArgs);
7486 ExprResult SubstInitializer(Expr *E,
7487 const MultiLevelTemplateArgumentList &TemplateArgs,
7488 bool CXXDirectInit);
7491 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7492 CXXRecordDecl *Pattern,
7493 const MultiLevelTemplateArgumentList &TemplateArgs);
7496 InstantiateClass(SourceLocation PointOfInstantiation,
7497 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7498 const MultiLevelTemplateArgumentList &TemplateArgs,
7499 TemplateSpecializationKind TSK,
7500 bool Complain = true);
7502 bool InstantiateEnum(SourceLocation PointOfInstantiation,
7503 EnumDecl *Instantiation, EnumDecl *Pattern,
7504 const MultiLevelTemplateArgumentList &TemplateArgs,
7505 TemplateSpecializationKind TSK);
7507 bool InstantiateInClassInitializer(
7508 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7509 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7511 struct LateInstantiatedAttribute {
7512 const Attr *TmplAttr;
7513 LocalInstantiationScope *Scope;
7516 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7518 : TmplAttr(A), Scope(S), NewDecl(D)
7521 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7523 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7524 const Decl *Pattern, Decl *Inst,
7525 LateInstantiatedAttrVec *LateAttrs = nullptr,
7526 LocalInstantiationScope *OuterMostScope = nullptr);
7529 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7530 const Decl *Pattern, Decl *Inst,
7531 LateInstantiatedAttrVec *LateAttrs = nullptr,
7532 LocalInstantiationScope *OuterMostScope = nullptr);
7535 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7536 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7537 TemplateSpecializationKind TSK,
7538 bool Complain = true);
7540 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7541 CXXRecordDecl *Instantiation,
7542 const MultiLevelTemplateArgumentList &TemplateArgs,
7543 TemplateSpecializationKind TSK);
7545 void InstantiateClassTemplateSpecializationMembers(
7546 SourceLocation PointOfInstantiation,
7547 ClassTemplateSpecializationDecl *ClassTemplateSpec,
7548 TemplateSpecializationKind TSK);
7550 NestedNameSpecifierLoc
7551 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7552 const MultiLevelTemplateArgumentList &TemplateArgs);
7555 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7556 const MultiLevelTemplateArgumentList &TemplateArgs);
7558 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7560 const MultiLevelTemplateArgumentList &TemplateArgs);
7561 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7562 TemplateArgumentListInfo &Result,
7563 const MultiLevelTemplateArgumentList &TemplateArgs);
7565 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7566 FunctionDecl *Function);
7567 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7568 FunctionDecl *Function,
7569 bool Recursive = false,
7570 bool DefinitionRequired = false,
7571 bool AtEndOfTU = false);
7572 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7573 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7574 const TemplateArgumentList &TemplateArgList,
7575 const TemplateArgumentListInfo &TemplateArgsInfo,
7576 SmallVectorImpl<TemplateArgument> &Converted,
7577 SourceLocation PointOfInstantiation, void *InsertPos,
7578 LateInstantiatedAttrVec *LateAttrs = nullptr,
7579 LocalInstantiationScope *StartingScope = nullptr);
7580 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7581 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7582 const MultiLevelTemplateArgumentList &TemplateArgs);
7584 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7585 const MultiLevelTemplateArgumentList &TemplateArgs,
7586 LateInstantiatedAttrVec *LateAttrs,
7588 LocalInstantiationScope *StartingScope,
7589 bool InstantiatingVarTemplate = false);
7590 void InstantiateVariableInitializer(
7591 VarDecl *Var, VarDecl *OldVar,
7592 const MultiLevelTemplateArgumentList &TemplateArgs);
7593 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7594 VarDecl *Var, bool Recursive = false,
7595 bool DefinitionRequired = false,
7596 bool AtEndOfTU = false);
7597 void InstantiateStaticDataMemberDefinition(
7598 SourceLocation PointOfInstantiation,
7600 bool Recursive = false,
7601 bool DefinitionRequired = false);
7603 void InstantiateMemInitializers(CXXConstructorDecl *New,
7604 const CXXConstructorDecl *Tmpl,
7605 const MultiLevelTemplateArgumentList &TemplateArgs);
7607 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7608 const MultiLevelTemplateArgumentList &TemplateArgs);
7609 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7610 const MultiLevelTemplateArgumentList &TemplateArgs);
7612 // Objective-C declarations.
7613 enum ObjCContainerKind {
7620 OCK_CategoryImplementation
7622 ObjCContainerKind getObjCContainerKind() const;
7624 DeclResult actOnObjCTypeParam(Scope *S,
7625 ObjCTypeParamVariance variance,
7626 SourceLocation varianceLoc,
7628 IdentifierInfo *paramName,
7629 SourceLocation paramLoc,
7630 SourceLocation colonLoc,
7631 ParsedType typeBound);
7633 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7634 ArrayRef<Decl *> typeParams,
7635 SourceLocation rAngleLoc);
7636 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7638 Decl *ActOnStartClassInterface(Scope *S,
7639 SourceLocation AtInterfaceLoc,
7640 IdentifierInfo *ClassName,
7641 SourceLocation ClassLoc,
7642 ObjCTypeParamList *typeParamList,
7643 IdentifierInfo *SuperName,
7644 SourceLocation SuperLoc,
7645 ArrayRef<ParsedType> SuperTypeArgs,
7646 SourceRange SuperTypeArgsRange,
7647 Decl * const *ProtoRefs,
7648 unsigned NumProtoRefs,
7649 const SourceLocation *ProtoLocs,
7650 SourceLocation EndProtoLoc,
7651 AttributeList *AttrList);
7653 void ActOnSuperClassOfClassInterface(Scope *S,
7654 SourceLocation AtInterfaceLoc,
7655 ObjCInterfaceDecl *IDecl,
7656 IdentifierInfo *ClassName,
7657 SourceLocation ClassLoc,
7658 IdentifierInfo *SuperName,
7659 SourceLocation SuperLoc,
7660 ArrayRef<ParsedType> SuperTypeArgs,
7661 SourceRange SuperTypeArgsRange);
7663 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7664 SmallVectorImpl<SourceLocation> &ProtocolLocs,
7665 IdentifierInfo *SuperName,
7666 SourceLocation SuperLoc);
7668 Decl *ActOnCompatibilityAlias(
7669 SourceLocation AtCompatibilityAliasLoc,
7670 IdentifierInfo *AliasName, SourceLocation AliasLocation,
7671 IdentifierInfo *ClassName, SourceLocation ClassLocation);
7673 bool CheckForwardProtocolDeclarationForCircularDependency(
7674 IdentifierInfo *PName,
7675 SourceLocation &PLoc, SourceLocation PrevLoc,
7676 const ObjCList<ObjCProtocolDecl> &PList);
7678 Decl *ActOnStartProtocolInterface(
7679 SourceLocation AtProtoInterfaceLoc,
7680 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7681 Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7682 const SourceLocation *ProtoLocs,
7683 SourceLocation EndProtoLoc,
7684 AttributeList *AttrList);
7686 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7687 IdentifierInfo *ClassName,
7688 SourceLocation ClassLoc,
7689 ObjCTypeParamList *typeParamList,
7690 IdentifierInfo *CategoryName,
7691 SourceLocation CategoryLoc,
7692 Decl * const *ProtoRefs,
7693 unsigned NumProtoRefs,
7694 const SourceLocation *ProtoLocs,
7695 SourceLocation EndProtoLoc,
7696 AttributeList *AttrList);
7698 Decl *ActOnStartClassImplementation(
7699 SourceLocation AtClassImplLoc,
7700 IdentifierInfo *ClassName, SourceLocation ClassLoc,
7701 IdentifierInfo *SuperClassname,
7702 SourceLocation SuperClassLoc);
7704 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7705 IdentifierInfo *ClassName,
7706 SourceLocation ClassLoc,
7707 IdentifierInfo *CatName,
7708 SourceLocation CatLoc);
7710 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7711 ArrayRef<Decl *> Decls);
7713 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7714 IdentifierInfo **IdentList,
7715 SourceLocation *IdentLocs,
7716 ArrayRef<ObjCTypeParamList *> TypeParamLists,
7719 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7720 ArrayRef<IdentifierLocPair> IdentList,
7721 AttributeList *attrList);
7723 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7724 ArrayRef<IdentifierLocPair> ProtocolId,
7725 SmallVectorImpl<Decl *> &Protocols);
7727 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7728 SourceLocation ProtocolLoc,
7729 IdentifierInfo *TypeArgId,
7730 SourceLocation TypeArgLoc,
7731 bool SelectProtocolFirst = false);
7733 /// Given a list of identifiers (and their locations), resolve the
7734 /// names to either Objective-C protocol qualifiers or type
7735 /// arguments, as appropriate.
7736 void actOnObjCTypeArgsOrProtocolQualifiers(
7738 ParsedType baseType,
7739 SourceLocation lAngleLoc,
7740 ArrayRef<IdentifierInfo *> identifiers,
7741 ArrayRef<SourceLocation> identifierLocs,
7742 SourceLocation rAngleLoc,
7743 SourceLocation &typeArgsLAngleLoc,
7744 SmallVectorImpl<ParsedType> &typeArgs,
7745 SourceLocation &typeArgsRAngleLoc,
7746 SourceLocation &protocolLAngleLoc,
7747 SmallVectorImpl<Decl *> &protocols,
7748 SourceLocation &protocolRAngleLoc,
7749 bool warnOnIncompleteProtocols);
7751 /// Build a an Objective-C protocol-qualified 'id' type where no
7752 /// base type was specified.
7753 TypeResult actOnObjCProtocolQualifierType(
7754 SourceLocation lAngleLoc,
7755 ArrayRef<Decl *> protocols,
7756 ArrayRef<SourceLocation> protocolLocs,
7757 SourceLocation rAngleLoc);
7759 /// Build a specialized and/or protocol-qualified Objective-C type.
7760 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7763 ParsedType BaseType,
7764 SourceLocation TypeArgsLAngleLoc,
7765 ArrayRef<ParsedType> TypeArgs,
7766 SourceLocation TypeArgsRAngleLoc,
7767 SourceLocation ProtocolLAngleLoc,
7768 ArrayRef<Decl *> Protocols,
7769 ArrayRef<SourceLocation> ProtocolLocs,
7770 SourceLocation ProtocolRAngleLoc);
7772 /// Build an Objective-C type parameter type.
7773 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7774 SourceLocation ProtocolLAngleLoc,
7775 ArrayRef<ObjCProtocolDecl *> Protocols,
7776 ArrayRef<SourceLocation> ProtocolLocs,
7777 SourceLocation ProtocolRAngleLoc,
7778 bool FailOnError = false);
7780 /// Build an Objective-C object pointer type.
7781 QualType BuildObjCObjectType(QualType BaseType,
7783 SourceLocation TypeArgsLAngleLoc,
7784 ArrayRef<TypeSourceInfo *> TypeArgs,
7785 SourceLocation TypeArgsRAngleLoc,
7786 SourceLocation ProtocolLAngleLoc,
7787 ArrayRef<ObjCProtocolDecl *> Protocols,
7788 ArrayRef<SourceLocation> ProtocolLocs,
7789 SourceLocation ProtocolRAngleLoc,
7790 bool FailOnError = false);
7792 /// Check the application of the Objective-C '__kindof' qualifier to
7794 bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7796 /// Ensure attributes are consistent with type.
7797 /// \param [in, out] Attributes The attributes to check; they will
7798 /// be modified to be consistent with \p PropertyTy.
7799 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7801 unsigned &Attributes,
7802 bool propertyInPrimaryClass);
7804 /// Process the specified property declaration and create decls for the
7805 /// setters and getters as needed.
7806 /// \param property The property declaration being processed
7807 void ProcessPropertyDecl(ObjCPropertyDecl *property);
7810 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7811 ObjCPropertyDecl *SuperProperty,
7812 const IdentifierInfo *Name,
7813 bool OverridingProtocolProperty);
7815 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7816 ObjCInterfaceDecl *ID);
7818 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7819 ArrayRef<Decl *> allMethods = None,
7820 ArrayRef<DeclGroupPtrTy> allTUVars = None);
7822 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7823 SourceLocation LParenLoc,
7824 FieldDeclarator &FD, ObjCDeclSpec &ODS,
7825 Selector GetterSel, Selector SetterSel,
7826 tok::ObjCKeywordKind MethodImplKind,
7827 DeclContext *lexicalDC = nullptr);
7829 Decl *ActOnPropertyImplDecl(Scope *S,
7830 SourceLocation AtLoc,
7831 SourceLocation PropertyLoc,
7833 IdentifierInfo *PropertyId,
7834 IdentifierInfo *PropertyIvar,
7835 SourceLocation PropertyIvarLoc,
7836 ObjCPropertyQueryKind QueryKind);
7838 enum ObjCSpecialMethodKind {
7844 OSMK_NonRetainingInit
7847 struct ObjCArgInfo {
7848 IdentifierInfo *Name;
7849 SourceLocation NameLoc;
7850 // The Type is null if no type was specified, and the DeclSpec is invalid
7853 ObjCDeclSpec DeclSpec;
7855 /// ArgAttrs - Attribute list for this argument.
7856 AttributeList *ArgAttrs;
7859 Decl *ActOnMethodDeclaration(
7861 SourceLocation BeginLoc, // location of the + or -.
7862 SourceLocation EndLoc, // location of the ; or {.
7863 tok::TokenKind MethodType,
7864 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7865 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7866 // optional arguments. The number of types/arguments is obtained
7867 // from the Sel.getNumArgs().
7868 ObjCArgInfo *ArgInfo,
7869 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7870 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7871 bool isVariadic, bool MethodDefinition);
7873 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7874 const ObjCObjectPointerType *OPT,
7876 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7879 bool CheckARCMethodDecl(ObjCMethodDecl *method);
7880 bool inferObjCARCLifetime(ValueDecl *decl);
7883 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7885 SourceLocation OpLoc,
7886 DeclarationName MemberName,
7887 SourceLocation MemberLoc,
7888 SourceLocation SuperLoc, QualType SuperType,
7892 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7893 IdentifierInfo &propertyName,
7894 SourceLocation receiverNameLoc,
7895 SourceLocation propertyNameLoc);
7897 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7899 /// \brief Describes the kind of message expression indicated by a message
7900 /// send that starts with an identifier.
7901 enum ObjCMessageKind {
7902 /// \brief The message is sent to 'super'.
7904 /// \brief The message is an instance message.
7905 ObjCInstanceMessage,
7906 /// \brief The message is a class message, and the identifier is a type
7911 ObjCMessageKind getObjCMessageKind(Scope *S,
7912 IdentifierInfo *Name,
7913 SourceLocation NameLoc,
7915 bool HasTrailingDot,
7916 ParsedType &ReceiverType);
7918 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7920 SourceLocation LBracLoc,
7921 ArrayRef<SourceLocation> SelectorLocs,
7922 SourceLocation RBracLoc,
7925 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7926 QualType ReceiverType,
7927 SourceLocation SuperLoc,
7929 ObjCMethodDecl *Method,
7930 SourceLocation LBracLoc,
7931 ArrayRef<SourceLocation> SelectorLocs,
7932 SourceLocation RBracLoc,
7934 bool isImplicit = false);
7936 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7937 bool isSuperReceiver,
7940 ObjCMethodDecl *Method,
7943 ExprResult ActOnClassMessage(Scope *S,
7944 ParsedType Receiver,
7946 SourceLocation LBracLoc,
7947 ArrayRef<SourceLocation> SelectorLocs,
7948 SourceLocation RBracLoc,
7951 ExprResult BuildInstanceMessage(Expr *Receiver,
7952 QualType ReceiverType,
7953 SourceLocation SuperLoc,
7955 ObjCMethodDecl *Method,
7956 SourceLocation LBracLoc,
7957 ArrayRef<SourceLocation> SelectorLocs,
7958 SourceLocation RBracLoc,
7960 bool isImplicit = false);
7962 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7963 QualType ReceiverType,
7966 ObjCMethodDecl *Method,
7969 ExprResult ActOnInstanceMessage(Scope *S,
7972 SourceLocation LBracLoc,
7973 ArrayRef<SourceLocation> SelectorLocs,
7974 SourceLocation RBracLoc,
7977 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7978 ObjCBridgeCastKind Kind,
7979 SourceLocation BridgeKeywordLoc,
7980 TypeSourceInfo *TSInfo,
7983 ExprResult ActOnObjCBridgedCast(Scope *S,
7984 SourceLocation LParenLoc,
7985 ObjCBridgeCastKind Kind,
7986 SourceLocation BridgeKeywordLoc,
7988 SourceLocation RParenLoc,
7991 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7993 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7995 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7998 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7999 QualType DestType, QualType SrcType,
8000 ObjCInterfaceDecl *&RelatedClass,
8001 ObjCMethodDecl *&ClassMethod,
8002 ObjCMethodDecl *&InstanceMethod,
8003 TypedefNameDecl *&TDNDecl,
8004 bool CfToNs, bool Diagnose = true);
8006 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8007 QualType DestType, QualType SrcType,
8008 Expr *&SrcExpr, bool Diagnose = true);
8010 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8011 bool Diagnose = true);
8013 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8015 /// \brief Check whether the given new method is a valid override of the
8016 /// given overridden method, and set any properties that should be inherited.
8017 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8018 const ObjCMethodDecl *Overridden);
8020 /// \brief Describes the compatibility of a result type with its method.
8021 enum ResultTypeCompatibilityKind {
8027 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8028 ObjCInterfaceDecl *CurrentClass,
8029 ResultTypeCompatibilityKind RTC);
8031 enum PragmaOptionsAlignKind {
8032 POAK_Native, // #pragma options align=native
8033 POAK_Natural, // #pragma options align=natural
8034 POAK_Packed, // #pragma options align=packed
8035 POAK_Power, // #pragma options align=power
8036 POAK_Mac68k, // #pragma options align=mac68k
8037 POAK_Reset // #pragma options align=reset
8040 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8041 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8042 SourceLocation PragmaLoc);
8044 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8045 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8046 StringRef SlotLabel, Expr *Alignment);
8048 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8049 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8051 /// ActOnPragmaMSComment - Called on well formed
8052 /// \#pragma comment(kind, "arg").
8053 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8056 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8057 /// pointers_to_members(representation method[, general purpose
8058 /// representation]).
8059 void ActOnPragmaMSPointersToMembers(
8060 LangOptions::PragmaMSPointersToMembersKind Kind,
8061 SourceLocation PragmaLoc);
8063 /// \brief Called on well formed \#pragma vtordisp().
8064 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8065 SourceLocation PragmaLoc,
8066 MSVtorDispAttr::Mode Value);
8068 enum PragmaSectionKind {
8075 bool UnifySection(StringRef SectionName,
8077 DeclaratorDecl *TheDecl);
8078 bool UnifySection(StringRef SectionName,
8080 SourceLocation PragmaSectionLocation);
8082 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8083 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8084 PragmaMsStackAction Action,
8085 llvm::StringRef StackSlotLabel,
8086 StringLiteral *SegmentName,
8087 llvm::StringRef PragmaName);
8089 /// \brief Called on well formed \#pragma section().
8090 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8091 int SectionFlags, StringLiteral *SegmentName);
8093 /// \brief Called on well-formed \#pragma init_seg().
8094 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8095 StringLiteral *SegmentName);
8097 /// \brief Called on #pragma clang __debug dump II
8098 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8100 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8101 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8104 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8105 void ActOnPragmaUnused(const Token &Identifier,
8107 SourceLocation PragmaLoc);
8109 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8110 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8111 SourceLocation PragmaLoc);
8113 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8114 SourceLocation Loc);
8115 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8117 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8118 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8119 SourceLocation PragmaLoc,
8120 SourceLocation WeakNameLoc);
8122 /// ActOnPragmaRedefineExtname - Called on well formed
8123 /// \#pragma redefine_extname oldname newname.
8124 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8125 IdentifierInfo* AliasName,
8126 SourceLocation PragmaLoc,
8127 SourceLocation WeakNameLoc,
8128 SourceLocation AliasNameLoc);
8130 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8131 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8132 IdentifierInfo* AliasName,
8133 SourceLocation PragmaLoc,
8134 SourceLocation WeakNameLoc,
8135 SourceLocation AliasNameLoc);
8137 /// ActOnPragmaFPContract - Called on well formed
8138 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8139 /// \#pragma clang fp contract
8140 void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8142 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8143 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8144 void AddAlignmentAttributesForRecord(RecordDecl *RD);
8146 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8147 void AddMsStructLayoutForRecord(RecordDecl *RD);
8149 /// FreePackedContext - Deallocate and null out PackContext.
8150 void FreePackedContext();
8152 /// PushNamespaceVisibilityAttr - Note that we've entered a
8153 /// namespace with a visibility attribute.
8154 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8155 SourceLocation Loc);
8157 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8158 /// add an appropriate visibility attribute.
8159 void AddPushedVisibilityAttribute(Decl *RD);
8161 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8162 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8163 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8165 /// FreeVisContext - Deallocate and null out VisContext.
8166 void FreeVisContext();
8168 /// AddCFAuditedAttribute - Check whether we're currently within
8169 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8170 /// the appropriate attribute.
8171 void AddCFAuditedAttribute(Decl *D);
8173 /// \brief Called on well-formed '\#pragma clang attribute push'.
8174 void ActOnPragmaAttributePush(AttributeList &Attribute,
8175 SourceLocation PragmaLoc,
8176 attr::ParsedSubjectMatchRuleSet Rules);
8178 /// \brief Called on well-formed '\#pragma clang attribute pop'.
8179 void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8181 /// \brief Adds the attributes that have been specified using the
8182 /// '\#pragma clang attribute push' directives to the given declaration.
8183 void AddPragmaAttributes(Scope *S, Decl *D);
8185 void DiagnoseUnterminatedPragmaAttribute();
8187 /// \brief Called on well formed \#pragma clang optimize.
8188 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8190 /// \brief Get the location for the currently active "\#pragma clang optimize
8191 /// off". If this location is invalid, then the state of the pragma is "on".
8192 SourceLocation getOptimizeOffPragmaLocation() const {
8193 return OptimizeOffPragmaLocation;
8196 /// \brief Only called on function definitions; if there is a pragma in scope
8197 /// with the effect of a range-based optnone, consider marking the function
8198 /// with attribute optnone.
8199 void AddRangeBasedOptnone(FunctionDecl *FD);
8201 /// \brief Adds the 'optnone' attribute to the function declaration if there
8202 /// are no conflicts; Loc represents the location causing the 'optnone'
8203 /// attribute to be added (usually because of a pragma).
8204 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8206 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8207 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8208 unsigned SpellingListIndex, bool IsPackExpansion);
8209 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8210 unsigned SpellingListIndex, bool IsPackExpansion);
8212 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8214 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8215 unsigned SpellingListIndex);
8217 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8219 void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8220 unsigned SpellingListIndex);
8222 /// AddAlignValueAttr - Adds an align_value attribute to a particular
8224 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8225 unsigned SpellingListIndex);
8227 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8229 void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8230 Expr *MinBlocks, unsigned SpellingListIndex);
8232 /// AddModeAttr - Adds a mode attribute to a particular declaration.
8233 void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8234 unsigned SpellingListIndex, bool InInstantiation = false);
8236 void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8237 ParameterABI ABI, unsigned SpellingListIndex);
8239 void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8240 unsigned SpellingListIndex, bool isNSConsumed,
8241 bool isTemplateInstantiation);
8243 //===--------------------------------------------------------------------===//
8244 // C++ Coroutines TS
8246 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8247 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8248 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8250 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8251 bool IsImplicit = false);
8252 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8253 UnresolvedLookupExpr* Lookup);
8254 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8255 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8256 bool IsImplicit = false);
8257 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8258 VarDecl *buildCoroutinePromise(SourceLocation Loc);
8259 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8261 //===--------------------------------------------------------------------===//
8262 // OpenCL extensions.
8265 std::string CurrOpenCLExtension;
8266 /// Extensions required by an OpenCL type.
8267 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8268 /// Extensions required by an OpenCL declaration.
8269 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8271 llvm::StringRef getCurrentOpenCLExtension() const {
8272 return CurrOpenCLExtension;
8274 void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8275 CurrOpenCLExtension = Ext;
8278 /// \brief Set OpenCL extensions for a type which can only be used when these
8279 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8280 /// \param Exts A space separated list of OpenCL extensions.
8281 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8283 /// \brief Set OpenCL extensions for a declaration which can only be
8284 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8286 /// \param Exts A space separated list of OpenCL extensions.
8287 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8289 /// \brief Set current OpenCL extensions for a type which can only be used
8290 /// when these OpenCL extensions are enabled. If current OpenCL extension is
8291 /// empty, do nothing.
8292 void setCurrentOpenCLExtensionForType(QualType T);
8294 /// \brief Set current OpenCL extensions for a declaration which
8295 /// can only be used when these OpenCL extensions are enabled. If current
8296 /// OpenCL extension is empty, do nothing.
8297 void setCurrentOpenCLExtensionForDecl(Decl *FD);
8299 bool isOpenCLDisabledDecl(Decl *FD);
8301 /// \brief Check if type \p T corresponding to declaration specifier \p DS
8302 /// is disabled due to required OpenCL extensions being disabled. If so,
8303 /// emit diagnostics.
8304 /// \return true if type is disabled.
8305 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8307 /// \brief Check if declaration \p D used by expression \p E
8308 /// is disabled due to required OpenCL extensions being disabled. If so,
8309 /// emit diagnostics.
8310 /// \return true if type is disabled.
8311 bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8313 //===--------------------------------------------------------------------===//
8314 // OpenMP directives and clauses.
8317 void *VarDataSharingAttributesStack;
8318 /// Set to true inside '#pragma omp declare target' region.
8319 bool IsInOpenMPDeclareTargetContext = false;
8320 /// \brief Initialization of data-sharing attributes stack.
8321 void InitDataSharingAttributesStack();
8322 void DestroyDataSharingAttributesStack();
8324 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8325 bool StrictlyPositive = true);
8326 /// Returns OpenMP nesting level for current directive.
8327 unsigned getOpenMPNestingLevel() const;
8329 /// Checks if a type or a declaration is disabled due to the owning extension
8330 /// being disabled, and emits diagnostic messages if it is disabled.
8331 /// \param D type or declaration to be checked.
8332 /// \param DiagLoc source location for the diagnostic message.
8333 /// \param DiagInfo information to be emitted for the diagnostic message.
8334 /// \param SrcRange source range of the declaration.
8335 /// \param Map maps type or declaration to the extensions.
8336 /// \param Selector selects diagnostic message: 0 for type and 1 for
8338 /// \return true if the type or declaration is disabled.
8339 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8340 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8341 MapT &Map, unsigned Selector = 0,
8342 SourceRange SrcRange = SourceRange());
8345 /// \brief Return true if the provided declaration \a VD should be captured by
8347 /// \param Level Relative level of nested OpenMP construct for that the check
8349 bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8351 /// \brief Check if the specified variable is used in one of the private
8352 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8354 VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8355 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8356 ExprObjectKind OK, SourceLocation Loc);
8358 /// \brief Check if the specified variable is used in 'private' clause.
8359 /// \param Level Relative level of nested OpenMP construct for that the check
8361 bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8363 /// \brief Check if the specified variable is captured by 'target' directive.
8364 /// \param Level Relative level of nested OpenMP construct for that the check
8366 bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8368 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8370 /// \brief Called on start of new data sharing attribute block.
8371 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8372 const DeclarationNameInfo &DirName, Scope *CurScope,
8373 SourceLocation Loc);
8374 /// \brief Start analysis of clauses.
8375 void StartOpenMPClause(OpenMPClauseKind K);
8376 /// \brief End analysis of clauses.
8377 void EndOpenMPClause();
8378 /// \brief Called on end of data sharing attribute block.
8379 void EndOpenMPDSABlock(Stmt *CurDirective);
8381 /// \brief Check if the current region is an OpenMP loop region and if it is,
8382 /// mark loop control variable, used in \p Init for loop initialization, as
8383 /// private by default.
8384 /// \param Init First part of the for loop.
8385 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8387 // OpenMP directives and clauses.
8388 /// \brief Called on correct id-expression from the '#pragma omp
8390 ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8391 CXXScopeSpec &ScopeSpec,
8392 const DeclarationNameInfo &Id);
8393 /// \brief Called on well-formed '#pragma omp threadprivate'.
8394 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8396 ArrayRef<Expr *> VarList);
8397 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8398 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8400 ArrayRef<Expr *> VarList);
8401 /// \brief Check if the specified type is allowed to be used in 'omp declare
8402 /// reduction' construct.
8403 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8404 TypeResult ParsedType);
8405 /// \brief Called on start of '#pragma omp declare reduction'.
8406 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8407 Scope *S, DeclContext *DC, DeclarationName Name,
8408 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8409 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8410 /// \brief Initialize declare reduction construct initializer.
8411 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8412 /// \brief Finish current declare reduction construct initializer.
8413 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8414 /// \brief Initialize declare reduction construct initializer.
8415 void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8416 /// \brief Finish current declare reduction construct initializer.
8417 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8418 /// \brief Called at the end of '#pragma omp declare reduction'.
8419 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8420 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8422 /// Called on the start of target region i.e. '#pragma omp declare target'.
8423 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8424 /// Called at the end of target region i.e. '#pragme omp end declare target'.
8425 void ActOnFinishOpenMPDeclareTargetDirective();
8426 /// Called on correct id-expression from the '#pragma omp declare target'.
8427 void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8428 const DeclarationNameInfo &Id,
8429 OMPDeclareTargetDeclAttr::MapTypeTy MT,
8430 NamedDeclSetType &SameDirectiveDecls);
8431 /// Check declaration inside target region.
8432 void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8433 /// Return true inside OpenMP target region.
8434 bool isInOpenMPDeclareTargetContext() const {
8435 return IsInOpenMPDeclareTargetContext;
8438 /// Return the number of captured regions created for an OpenMP directive.
8439 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8441 /// \brief Initialization of captured region for OpenMP region.
8442 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8443 /// \brief End of OpenMP region.
8445 /// \param S Statement associated with the current OpenMP region.
8446 /// \param Clauses List of clauses for the current OpenMP region.
8448 /// \returns Statement for finished OpenMP region.
8449 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8450 StmtResult ActOnOpenMPExecutableDirective(
8451 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8452 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8453 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8454 /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8455 /// of the associated statement.
8456 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8458 SourceLocation StartLoc,
8459 SourceLocation EndLoc);
8460 /// \brief Called on well-formed '\#pragma omp simd' after parsing
8461 /// of the associated statement.
8462 StmtResult ActOnOpenMPSimdDirective(
8463 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8464 SourceLocation EndLoc,
8465 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8466 /// \brief Called on well-formed '\#pragma omp for' after parsing
8467 /// of the associated statement.
8468 StmtResult ActOnOpenMPForDirective(
8469 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8470 SourceLocation EndLoc,
8471 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8472 /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8473 /// of the associated statement.
8474 StmtResult ActOnOpenMPForSimdDirective(
8475 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8476 SourceLocation EndLoc,
8477 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8478 /// \brief Called on well-formed '\#pragma omp sections' after parsing
8479 /// of the associated statement.
8480 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8481 Stmt *AStmt, SourceLocation StartLoc,
8482 SourceLocation EndLoc);
8483 /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8484 /// associated statement.
8485 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8486 SourceLocation EndLoc);
8487 /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8488 /// associated statement.
8489 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8490 Stmt *AStmt, SourceLocation StartLoc,
8491 SourceLocation EndLoc);
8492 /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8493 /// associated statement.
8494 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8495 SourceLocation EndLoc);
8496 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8497 /// associated statement.
8498 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8499 ArrayRef<OMPClause *> Clauses,
8500 Stmt *AStmt, SourceLocation StartLoc,
8501 SourceLocation EndLoc);
8502 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8503 /// of the associated statement.
8504 StmtResult ActOnOpenMPParallelForDirective(
8505 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8506 SourceLocation EndLoc,
8507 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8508 /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8509 /// parsing of the associated statement.
8510 StmtResult ActOnOpenMPParallelForSimdDirective(
8511 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8512 SourceLocation EndLoc,
8513 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8514 /// \brief Called on well-formed '\#pragma omp parallel sections' after
8515 /// parsing of the associated statement.
8516 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8518 SourceLocation StartLoc,
8519 SourceLocation EndLoc);
8520 /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8521 /// associated statement.
8522 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8523 Stmt *AStmt, SourceLocation StartLoc,
8524 SourceLocation EndLoc);
8525 /// \brief Called on well-formed '\#pragma omp taskyield'.
8526 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8527 SourceLocation EndLoc);
8528 /// \brief Called on well-formed '\#pragma omp barrier'.
8529 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8530 SourceLocation EndLoc);
8531 /// \brief Called on well-formed '\#pragma omp taskwait'.
8532 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8533 SourceLocation EndLoc);
8534 /// \brief Called on well-formed '\#pragma omp taskgroup'.
8535 StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8536 SourceLocation EndLoc);
8537 /// \brief Called on well-formed '\#pragma omp flush'.
8538 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8539 SourceLocation StartLoc,
8540 SourceLocation EndLoc);
8541 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8542 /// associated statement.
8543 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8544 Stmt *AStmt, SourceLocation StartLoc,
8545 SourceLocation EndLoc);
8546 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8547 /// associated statement.
8548 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8549 Stmt *AStmt, SourceLocation StartLoc,
8550 SourceLocation EndLoc);
8551 /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8552 /// associated statement.
8553 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8554 Stmt *AStmt, SourceLocation StartLoc,
8555 SourceLocation EndLoc);
8556 /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8557 /// the associated statement.
8558 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8559 Stmt *AStmt, SourceLocation StartLoc,
8560 SourceLocation EndLoc);
8561 /// \brief Called on well-formed '\#pragma omp target enter data' after
8562 /// parsing of the associated statement.
8563 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8564 SourceLocation StartLoc,
8565 SourceLocation EndLoc);
8566 /// \brief Called on well-formed '\#pragma omp target exit data' after
8567 /// parsing of the associated statement.
8568 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8569 SourceLocation StartLoc,
8570 SourceLocation EndLoc);
8571 /// \brief Called on well-formed '\#pragma omp target parallel' after
8572 /// parsing of the associated statement.
8573 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8575 SourceLocation StartLoc,
8576 SourceLocation EndLoc);
8577 /// \brief Called on well-formed '\#pragma omp target parallel for' after
8578 /// parsing of the associated statement.
8579 StmtResult ActOnOpenMPTargetParallelForDirective(
8580 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8581 SourceLocation EndLoc,
8582 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8583 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8584 /// associated statement.
8585 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8586 Stmt *AStmt, SourceLocation StartLoc,
8587 SourceLocation EndLoc);
8588 /// \brief Called on well-formed '\#pragma omp cancellation point'.
8590 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8591 SourceLocation EndLoc,
8592 OpenMPDirectiveKind CancelRegion);
8593 /// \brief Called on well-formed '\#pragma omp cancel'.
8594 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8595 SourceLocation StartLoc,
8596 SourceLocation EndLoc,
8597 OpenMPDirectiveKind CancelRegion);
8598 /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8599 /// associated statement.
8600 StmtResult ActOnOpenMPTaskLoopDirective(
8601 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8602 SourceLocation EndLoc,
8603 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8604 /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8605 /// the associated statement.
8606 StmtResult ActOnOpenMPTaskLoopSimdDirective(
8607 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8608 SourceLocation EndLoc,
8609 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8610 /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8611 /// of the associated statement.
8612 StmtResult ActOnOpenMPDistributeDirective(
8613 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8614 SourceLocation EndLoc,
8615 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8616 /// \brief Called on well-formed '\#pragma omp target update'.
8617 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8618 SourceLocation StartLoc,
8619 SourceLocation EndLoc);
8620 /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8621 /// parsing of the associated statement.
8622 StmtResult ActOnOpenMPDistributeParallelForDirective(
8623 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8624 SourceLocation EndLoc,
8625 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8626 /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8627 /// after parsing of the associated statement.
8628 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8629 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8630 SourceLocation EndLoc,
8631 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8632 /// \brief Called on well-formed '\#pragma omp distribute simd' after
8633 /// parsing of the associated statement.
8634 StmtResult ActOnOpenMPDistributeSimdDirective(
8635 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8636 SourceLocation EndLoc,
8637 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8638 /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8639 /// parsing of the associated statement.
8640 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8641 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8642 SourceLocation EndLoc,
8643 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8644 /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8645 /// the associated statement.
8646 StmtResult ActOnOpenMPTargetSimdDirective(
8647 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8648 SourceLocation EndLoc,
8649 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8650 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8651 /// the associated statement.
8652 StmtResult ActOnOpenMPTeamsDistributeDirective(
8653 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8654 SourceLocation EndLoc,
8655 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8656 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8657 /// of the associated statement.
8658 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8659 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8660 SourceLocation EndLoc,
8661 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8662 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8663 /// after parsing of the associated statement.
8664 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8665 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8666 SourceLocation EndLoc,
8667 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8668 /// Called on well-formed '\#pragma omp teams distribute parallel for'
8669 /// after parsing of the associated statement.
8670 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8671 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8672 SourceLocation EndLoc,
8673 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8674 /// Called on well-formed '\#pragma omp target teams' after parsing of the
8675 /// associated statement.
8676 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8678 SourceLocation StartLoc,
8679 SourceLocation EndLoc);
8680 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8681 /// of the associated statement.
8682 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8683 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8684 SourceLocation EndLoc,
8685 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8686 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8687 /// after parsing of the associated statement.
8688 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8689 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8690 SourceLocation EndLoc,
8691 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8692 /// Called on well-formed '\#pragma omp target teams distribute parallel for
8693 /// simd' after parsing of the associated statement.
8694 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8695 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8696 SourceLocation EndLoc,
8697 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8698 /// Called on well-formed '\#pragma omp target teams distribute simd' after
8699 /// parsing of the associated statement.
8700 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8701 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8702 SourceLocation EndLoc,
8703 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8705 /// Checks correctness of linear modifiers.
8706 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8707 SourceLocation LinLoc);
8708 /// Checks that the specified declaration matches requirements for the linear
8710 bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8711 OpenMPLinearClauseKind LinKind, QualType Type);
8713 /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8714 /// the associated method/function.
8715 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8716 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8717 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8718 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8719 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8721 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8723 SourceLocation StartLoc,
8724 SourceLocation LParenLoc,
8725 SourceLocation EndLoc);
8726 /// \brief Called on well-formed 'if' clause.
8727 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8728 Expr *Condition, SourceLocation StartLoc,
8729 SourceLocation LParenLoc,
8730 SourceLocation NameModifierLoc,
8731 SourceLocation ColonLoc,
8732 SourceLocation EndLoc);
8733 /// \brief Called on well-formed 'final' clause.
8734 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8735 SourceLocation LParenLoc,
8736 SourceLocation EndLoc);
8737 /// \brief Called on well-formed 'num_threads' clause.
8738 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8739 SourceLocation StartLoc,
8740 SourceLocation LParenLoc,
8741 SourceLocation EndLoc);
8742 /// \brief Called on well-formed 'safelen' clause.
8743 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8744 SourceLocation StartLoc,
8745 SourceLocation LParenLoc,
8746 SourceLocation EndLoc);
8747 /// \brief Called on well-formed 'simdlen' clause.
8748 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8749 SourceLocation LParenLoc,
8750 SourceLocation EndLoc);
8751 /// \brief Called on well-formed 'collapse' clause.
8752 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8753 SourceLocation StartLoc,
8754 SourceLocation LParenLoc,
8755 SourceLocation EndLoc);
8756 /// \brief Called on well-formed 'ordered' clause.
8758 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8759 SourceLocation LParenLoc = SourceLocation(),
8760 Expr *NumForLoops = nullptr);
8761 /// \brief Called on well-formed 'grainsize' clause.
8762 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8763 SourceLocation LParenLoc,
8764 SourceLocation EndLoc);
8765 /// \brief Called on well-formed 'num_tasks' clause.
8766 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8767 SourceLocation LParenLoc,
8768 SourceLocation EndLoc);
8769 /// \brief Called on well-formed 'hint' clause.
8770 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8771 SourceLocation LParenLoc,
8772 SourceLocation EndLoc);
8774 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8776 SourceLocation ArgumentLoc,
8777 SourceLocation StartLoc,
8778 SourceLocation LParenLoc,
8779 SourceLocation EndLoc);
8780 /// \brief Called on well-formed 'default' clause.
8781 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8782 SourceLocation KindLoc,
8783 SourceLocation StartLoc,
8784 SourceLocation LParenLoc,
8785 SourceLocation EndLoc);
8786 /// \brief Called on well-formed 'proc_bind' clause.
8787 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8788 SourceLocation KindLoc,
8789 SourceLocation StartLoc,
8790 SourceLocation LParenLoc,
8791 SourceLocation EndLoc);
8793 OMPClause *ActOnOpenMPSingleExprWithArgClause(
8794 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8795 SourceLocation StartLoc, SourceLocation LParenLoc,
8796 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8797 SourceLocation EndLoc);
8798 /// \brief Called on well-formed 'schedule' clause.
8799 OMPClause *ActOnOpenMPScheduleClause(
8800 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8801 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8802 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8803 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8805 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8806 SourceLocation EndLoc);
8807 /// \brief Called on well-formed 'nowait' clause.
8808 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8809 SourceLocation EndLoc);
8810 /// \brief Called on well-formed 'untied' clause.
8811 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8812 SourceLocation EndLoc);
8813 /// \brief Called on well-formed 'mergeable' clause.
8814 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8815 SourceLocation EndLoc);
8816 /// \brief Called on well-formed 'read' clause.
8817 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8818 SourceLocation EndLoc);
8819 /// \brief Called on well-formed 'write' clause.
8820 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8821 SourceLocation EndLoc);
8822 /// \brief Called on well-formed 'update' clause.
8823 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8824 SourceLocation EndLoc);
8825 /// \brief Called on well-formed 'capture' clause.
8826 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8827 SourceLocation EndLoc);
8828 /// \brief Called on well-formed 'seq_cst' clause.
8829 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8830 SourceLocation EndLoc);
8831 /// \brief Called on well-formed 'threads' clause.
8832 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8833 SourceLocation EndLoc);
8834 /// \brief Called on well-formed 'simd' clause.
8835 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8836 SourceLocation EndLoc);
8837 /// \brief Called on well-formed 'nogroup' clause.
8838 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8839 SourceLocation EndLoc);
8841 OMPClause *ActOnOpenMPVarListClause(
8842 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8843 SourceLocation StartLoc, SourceLocation LParenLoc,
8844 SourceLocation ColonLoc, SourceLocation EndLoc,
8845 CXXScopeSpec &ReductionIdScopeSpec,
8846 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8847 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8848 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8849 SourceLocation DepLinMapLoc);
8850 /// \brief Called on well-formed 'private' clause.
8851 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8852 SourceLocation StartLoc,
8853 SourceLocation LParenLoc,
8854 SourceLocation EndLoc);
8855 /// \brief Called on well-formed 'firstprivate' clause.
8856 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8857 SourceLocation StartLoc,
8858 SourceLocation LParenLoc,
8859 SourceLocation EndLoc);
8860 /// \brief Called on well-formed 'lastprivate' clause.
8861 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8862 SourceLocation StartLoc,
8863 SourceLocation LParenLoc,
8864 SourceLocation EndLoc);
8865 /// \brief Called on well-formed 'shared' clause.
8866 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8867 SourceLocation StartLoc,
8868 SourceLocation LParenLoc,
8869 SourceLocation EndLoc);
8870 /// \brief Called on well-formed 'reduction' clause.
8871 OMPClause *ActOnOpenMPReductionClause(
8872 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8873 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8874 CXXScopeSpec &ReductionIdScopeSpec,
8875 const DeclarationNameInfo &ReductionId,
8876 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8877 /// \brief Called on well-formed 'linear' clause.
8879 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8880 SourceLocation StartLoc, SourceLocation LParenLoc,
8881 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8882 SourceLocation ColonLoc, SourceLocation EndLoc);
8883 /// \brief Called on well-formed 'aligned' clause.
8884 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8886 SourceLocation StartLoc,
8887 SourceLocation LParenLoc,
8888 SourceLocation ColonLoc,
8889 SourceLocation EndLoc);
8890 /// \brief Called on well-formed 'copyin' clause.
8891 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8892 SourceLocation StartLoc,
8893 SourceLocation LParenLoc,
8894 SourceLocation EndLoc);
8895 /// \brief Called on well-formed 'copyprivate' clause.
8896 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8897 SourceLocation StartLoc,
8898 SourceLocation LParenLoc,
8899 SourceLocation EndLoc);
8900 /// \brief Called on well-formed 'flush' pseudo clause.
8901 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8902 SourceLocation StartLoc,
8903 SourceLocation LParenLoc,
8904 SourceLocation EndLoc);
8905 /// \brief Called on well-formed 'depend' clause.
8907 ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8908 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8909 SourceLocation StartLoc, SourceLocation LParenLoc,
8910 SourceLocation EndLoc);
8911 /// \brief Called on well-formed 'device' clause.
8912 OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8913 SourceLocation LParenLoc,
8914 SourceLocation EndLoc);
8915 /// \brief Called on well-formed 'map' clause.
8917 ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8918 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8919 SourceLocation MapLoc, SourceLocation ColonLoc,
8920 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8921 SourceLocation LParenLoc, SourceLocation EndLoc);
8922 /// \brief Called on well-formed 'num_teams' clause.
8923 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8924 SourceLocation LParenLoc,
8925 SourceLocation EndLoc);
8926 /// \brief Called on well-formed 'thread_limit' clause.
8927 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8928 SourceLocation StartLoc,
8929 SourceLocation LParenLoc,
8930 SourceLocation EndLoc);
8931 /// \brief Called on well-formed 'priority' clause.
8932 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8933 SourceLocation LParenLoc,
8934 SourceLocation EndLoc);
8935 /// \brief Called on well-formed 'dist_schedule' clause.
8936 OMPClause *ActOnOpenMPDistScheduleClause(
8937 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8938 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8939 SourceLocation CommaLoc, SourceLocation EndLoc);
8940 /// \brief Called on well-formed 'defaultmap' clause.
8941 OMPClause *ActOnOpenMPDefaultmapClause(
8942 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8943 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8944 SourceLocation KindLoc, SourceLocation EndLoc);
8945 /// \brief Called on well-formed 'to' clause.
8946 OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8947 SourceLocation StartLoc,
8948 SourceLocation LParenLoc,
8949 SourceLocation EndLoc);
8950 /// \brief Called on well-formed 'from' clause.
8951 OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8952 SourceLocation StartLoc,
8953 SourceLocation LParenLoc,
8954 SourceLocation EndLoc);
8955 /// Called on well-formed 'use_device_ptr' clause.
8956 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8957 SourceLocation StartLoc,
8958 SourceLocation LParenLoc,
8959 SourceLocation EndLoc);
8960 /// Called on well-formed 'is_device_ptr' clause.
8961 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8962 SourceLocation StartLoc,
8963 SourceLocation LParenLoc,
8964 SourceLocation EndLoc);
8966 /// \brief The kind of conversion being performed.
8967 enum CheckedConversionKind {
8968 /// \brief An implicit conversion.
8969 CCK_ImplicitConversion,
8970 /// \brief A C-style cast.
8972 /// \brief A functional-style cast.
8974 /// \brief A cast other than a C-style cast.
8978 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8979 /// cast. If there is already an implicit cast, merge into the existing one.
8980 /// If isLvalue, the result of the cast is an lvalue.
8981 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8982 ExprValueKind VK = VK_RValue,
8983 const CXXCastPath *BasePath = nullptr,
8984 CheckedConversionKind CCK
8985 = CCK_ImplicitConversion);
8987 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8988 /// to the conversion from scalar type ScalarTy to the Boolean type.
8989 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8991 /// IgnoredValueConversions - Given that an expression's result is
8992 /// syntactically ignored, perform any conversions that are
8994 ExprResult IgnoredValueConversions(Expr *E);
8996 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8997 // functions and arrays to their respective pointers (C99 6.3.2.1).
8998 ExprResult UsualUnaryConversions(Expr *E);
9000 /// CallExprUnaryConversions - a special case of an unary conversion
9001 /// performed on a function designator of a call expression.
9002 ExprResult CallExprUnaryConversions(Expr *E);
9004 // DefaultFunctionArrayConversion - converts functions and arrays
9005 // to their respective pointers (C99 6.3.2.1).
9006 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9008 // DefaultFunctionArrayLvalueConversion - converts functions and
9009 // arrays to their respective pointers and performs the
9010 // lvalue-to-rvalue conversion.
9011 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9012 bool Diagnose = true);
9014 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9015 // the operand. This is DefaultFunctionArrayLvalueConversion,
9016 // except that it assumes the operand isn't of function or array
9018 ExprResult DefaultLvalueConversion(Expr *E);
9020 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9021 // do not have a prototype. Integer promotions are performed on each
9022 // argument, and arguments that have type float are promoted to double.
9023 ExprResult DefaultArgumentPromotion(Expr *E);
9025 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9026 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9027 /// we don't have xvalues there.
9028 ExprResult TemporaryMaterializationConversion(Expr *E);
9030 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9031 enum VariadicCallType {
9035 VariadicConstructor,
9036 VariadicDoesNotApply
9039 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9040 const FunctionProtoType *Proto,
9043 // Used for determining in which context a type is allowed to be passed to a
9053 // Determines which VarArgKind fits an expression.
9054 VarArgKind isValidVarArgType(const QualType &Ty);
9056 /// Check to see if the given expression is a valid argument to a variadic
9057 /// function, issuing a diagnostic if not.
9058 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9060 /// Check to see if a given expression could have '.c_str()' called on it.
9061 bool hasCStrMethod(const Expr *E);
9063 /// GatherArgumentsForCall - Collector argument expressions for various
9064 /// form of call prototypes.
9065 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9066 const FunctionProtoType *Proto,
9067 unsigned FirstParam, ArrayRef<Expr *> Args,
9068 SmallVectorImpl<Expr *> &AllArgs,
9069 VariadicCallType CallType = VariadicDoesNotApply,
9070 bool AllowExplicit = false,
9071 bool IsListInitialization = false);
9073 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9074 // will create a runtime trap if the resulting type is not a POD type.
9075 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9076 FunctionDecl *FDecl);
9078 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9079 // operands and then handles various conversions that are common to binary
9080 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9081 // routine returns the first non-arithmetic type found. The client is
9082 // responsible for emitting appropriate error diagnostics.
9083 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9084 bool IsCompAssign = false);
9086 /// AssignConvertType - All of the 'assignment' semantic checks return this
9087 /// enum to indicate whether the assignment was allowed. These checks are
9088 /// done for simple assignments, as well as initialization, return from
9089 /// function, argument passing, etc. The query is phrased in terms of a
9090 /// source and destination type.
9091 enum AssignConvertType {
9092 /// Compatible - the types are compatible according to the standard.
9095 /// PointerToInt - The assignment converts a pointer to an int, which we
9096 /// accept as an extension.
9099 /// IntToPointer - The assignment converts an int to a pointer, which we
9100 /// accept as an extension.
9103 /// FunctionVoidPointer - The assignment is between a function pointer and
9104 /// void*, which the standard doesn't allow, but we accept as an extension.
9105 FunctionVoidPointer,
9107 /// IncompatiblePointer - The assignment is between two pointers types that
9108 /// are not compatible, but we accept them as an extension.
9109 IncompatiblePointer,
9111 /// IncompatiblePointerSign - The assignment is between two pointers types
9112 /// which point to integers which have a different sign, but are otherwise
9113 /// identical. This is a subset of the above, but broken out because it's by
9114 /// far the most common case of incompatible pointers.
9115 IncompatiblePointerSign,
9117 /// CompatiblePointerDiscardsQualifiers - The assignment discards
9118 /// c/v/r qualifiers, which we accept as an extension.
9119 CompatiblePointerDiscardsQualifiers,
9121 /// IncompatiblePointerDiscardsQualifiers - The assignment
9122 /// discards qualifiers that we don't permit to be discarded,
9123 /// like address spaces.
9124 IncompatiblePointerDiscardsQualifiers,
9126 /// IncompatibleNestedPointerQualifiers - The assignment is between two
9127 /// nested pointer types, and the qualifiers other than the first two
9128 /// levels differ e.g. char ** -> const char **, but we accept them as an
9130 IncompatibleNestedPointerQualifiers,
9132 /// IncompatibleVectors - The assignment is between two vector types that
9133 /// have the same size, which we accept as an extension.
9134 IncompatibleVectors,
9136 /// IntToBlockPointer - The assignment converts an int to a block
9137 /// pointer. We disallow this.
9140 /// IncompatibleBlockPointer - The assignment is between two block
9141 /// pointers types that are not compatible.
9142 IncompatibleBlockPointer,
9144 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9145 /// id type and something else (that is incompatible with it). For example,
9146 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9147 IncompatibleObjCQualifiedId,
9149 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9150 /// object with __weak qualifier.
9151 IncompatibleObjCWeakRef,
9153 /// Incompatible - We reject this conversion outright, it is invalid to
9154 /// represent it in the AST.
9158 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9159 /// assignment conversion type specified by ConvTy. This returns true if the
9160 /// conversion was invalid or false if the conversion was accepted.
9161 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9163 QualType DstType, QualType SrcType,
9164 Expr *SrcExpr, AssignmentAction Action,
9165 bool *Complained = nullptr);
9167 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9168 /// enum. If AllowMask is true, then we also allow the complement of a valid
9169 /// value, to be used as a mask.
9170 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9171 bool AllowMask) const;
9173 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9174 /// integer not in the range of enum values.
9175 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9178 /// CheckAssignmentConstraints - Perform type checking for assignment,
9179 /// argument passing, variable initialization, and function return values.
9181 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9185 /// Check assignment constraints and optionally prepare for a conversion of
9186 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9188 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9191 bool ConvertRHS = true);
9193 /// Check assignment constraints for an assignment of RHS to LHSType.
9195 /// \param LHSType The destination type for the assignment.
9196 /// \param RHS The source expression for the assignment.
9197 /// \param Diagnose If \c true, diagnostics may be produced when checking
9198 /// for assignability. If a diagnostic is produced, \p RHS will be
9199 /// set to ExprError(). Note that this function may still return
9200 /// without producing a diagnostic, even for an invalid assignment.
9201 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9202 /// in an audited Core Foundation API and does not need to be checked
9203 /// for ARC retain issues.
9204 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9205 /// conversions necessary to perform the assignment. If \c false,
9206 /// \p Diagnose must also be \c false.
9207 AssignConvertType CheckSingleAssignmentConstraints(
9208 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9209 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9211 // \brief If the lhs type is a transparent union, check whether we
9212 // can initialize the transparent union with the given expression.
9213 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9216 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9218 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9220 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9221 AssignmentAction Action,
9222 bool AllowExplicit = false);
9223 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9224 AssignmentAction Action,
9226 ImplicitConversionSequence& ICS);
9227 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9228 const ImplicitConversionSequence& ICS,
9229 AssignmentAction Action,
9230 CheckedConversionKind CCK
9231 = CCK_ImplicitConversion);
9232 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9233 const StandardConversionSequence& SCS,
9234 AssignmentAction Action,
9235 CheckedConversionKind CCK);
9237 /// the following "Check" methods will return a valid/converted QualType
9238 /// or a null QualType (indicating an error diagnostic was issued).
9240 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9241 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9243 QualType CheckPointerToMemberOperands( // C++ 5.5
9244 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9245 SourceLocation OpLoc, bool isIndirect);
9246 QualType CheckMultiplyDivideOperands( // C99 6.5.5
9247 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9249 QualType CheckRemainderOperands( // C99 6.5.5
9250 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9251 bool IsCompAssign = false);
9252 QualType CheckAdditionOperands( // C99 6.5.6
9253 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9254 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9255 QualType CheckSubtractionOperands( // C99 6.5.6
9256 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9257 QualType* CompLHSTy = nullptr);
9258 QualType CheckShiftOperands( // C99 6.5.7
9259 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9260 BinaryOperatorKind Opc, bool IsCompAssign = false);
9261 QualType CheckCompareOperands( // C99 6.5.8/9
9262 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9263 BinaryOperatorKind Opc, bool isRelational);
9264 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9265 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9266 BinaryOperatorKind Opc);
9267 QualType CheckLogicalOperands( // C99 6.5.[13,14]
9268 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9269 BinaryOperatorKind Opc);
9270 // CheckAssignmentOperands is used for both simple and compound assignment.
9271 // For simple assignment, pass both expressions and a null converted type.
9272 // For compound assignment, pass both expressions and the converted type.
9273 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9274 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9276 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9277 UnaryOperatorKind Opcode, Expr *Op);
9278 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9279 BinaryOperatorKind Opcode,
9280 Expr *LHS, Expr *RHS);
9281 ExprResult checkPseudoObjectRValue(Expr *E);
9282 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9284 QualType CheckConditionalOperands( // C99 6.5.15
9285 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9286 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9287 QualType CXXCheckConditionalOperands( // C++ 5.16
9288 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9289 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9290 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9291 bool ConvertArgs = true);
9292 QualType FindCompositePointerType(SourceLocation Loc,
9293 ExprResult &E1, ExprResult &E2,
9294 bool ConvertArgs = true) {
9295 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9296 QualType Composite =
9297 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9303 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9304 SourceLocation QuestionLoc);
9306 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9307 SourceLocation QuestionLoc);
9309 void DiagnoseAlwaysNonNullPointer(Expr *E,
9310 Expr::NullPointerConstantKind NullType,
9311 bool IsEqual, SourceRange Range);
9313 /// type checking for vector binary operators.
9314 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9315 SourceLocation Loc, bool IsCompAssign,
9316 bool AllowBothBool, bool AllowBoolConversion);
9317 QualType GetSignedVectorType(QualType V);
9318 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9319 SourceLocation Loc, bool isRelational);
9320 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9321 SourceLocation Loc);
9323 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9324 bool isLaxVectorConversion(QualType srcType, QualType destType);
9326 /// type checking declaration initializers (C99 6.7.8)
9327 bool CheckForConstantInitializer(Expr *e, QualType t);
9329 // type checking C++ declaration initializers (C++ [dcl.init]).
9331 /// ReferenceCompareResult - Expresses the result of comparing two
9332 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9333 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9334 enum ReferenceCompareResult {
9335 /// Ref_Incompatible - The two types are incompatible, so direct
9336 /// reference binding is not possible.
9337 Ref_Incompatible = 0,
9338 /// Ref_Related - The two types are reference-related, which means
9339 /// that their unqualified forms (T1 and T2) are either the same
9340 /// or T1 is a base class of T2.
9342 /// Ref_Compatible - The two types are reference-compatible.
9346 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9347 QualType T1, QualType T2,
9348 bool &DerivedToBase,
9349 bool &ObjCConversion,
9350 bool &ObjCLifetimeConversion);
9352 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9353 Expr *CastExpr, CastKind &CastKind,
9354 ExprValueKind &VK, CXXCastPath &Path);
9356 /// \brief Force an expression with unknown-type to an expression of the
9358 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9360 /// \brief Type-check an expression that's being passed to an
9361 /// __unknown_anytype parameter.
9362 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9363 Expr *result, QualType ¶mType);
9365 // CheckVectorCast - check type constraints for vectors.
9366 // Since vectors are an extension, there are no C standard reference for this.
9367 // We allow casting between vectors and integer datatypes of the same size.
9368 // returns true if the cast is invalid
9369 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9372 /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9373 /// implicit casts if necessary.
9374 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9376 // CheckExtVectorCast - check type constraints for extended vectors.
9377 // Since vectors are an extension, there are no C standard reference for this.
9378 // We allow casting between vectors and integer datatypes of the same size,
9379 // or vectors and the element type of that vector.
9380 // returns the cast expr
9381 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9384 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9385 SourceLocation LParenLoc,
9387 SourceLocation RParenLoc);
9389 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9391 /// \brief Checks for invalid conversions and casts between
9392 /// retainable pointers and other pointer kinds for ARC and Weak.
9393 ARCConversionResult CheckObjCConversion(SourceRange castRange,
9394 QualType castType, Expr *&op,
9395 CheckedConversionKind CCK,
9396 bool Diagnose = true,
9397 bool DiagnoseCFAudited = false,
9398 BinaryOperatorKind Opc = BO_PtrMemD
9401 Expr *stripARCUnbridgedCast(Expr *e);
9402 void diagnoseARCUnbridgedCast(Expr *e);
9404 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9407 /// checkRetainCycles - Check whether an Objective-C message send
9408 /// might create an obvious retain cycle.
9409 void checkRetainCycles(ObjCMessageExpr *msg);
9410 void checkRetainCycles(Expr *receiver, Expr *argument);
9411 void checkRetainCycles(VarDecl *Var, Expr *Init);
9413 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9414 /// to weak/__unsafe_unretained type.
9415 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9417 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9418 /// to weak/__unsafe_unretained expression.
9419 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9421 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9422 /// \param Method - May be null.
9423 /// \param [out] ReturnType - The return type of the send.
9424 /// \return true iff there were any incompatible types.
9425 bool CheckMessageArgumentTypes(QualType ReceiverType,
9426 MultiExprArg Args, Selector Sel,
9427 ArrayRef<SourceLocation> SelectorLocs,
9428 ObjCMethodDecl *Method, bool isClassMessage,
9429 bool isSuperMessage,
9430 SourceLocation lbrac, SourceLocation rbrac,
9431 SourceRange RecRange,
9432 QualType &ReturnType, ExprValueKind &VK);
9434 /// \brief Determine the result of a message send expression based on
9435 /// the type of the receiver, the method expected to receive the message,
9436 /// and the form of the message send.
9437 QualType getMessageSendResultType(QualType ReceiverType,
9438 ObjCMethodDecl *Method,
9439 bool isClassMessage, bool isSuperMessage);
9441 /// \brief If the given expression involves a message send to a method
9442 /// with a related result type, emit a note describing what happened.
9443 void EmitRelatedResultTypeNote(const Expr *E);
9445 /// \brief Given that we had incompatible pointer types in a return
9446 /// statement, check whether we're in a method with a related result
9447 /// type, and if so, emit a note describing what happened.
9448 void EmitRelatedResultTypeNoteForReturn(QualType destType);
9450 class ConditionResult {
9452 FullExprArg Condition;
9458 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9460 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9461 HasKnownValue(IsConstexpr && Condition.get() &&
9462 !Condition.get()->isValueDependent()),
9463 KnownValue(HasKnownValue &&
9464 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9465 explicit ConditionResult(bool Invalid)
9466 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9467 HasKnownValue(false), KnownValue(false) {}
9470 ConditionResult() : ConditionResult(false) {}
9471 bool isInvalid() const { return Invalid; }
9472 std::pair<VarDecl *, Expr *> get() const {
9473 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9476 llvm::Optional<bool> getKnownValue() const {
9482 static ConditionResult ConditionError() { return ConditionResult(true); }
9484 enum class ConditionKind {
9485 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9486 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9487 Switch ///< An integral condition for a 'switch' statement.
9490 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9491 Expr *SubExpr, ConditionKind CK);
9493 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9494 SourceLocation StmtLoc,
9497 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9499 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9500 SourceLocation StmtLoc,
9502 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9504 /// CheckBooleanCondition - Diagnose problems involving the use of
9505 /// the given expression as a boolean condition (e.g. in an if
9506 /// statement). Also performs the standard function and array
9507 /// decays, possibly changing the input variable.
9509 /// \param Loc - A location associated with the condition, e.g. the
9511 /// \return true iff there were any errors
9512 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9513 bool IsConstexpr = false);
9515 /// DiagnoseAssignmentAsCondition - Given that an expression is
9516 /// being used as a boolean condition, warn if it's an assignment.
9517 void DiagnoseAssignmentAsCondition(Expr *E);
9519 /// \brief Redundant parentheses over an equality comparison can indicate
9520 /// that the user intended an assignment used as condition.
9521 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9523 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9524 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9526 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9527 /// the specified width and sign. If an overflow occurs, detect it and emit
9528 /// the specified diagnostic.
9529 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9530 unsigned NewWidth, bool NewSign,
9531 SourceLocation Loc, unsigned DiagID);
9533 /// Checks that the Objective-C declaration is declared in the global scope.
9534 /// Emits an error and marks the declaration as invalid if it's not declared
9535 /// in the global scope.
9536 bool CheckObjCDeclScope(Decl *D);
9538 /// \brief Abstract base class used for diagnosing integer constant
9539 /// expression violations.
9540 class VerifyICEDiagnoser {
9544 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9546 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9547 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9548 virtual ~VerifyICEDiagnoser() { }
9551 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9552 /// and reports the appropriate diagnostics. Returns false on success.
9553 /// Can optionally return the value of the expression.
9554 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9555 VerifyICEDiagnoser &Diagnoser,
9556 bool AllowFold = true);
9557 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9559 bool AllowFold = true);
9560 ExprResult VerifyIntegerConstantExpression(Expr *E,
9561 llvm::APSInt *Result = nullptr);
9563 /// VerifyBitField - verifies that a bit field expression is an ICE and has
9564 /// the correct width, and that the field type is valid.
9565 /// Returns false on success.
9566 /// Can optionally return whether the bit-field is of width 0
9567 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9568 QualType FieldTy, bool IsMsStruct,
9569 Expr *BitWidth, bool *ZeroWidth = nullptr);
9572 unsigned ForceCUDAHostDeviceDepth = 0;
9575 /// Increments our count of the number of times we've seen a pragma forcing
9576 /// functions to be __host__ __device__. So long as this count is greater
9577 /// than zero, all functions encountered will be __host__ __device__.
9578 void PushForceCUDAHostDevice();
9580 /// Decrements our count of the number of times we've seen a pragma forcing
9581 /// functions to be __host__ __device__. Returns false if the count is 0
9582 /// before incrementing, so you can emit an error.
9583 bool PopForceCUDAHostDevice();
9585 /// Diagnostics that are emitted only if we discover that the given function
9586 /// must be codegen'ed. Because handling these correctly adds overhead to
9587 /// compilation, this is currently only enabled for CUDA compilations.
9588 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9589 std::vector<PartialDiagnosticAt>>
9592 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
9593 /// key in a hashtable, both the FD and location are hashed.
9594 struct FunctionDeclAndLoc {
9595 CanonicalDeclPtr<FunctionDecl> FD;
9599 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9600 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
9601 /// same deferred diag twice.
9602 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9604 /// An inverse call graph, mapping known-emitted functions to one of their
9605 /// known-emitted callers (plus the location of the call).
9607 /// Functions that we can tell a priori must be emitted aren't added to this
9609 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9610 /* Caller = */ FunctionDeclAndLoc>
9611 CUDAKnownEmittedFns;
9613 /// A partial call graph maintained during CUDA compilation to support
9614 /// deferred diagnostics.
9616 /// Functions are only added here if, at the time they're considered, they are
9617 /// not known-emitted. As soon as we discover that a function is
9618 /// known-emitted, we remove it and everything it transitively calls from this
9619 /// set and add those functions to CUDAKnownEmittedFns.
9620 llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9621 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9625 /// Diagnostic builder for CUDA errors which may or may not be deferred.
9627 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9628 /// which are not allowed to appear inside __device__ functions and are
9629 /// allowed to appear in __host__ __device__ functions only if the host+device
9630 /// function is never codegen'ed.
9632 /// To handle this, we use the notion of "deferred diagnostics", where we
9633 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9635 /// This class lets you emit either a regular diagnostic, a deferred
9636 /// diagnostic, or no diagnostic at all, according to an argument you pass to
9637 /// its constructor, thus simplifying the process of creating these "maybe
9638 /// deferred" diagnostics.
9639 class CUDADiagBuilder {
9642 /// Emit no diagnostics.
9644 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9646 /// Emit the diagnostic immediately, and, if it's a warning or error, also
9647 /// emit a call stack showing how this function can be reached by an a
9648 /// priori known-emitted function.
9649 K_ImmediateWithCallStack,
9650 /// Create a deferred diagnostic, which is emitted only if the function
9651 /// it's attached to is codegen'ed. Also emit a call stack as with
9652 /// K_ImmediateWithCallStack.
9656 CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9657 FunctionDecl *Fn, Sema &S);
9660 /// Convertible to bool: True if we immediately emitted an error, false if
9661 /// we didn't emit an error or we created a deferred error.
9665 /// if (CUDADiagBuilder(...) << foo << bar)
9666 /// return ExprError();
9668 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9669 /// want to use these instead of creating a CUDADiagBuilder yourself.
9670 operator bool() const { return ImmediateDiag.hasValue(); }
9672 template <typename T>
9673 friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9675 if (Diag.ImmediateDiag.hasValue())
9676 *Diag.ImmediateDiag << Value;
9677 else if (Diag.PartialDiag.hasValue())
9678 *Diag.PartialDiag << Value;
9689 // Invariant: At most one of these Optionals has a value.
9690 // FIXME: Switch these to a Variant once that exists.
9691 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9692 llvm::Optional<PartialDiagnostic> PartialDiag;
9695 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9696 /// is "used as device code".
9698 /// - If CurContext is a __host__ function, does not emit any diagnostics.
9699 /// - If CurContext is a __device__ or __global__ function, emits the
9700 /// diagnostics immediately.
9701 /// - If CurContext is a __host__ __device__ function and we are compiling for
9702 /// the device, creates a diagnostic which is emitted if and when we realize
9703 /// that the function will be codegen'ed.
9707 /// // Variable-length arrays are not allowed in CUDA device code.
9708 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9709 /// return ExprError();
9710 /// // Otherwise, continue parsing as normal.
9711 CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9713 /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9714 /// is "used as host code".
9716 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9717 CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9719 enum CUDAFunctionTarget {
9727 /// Determines whether the given function is a CUDA device/host/kernel/etc.
9730 /// Use this rather than examining the function's attributes yourself -- you
9731 /// will get it wrong. Returns CFT_Host if D is null.
9732 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9733 bool IgnoreImplicitHDAttr = false);
9734 CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9736 /// Gets the CUDA target for the current context.
9737 CUDAFunctionTarget CurrentCUDATarget() {
9738 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9741 // CUDA function call preference. Must be ordered numerically from
9743 enum CUDAFunctionPreference {
9744 CFP_Never, // Invalid caller/callee combination.
9745 CFP_WrongSide, // Calls from host-device to host or device
9746 // function that do not match current compilation
9748 CFP_HostDevice, // Any calls to host/device functions.
9749 CFP_SameSide, // Calls from host-device to host or device
9750 // function matching current compilation mode.
9751 CFP_Native, // host-to-host or device-to-device calls.
9754 /// Identifies relative preference of a given Caller/Callee
9755 /// combination, based on their host/device attributes.
9756 /// \param Caller function which needs address of \p Callee.
9757 /// nullptr in case of global context.
9758 /// \param Callee target function
9760 /// \returns preference value for particular Caller/Callee combination.
9761 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9762 const FunctionDecl *Callee);
9764 /// Determines whether Caller may invoke Callee, based on their CUDA
9765 /// host/device attributes. Returns false if the call is not allowed.
9767 /// Note: Will return true for CFP_WrongSide calls. These may appear in
9768 /// semantically correct CUDA programs, but only if they're never codegen'ed.
9769 bool IsAllowedCUDACall(const FunctionDecl *Caller,
9770 const FunctionDecl *Callee) {
9771 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9774 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9775 /// depending on FD and the current compilation settings.
9776 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9777 const LookupResult &Previous);
9780 /// Check whether we're allowed to call Callee from the current context.
9782 /// - If the call is never allowed in a semantically-correct program
9783 /// (CFP_Never), emits an error and returns false.
9785 /// - If the call is allowed in semantically-correct programs, but only if
9786 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9787 /// be emitted if and when the caller is codegen'ed, and returns true.
9789 /// Will only create deferred diagnostics for a given SourceLocation once,
9790 /// so you can safely call this multiple times without generating duplicate
9791 /// deferred errors.
9793 /// - Otherwise, returns true without emitting any diagnostics.
9794 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9796 /// Set __device__ or __host__ __device__ attributes on the given lambda
9797 /// operator() method.
9799 /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9800 /// the __device__ attribute. Similarly, lambdas inside __host__ __device__
9801 /// functions become __host__ __device__ themselves.
9802 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9804 /// Finds a function in \p Matches with highest calling priority
9805 /// from \p Caller context and erases all functions with lower
9806 /// calling priority.
9807 void EraseUnwantedCUDAMatches(
9808 const FunctionDecl *Caller,
9809 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9811 /// Given a implicit special member, infer its CUDA target from the
9812 /// calls it needs to make to underlying base/field special members.
9813 /// \param ClassDecl the class for which the member is being created.
9814 /// \param CSM the kind of special member.
9815 /// \param MemberDecl the special member itself.
9816 /// \param ConstRHS true if this is a copy operation with a const object on
9818 /// \param Diagnose true if this call should emit diagnostics.
9819 /// \return true if there was an error inferring.
9820 /// The result of this call is implicit CUDA target attribute(s) attached to
9821 /// the member declaration.
9822 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9823 CXXSpecialMember CSM,
9824 CXXMethodDecl *MemberDecl,
9828 /// \return true if \p CD can be considered empty according to CUDA
9829 /// (E.2.3.1 in CUDA 7.5 Programming guide).
9830 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9831 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9833 /// Check whether NewFD is a valid overload for CUDA. Emits
9834 /// diagnostics and invalidates NewFD if not.
9835 void checkCUDATargetOverload(FunctionDecl *NewFD,
9836 const LookupResult &Previous);
9837 /// Copies target attributes from the template TD to the function FD.
9838 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9840 /// \name Code completion
9842 /// \brief Describes the context in which code completion occurs.
9843 enum ParserCompletionContext {
9844 /// \brief Code completion occurs at top-level or namespace context.
9846 /// \brief Code completion occurs within a class, struct, or union.
9848 /// \brief Code completion occurs within an Objective-C interface, protocol,
9851 /// \brief Code completion occurs within an Objective-C implementation or
9852 /// category implementation
9853 PCC_ObjCImplementation,
9854 /// \brief Code completion occurs within the list of instance variables
9855 /// in an Objective-C interface, protocol, category, or implementation.
9856 PCC_ObjCInstanceVariableList,
9857 /// \brief Code completion occurs following one or more template
9860 /// \brief Code completion occurs following one or more template
9861 /// headers within a class.
9863 /// \brief Code completion occurs within an expression.
9865 /// \brief Code completion occurs within a statement, which may
9866 /// also be an expression or a declaration.
9868 /// \brief Code completion occurs at the beginning of the
9869 /// initialization statement (or expression) in a for loop.
9871 /// \brief Code completion occurs within the condition of an if,
9872 /// while, switch, or for statement.
9874 /// \brief Code completion occurs within the body of a function on a
9875 /// recovery path, where we do not have a specific handle on our position
9877 PCC_RecoveryInFunction,
9878 /// \brief Code completion occurs where only a type is permitted.
9880 /// \brief Code completion occurs in a parenthesized expression, which
9881 /// might also be a type cast.
9882 PCC_ParenthesizedExpression,
9883 /// \brief Code completion occurs within a sequence of declaration
9884 /// specifiers within a function, method, or block.
9885 PCC_LocalDeclarationSpecifiers
9888 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9889 void CodeCompleteOrdinaryName(Scope *S,
9890 ParserCompletionContext CompletionContext);
9891 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9892 bool AllowNonIdentifiers,
9893 bool AllowNestedNameSpecifiers);
9895 struct CodeCompleteExpressionData;
9896 void CodeCompleteExpression(Scope *S,
9897 const CodeCompleteExpressionData &Data);
9898 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9899 SourceLocation OpLoc, bool IsArrow,
9900 bool IsBaseExprStatement);
9901 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9902 void CodeCompleteTag(Scope *S, unsigned TagSpec);
9903 void CodeCompleteTypeQualifiers(DeclSpec &DS);
9904 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9905 const VirtSpecifiers *VS = nullptr);
9906 void CodeCompleteBracketDeclarator(Scope *S);
9907 void CodeCompleteCase(Scope *S);
9908 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9909 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9910 ArrayRef<Expr *> Args);
9911 void CodeCompleteInitializer(Scope *S, Decl *D);
9912 void CodeCompleteReturn(Scope *S);
9913 void CodeCompleteAfterIf(Scope *S);
9914 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9916 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9917 bool EnteringContext);
9918 void CodeCompleteUsing(Scope *S);
9919 void CodeCompleteUsingDirective(Scope *S);
9920 void CodeCompleteNamespaceDecl(Scope *S);
9921 void CodeCompleteNamespaceAliasDecl(Scope *S);
9922 void CodeCompleteOperatorName(Scope *S);
9923 void CodeCompleteConstructorInitializer(
9925 ArrayRef<CXXCtorInitializer *> Initializers);
9927 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9928 bool AfterAmpersand);
9930 void CodeCompleteObjCAtDirective(Scope *S);
9931 void CodeCompleteObjCAtVisibility(Scope *S);
9932 void CodeCompleteObjCAtStatement(Scope *S);
9933 void CodeCompleteObjCAtExpression(Scope *S);
9934 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9935 void CodeCompleteObjCPropertyGetter(Scope *S);
9936 void CodeCompleteObjCPropertySetter(Scope *S);
9937 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9939 void CodeCompleteObjCMessageReceiver(Scope *S);
9940 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9941 ArrayRef<IdentifierInfo *> SelIdents,
9942 bool AtArgumentExpression);
9943 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9944 ArrayRef<IdentifierInfo *> SelIdents,
9945 bool AtArgumentExpression,
9946 bool IsSuper = false);
9947 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9948 ArrayRef<IdentifierInfo *> SelIdents,
9949 bool AtArgumentExpression,
9950 ObjCInterfaceDecl *Super = nullptr);
9951 void CodeCompleteObjCForCollection(Scope *S,
9952 DeclGroupPtrTy IterationVar);
9953 void CodeCompleteObjCSelector(Scope *S,
9954 ArrayRef<IdentifierInfo *> SelIdents);
9955 void CodeCompleteObjCProtocolReferences(
9956 ArrayRef<IdentifierLocPair> Protocols);
9957 void CodeCompleteObjCProtocolDecl(Scope *S);
9958 void CodeCompleteObjCInterfaceDecl(Scope *S);
9959 void CodeCompleteObjCSuperclass(Scope *S,
9960 IdentifierInfo *ClassName,
9961 SourceLocation ClassNameLoc);
9962 void CodeCompleteObjCImplementationDecl(Scope *S);
9963 void CodeCompleteObjCInterfaceCategory(Scope *S,
9964 IdentifierInfo *ClassName,
9965 SourceLocation ClassNameLoc);
9966 void CodeCompleteObjCImplementationCategory(Scope *S,
9967 IdentifierInfo *ClassName,
9968 SourceLocation ClassNameLoc);
9969 void CodeCompleteObjCPropertyDefinition(Scope *S);
9970 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9971 IdentifierInfo *PropertyName);
9972 void CodeCompleteObjCMethodDecl(Scope *S,
9973 bool IsInstanceMethod,
9974 ParsedType ReturnType);
9975 void CodeCompleteObjCMethodDeclSelector(Scope *S,
9976 bool IsInstanceMethod,
9977 bool AtParameterName,
9978 ParsedType ReturnType,
9979 ArrayRef<IdentifierInfo *> SelIdents);
9980 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
9981 SourceLocation ClassNameLoc,
9982 bool IsBaseExprStatement);
9983 void CodeCompletePreprocessorDirective(bool InConditional);
9984 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9985 void CodeCompletePreprocessorMacroName(bool IsDefinition);
9986 void CodeCompletePreprocessorExpression();
9987 void CodeCompletePreprocessorMacroArgument(Scope *S,
9988 IdentifierInfo *Macro,
9989 MacroInfo *MacroInfo,
9991 void CodeCompleteNaturalLanguage();
9992 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9993 CodeCompletionTUInfo &CCTUInfo,
9994 SmallVectorImpl<CodeCompletionResult> &Results);
9997 //===--------------------------------------------------------------------===//
9998 // Extra semantic analysis beyond the C type system
10001 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10002 unsigned ByteNo) const;
10005 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10006 const ArraySubscriptExpr *ASE=nullptr,
10007 bool AllowOnePastEnd=true, bool IndexNegated=false);
10008 void CheckArrayAccess(const Expr *E);
10009 // Used to grab the relevant information from a FormatAttr and a
10010 // FunctionDeclaration.
10011 struct FormatStringInfo {
10012 unsigned FormatIdx;
10013 unsigned FirstDataArg;
10017 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10018 FormatStringInfo *FSI);
10019 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10020 const FunctionProtoType *Proto);
10021 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10022 ArrayRef<const Expr *> Args);
10023 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10024 const FunctionProtoType *Proto);
10025 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10026 void CheckConstructorCall(FunctionDecl *FDecl,
10027 ArrayRef<const Expr *> Args,
10028 const FunctionProtoType *Proto,
10029 SourceLocation Loc);
10031 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10032 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10033 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10034 VariadicCallType CallType);
10036 bool CheckObjCString(Expr *Arg);
10037 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10039 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10040 unsigned BuiltinID, CallExpr *TheCall);
10042 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10043 unsigned MaxWidth);
10044 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10045 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10047 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10048 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10049 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10050 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10051 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10052 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10053 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10055 bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
10056 bool SemaBuiltinVAStart(CallExpr *TheCall);
10057 bool SemaBuiltinMSVAStart(CallExpr *TheCall);
10058 bool SemaBuiltinVAStartARM(CallExpr *Call);
10059 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10060 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10061 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10064 // Used by C++ template instantiation.
10065 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10066 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10067 SourceLocation BuiltinLoc,
10068 SourceLocation RParenLoc);
10071 bool SemaBuiltinPrefetch(CallExpr *TheCall);
10072 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10073 bool SemaBuiltinAssume(CallExpr *TheCall);
10074 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10075 bool SemaBuiltinLongjmp(CallExpr *TheCall);
10076 bool SemaBuiltinSetjmp(CallExpr *TheCall);
10077 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10078 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10079 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10080 AtomicExpr::AtomicOp Op);
10081 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10082 llvm::APSInt &Result);
10083 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10084 int Low, int High);
10085 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10086 unsigned Multiple);
10087 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10088 int ArgNum, unsigned ExpectedFieldNum,
10091 enum FormatStringType {
10098 FST_FreeBSDKPrintf,
10103 static FormatStringType GetFormatStringType(const FormatAttr *Format);
10105 bool FormatStringHasSArg(const StringLiteral *FExpr);
10107 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10110 bool CheckFormatArguments(const FormatAttr *Format,
10111 ArrayRef<const Expr *> Args,
10113 VariadicCallType CallType,
10114 SourceLocation Loc, SourceRange Range,
10115 llvm::SmallBitVector &CheckedVarArgs);
10116 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10117 bool HasVAListArg, unsigned format_idx,
10118 unsigned firstDataArg, FormatStringType Type,
10119 VariadicCallType CallType,
10120 SourceLocation Loc, SourceRange range,
10121 llvm::SmallBitVector &CheckedVarArgs);
10123 void CheckAbsoluteValueFunction(const CallExpr *Call,
10124 const FunctionDecl *FDecl);
10126 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10128 void CheckMemaccessArguments(const CallExpr *Call,
10130 IdentifierInfo *FnName);
10132 void CheckStrlcpycatArguments(const CallExpr *Call,
10133 IdentifierInfo *FnName);
10135 void CheckStrncatArguments(const CallExpr *Call,
10136 IdentifierInfo *FnName);
10138 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10139 SourceLocation ReturnLoc,
10140 bool isObjCMethod = false,
10141 const AttrVec *Attrs = nullptr,
10142 const FunctionDecl *FD = nullptr);
10144 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10145 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10146 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10147 void CheckForIntOverflow(Expr *E);
10148 void CheckUnsequencedOperations(Expr *E);
10150 /// \brief Perform semantic checks on a completed expression. This will either
10151 /// be a full-expression or a default argument expression.
10152 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10153 bool IsConstexpr = false);
10155 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10158 /// Check if there is a field shadowing.
10159 void CheckShadowInheritedFields(const SourceLocation &Loc,
10160 DeclarationName FieldName,
10161 const CXXRecordDecl *RD);
10163 /// \brief Check if the given expression contains 'break' or 'continue'
10164 /// statement that produces control flow different from GCC.
10165 void CheckBreakContinueBinding(Expr *E);
10167 /// \brief Check whether receiver is mutable ObjC container which
10168 /// attempts to add itself into the container
10169 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10171 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10172 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10173 bool DeleteWasArrayForm);
10175 /// \brief Register a magic integral constant to be used as a type tag.
10176 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10177 uint64_t MagicValue, QualType Type,
10178 bool LayoutCompatible, bool MustBeNull);
10180 struct TypeTagData {
10183 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10184 Type(Type), LayoutCompatible(LayoutCompatible),
10185 MustBeNull(MustBeNull)
10190 /// If true, \c Type should be compared with other expression's types for
10191 /// layout-compatibility.
10192 unsigned LayoutCompatible : 1;
10193 unsigned MustBeNull : 1;
10196 /// A pair of ArgumentKind identifier and magic value. This uniquely
10197 /// identifies the magic value.
10198 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10201 /// \brief A map from magic value to type information.
10202 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10203 TypeTagForDatatypeMagicValues;
10205 /// \brief Peform checks on a call of a function with argument_with_type_tag
10206 /// or pointer_with_type_tag attributes.
10207 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10208 const Expr * const *ExprArgs);
10210 /// \brief Check if we are taking the address of a packed field
10211 /// as this may be a problem if the pointer value is dereferenced.
10212 void CheckAddressOfPackedMember(Expr *rhs);
10214 /// \brief The parser's current scope.
10216 /// The parser maintains this state here.
10219 mutable IdentifierInfo *Ident_super;
10220 mutable IdentifierInfo *Ident___float128;
10222 /// Nullability type specifiers.
10223 IdentifierInfo *Ident__Nonnull = nullptr;
10224 IdentifierInfo *Ident__Nullable = nullptr;
10225 IdentifierInfo *Ident__Null_unspecified = nullptr;
10227 IdentifierInfo *Ident_NSError = nullptr;
10230 friend class Parser;
10231 friend class InitializationSequence;
10232 friend class ASTReader;
10233 friend class ASTDeclReader;
10234 friend class ASTWriter;
10237 /// Retrieve the keyword associated
10238 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10240 /// The struct behind the CFErrorRef pointer.
10241 RecordDecl *CFError = nullptr;
10243 /// Retrieve the identifier "NSError".
10244 IdentifierInfo *getNSErrorIdent();
10246 /// \brief Retrieve the parser's current scope.
10248 /// This routine must only be used when it is certain that semantic analysis
10249 /// and the parser are in precisely the same context, which is not the case
10250 /// when, e.g., we are performing any kind of template instantiation.
10251 /// Therefore, the only safe places to use this scope are in the parser
10252 /// itself and in routines directly invoked from the parser and *never* from
10253 /// template substitution or instantiation.
10254 Scope *getCurScope() const { return CurScope; }
10256 void incrementMSManglingNumber() const {
10257 return CurScope->incrementMSManglingNumber();
10260 IdentifierInfo *getSuperIdentifier() const;
10261 IdentifierInfo *getFloat128Identifier() const;
10263 Decl *getObjCDeclContext() const;
10265 DeclContext *getCurLexicalContext() const {
10266 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10269 /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10271 /// \param D The declaration to check. Note that this may be altered to point
10272 /// to another declaration that \c D gets it's availability from. i.e., we
10273 /// walk the list of typedefs to find an availability attribute.
10275 /// \param Message If non-null, this will be populated with the message from
10276 /// the availability attribute that is selected.
10277 AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10278 std::string *Message);
10280 const DeclContext *getCurObjCLexicalContext() const {
10281 const DeclContext *DC = getCurLexicalContext();
10282 // A category implicitly has the attribute of the interface.
10283 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10284 DC = CatD->getClassInterface();
10288 /// \brief To be used for checking whether the arguments being passed to
10289 /// function exceeds the number of parameters expected for it.
10290 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10291 bool PartialOverloading = false) {
10292 // We check whether we're just after a comma in code-completion.
10293 if (NumArgs > 0 && PartialOverloading)
10294 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10295 return NumArgs > NumParams;
10298 // Emitting members of dllexported classes is delayed until the class
10299 // (including field initializers) is fully parsed.
10300 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10303 /// \brief Helper class that collects misaligned member designations and
10304 /// their location info for delayed diagnostics.
10305 struct MisalignedMember {
10309 CharUnits Alignment;
10311 MisalignedMember() : E(), RD(), MD(), Alignment() {}
10312 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10313 CharUnits Alignment)
10314 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10315 explicit MisalignedMember(Expr *E)
10316 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10318 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10320 /// \brief Small set of gathered accesses to potentially misaligned members
10321 /// due to the packed attribute.
10322 SmallVector<MisalignedMember, 4> MisalignedMembers;
10324 /// \brief Adds an expression to the set of gathered misaligned members.
10325 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10326 CharUnits Alignment);
10329 /// \brief Diagnoses the current set of gathered accesses. This typically
10330 /// happens at full expression level. The set is cleared after emitting the
10332 void DiagnoseMisalignedMembers();
10334 /// \brief This function checks if the expression is in the sef of potentially
10335 /// misaligned members and it is converted to some pointer type T with lower
10336 /// or equal alignment requirements. If so it removes it. This is used when
10337 /// we do not want to diagnose such misaligned access (e.g. in conversions to
10339 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10341 /// \brief This function calls Action when it determines that E designates a
10342 /// misaligned member due to the packed attribute. This is used to emit
10343 /// local diagnostics like in reference binding.
10344 void RefersToMemberWithReducedAlignment(
10346 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10350 /// \brief RAII object that enters a new expression evaluation context.
10351 class EnterExpressionEvaluationContext {
10353 bool Entered = true;
10357 EnterExpressionEvaluationContext(Sema &Actions,
10358 Sema::ExpressionEvaluationContext NewContext,
10359 Decl *LambdaContextDecl = nullptr,
10360 bool IsDecltype = false,
10361 bool ShouldEnter = true)
10362 : Actions(Actions), Entered(ShouldEnter) {
10364 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10367 EnterExpressionEvaluationContext(Sema &Actions,
10368 Sema::ExpressionEvaluationContext NewContext,
10369 Sema::ReuseLambdaContextDecl_t,
10370 bool IsDecltype = false)
10371 : Actions(Actions) {
10372 Actions.PushExpressionEvaluationContext(NewContext,
10373 Sema::ReuseLambdaContextDecl,
10377 enum InitListTag { InitList };
10378 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10379 bool ShouldEnter = true)
10380 : Actions(Actions), Entered(false) {
10381 // In C++11 onwards, narrowing checks are performed on the contents of
10382 // braced-init-lists, even when they occur within unevaluated operands.
10383 // Therefore we still need to instantiate constexpr functions used in such
10385 if (ShouldEnter && Actions.isUnevaluatedContext() &&
10386 Actions.getLangOpts().CPlusPlus11) {
10387 Actions.PushExpressionEvaluationContext(
10388 Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10393 ~EnterExpressionEvaluationContext() {
10395 Actions.PopExpressionEvaluationContext();
10399 DeductionFailureInfo
10400 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10401 sema::TemplateDeductionInfo &Info);
10403 /// \brief Contains a late templated function.
10404 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10405 struct LateParsedTemplate {
10407 /// \brief The template function declaration to be late parsed.
10411 } // end namespace clang
10414 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10416 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10417 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10418 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10420 static FunctionDeclAndLoc getEmptyKey() {
10421 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10424 static FunctionDeclAndLoc getTombstoneKey() {
10425 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10428 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10429 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10430 FDL.Loc.getRawEncoding());
10433 static bool isEqual(const FunctionDeclAndLoc &LHS,
10434 const FunctionDeclAndLoc &RHS) {
10435 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10438 } // namespace llvm