Bug Summary

File:tools/clang/include/clang/Sema/Sema.h
Warning:line 274, column 7
Excessive padding in 'class clang::Sema' (75 padding bytes, where 3 is optimal). Optimal fields order: ExternalSource, LangOpts, PP, Context, Consumer, Diags, SourceMgr, CodeCompleter, CurContext, OriginalLexicalContext, VAListTagName, CurInitSeg, VisContext, PragmaAttributeCurrentTargetDecl, PreallocatedFunctionScope, FieldCollector, PureVirtualClassDiagSet, LateTemplateParser, LateTemplateParserCleanup, OpaqueParser, DelayedDiagnostics, TUScope, StdNamespace, StdBadAlloc, StdAlignValT, StdExperimentalNamespaceCache, StdInitializerList, CXXTypeInfoDecl, MSVCGuidDecl, NSAPIObj, NSNumberDecl, NSValueDecl, NSNumberPointer, NSValuePointer, NSStringDecl, NSStringPointer, StringWithUTF8StringMethod, ValueWithBytesObjCTypeMethod, NSArrayDecl, ArrayWithObjectsMethod, NSDictionaryDecl, DictionaryWithObjectsMethod, QIDNSCopying, RespondsToSelectorSel, CXXThisTypeOverride, CurrentInstantiationScope, ThreadSafetyDeclCache, VarDataSharingAttributesStack, TypeTagForDatatypeMagicValues, CurScope, Ident_super, Ident___float128, Ident__Nonnull, Ident__Nullable, Ident__Null_unspecified, Ident_NSError, SemaPPCallbackHandler, CFError, IdResolver, SpecialMemberCache, TemplateInstCallbacks, OpenCLFeatures, ExtnameUndeclaredIdentifiers, FlagBitsCache, UnparsedDefaultArgInstantiations, UnparsedDefaultArgLocs, MethodPool, VisibleModules, ShadowingDecls, VTablesUsed, InstantiatingSpecializations, InstantiatedNonDependentTypes, LookupModulesCache, VisibleNamespaceCache, SuppressedDiagnostics, TypoCorrectionFailures, CurrOpenCLExtension, OpenCLTypeExtMap, OpenCLDeclExtMap, CUDADeferredDiags, LocsWithCUDACallDiags, CUDAKnownEmittedFns, CUDACallGraph, CurrentSEHFinally, PragmaClangBSSSection, PragmaClangDataSection, PragmaClangRodataSection, PragmaClangTextSection, WeakTopLevelDecl, NullabilityMap, LateParsedInstantiations, MaybeODRUseExprs, FunctionScopes, DeleteExprs, DelayedExceptionSpecChecks, DelayedDefaultedMemberExceptionSpecs, LateParsedTemplateMap, WeakUndeclaredIdentifiers, UndefinedButUsed, ReferencedSelectors, CurrentParameterCopyTypes, DelayedTypos, KnownNamespaces, DelayedDllExportClasses, ParsingInitForAutoVars, SpecialMembersBeingDeclared, TypoCorrectedFunctionDefinitions, ExtVectorDecls, TentativeDefinitions, UnusedFileScopedDecls, DelegatingCtorDecls, PendingInstantiations, PendingLocalImplicitInstantiations, ExprCleanupObjects, AnalysisWarnings, VtorDispStack, PackStack, UnusedLocalTypedefNameCandidates, DataSegStack, BSSSegStack, ConstSegStack, CodeSegStack, PackIncludeStack, NSNumberLiteralMethods, BumpAlloc, PragmaAttributeStack, CodeSynthesisContextLookupModules, MisalignedMembers, VTableUses, UnusedPrivateFields, ModuleScopes, CodeSynthesisContexts, ExprEvalContexts, FPFeatures, MSPointerToMemberRepresentationMethod, ImplicitMSInheritanceAttrLoc, CurInitSegLoc, OptimizeOffPragmaLocation, TUKind, NumSFINAEErrors, NonInstantiationEntries, LastEmittedCodeSynthesisContextDepth, ArgumentPackSubstitutionIndex, TyposCorrected, ForceCUDAHostDeviceDepth, isMultiplexExternalSource, CollectStats, MSStructPragmaOn, IsBuildingRecoveryCallExpr, GlobalNewDeleteDeclared, AllowAbstractFieldReference, LoadedExternalKnownNamespaces, AccessCheckingSFINAE, InNonInstantiationSFINAEContext, DisableTypoCorrection, IsInOpenMPDeclareTargetContext, Cleanup, consider reordering the fields or adding explicit padding members

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name IncludeFixer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/tools/extra/include-fixer -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/tools/extra/include-fixer -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/tools/extra/include-fixer -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/tools/extra/include-fixer/IncludeFixer.cpp
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
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/Module.h"
34#include "clang/Basic/OpenMPKinds.h"
35#include "clang/Basic/PragmaKinds.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TemplateKinds.h"
38#include "clang/Basic/TypeTraits.h"
39#include "clang/Sema/AnalysisBasedWarnings.h"
40#include "clang/Sema/CleanupInfo.h"
41#include "clang/Sema/DeclSpec.h"
42#include "clang/Sema/ExternalSemaSource.h"
43#include "clang/Sema/IdentifierResolver.h"
44#include "clang/Sema/ObjCMethodList.h"
45#include "clang/Sema/Ownership.h"
46#include "clang/Sema/Scope.h"
47#include "clang/Sema/TypoCorrection.h"
48#include "clang/Sema/Weak.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/Optional.h"
51#include "llvm/ADT/SetVector.h"
52#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallVector.h"
54#include "llvm/ADT/TinyPtrVector.h"
55#include <deque>
56#include <memory>
57#include <string>
58#include <vector>
59
60namespace llvm {
61 class APSInt;
62 template <typename ValueT> struct DenseMapInfo;
63 template <typename ValueT, typename ValueInfoT> class DenseSet;
64 class SmallBitVector;
65 struct InlineAsmIdentifierInfo;
66}
67
68namespace clang {
69 class ADLResult;
70 class ASTConsumer;
71 class ASTContext;
72 class ASTMutationListener;
73 class ASTReader;
74 class ASTWriter;
75 class ArrayType;
76 class AttributeList;
77 class BindingDecl;
78 class BlockDecl;
79 class CapturedDecl;
80 class CXXBasePath;
81 class CXXBasePaths;
82 class CXXBindTemporaryExpr;
83 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
84 class CXXConstructorDecl;
85 class CXXConversionDecl;
86 class CXXDeleteExpr;
87 class CXXDestructorDecl;
88 class CXXFieldCollector;
89 class CXXMemberCallExpr;
90 class CXXMethodDecl;
91 class CXXScopeSpec;
92 class CXXTemporary;
93 class CXXTryStmt;
94 class CallExpr;
95 class ClassTemplateDecl;
96 class ClassTemplatePartialSpecializationDecl;
97 class ClassTemplateSpecializationDecl;
98 class VarTemplatePartialSpecializationDecl;
99 class CodeCompleteConsumer;
100 class CodeCompletionAllocator;
101 class CodeCompletionTUInfo;
102 class CodeCompletionResult;
103 class CoroutineBodyStmt;
104 class Decl;
105 class DeclAccessPair;
106 class DeclContext;
107 class DeclRefExpr;
108 class DeclaratorDecl;
109 class DeducedTemplateArgument;
110 class DependentDiagnostic;
111 class DesignatedInitExpr;
112 class Designation;
113 class EnableIfAttr;
114 class EnumConstantDecl;
115 class Expr;
116 class ExtVectorType;
117 class FormatAttr;
118 class FriendDecl;
119 class FunctionDecl;
120 class FunctionProtoType;
121 class FunctionTemplateDecl;
122 class ImplicitConversionSequence;
123 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
124 class InitListExpr;
125 class InitializationKind;
126 class InitializationSequence;
127 class InitializedEntity;
128 class IntegerLiteral;
129 class LabelStmt;
130 class LambdaExpr;
131 class LangOptions;
132 class LocalInstantiationScope;
133 class LookupResult;
134 class MacroInfo;
135 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
136 class ModuleLoader;
137 class MultiLevelTemplateArgumentList;
138 class NamedDecl;
139 class ObjCCategoryDecl;
140 class ObjCCategoryImplDecl;
141 class ObjCCompatibleAliasDecl;
142 class ObjCContainerDecl;
143 class ObjCImplDecl;
144 class ObjCImplementationDecl;
145 class ObjCInterfaceDecl;
146 class ObjCIvarDecl;
147 template <class T> class ObjCList;
148 class ObjCMessageExpr;
149 class ObjCMethodDecl;
150 class ObjCPropertyDecl;
151 class ObjCProtocolDecl;
152 class OMPThreadPrivateDecl;
153 class OMPDeclareReductionDecl;
154 class OMPDeclareSimdDecl;
155 class OMPClause;
156 struct OverloadCandidate;
157 class OverloadCandidateSet;
158 class OverloadExpr;
159 class ParenListExpr;
160 class ParmVarDecl;
161 class Preprocessor;
162 class PseudoDestructorTypeStorage;
163 class PseudoObjectExpr;
164 class QualType;
165 class StandardConversionSequence;
166 class Stmt;
167 class StringLiteral;
168 class SwitchStmt;
169 class TemplateArgument;
170 class TemplateArgumentList;
171 class TemplateArgumentLoc;
172 class TemplateDecl;
173 class TemplateInstantiationCallback;
174 class TemplateParameterList;
175 class TemplatePartialOrderingContext;
176 class TemplateTemplateParmDecl;
177 class Token;
178 class TypeAliasDecl;
179 class TypedefDecl;
180 class TypedefNameDecl;
181 class TypeLoc;
182 class TypoCorrectionConsumer;
183 class UnqualifiedId;
184 class UnresolvedLookupExpr;
185 class UnresolvedMemberExpr;
186 class UnresolvedSetImpl;
187 class UnresolvedSetIterator;
188 class UsingDecl;
189 class UsingShadowDecl;
190 class ValueDecl;
191 class VarDecl;
192 class VarTemplateSpecializationDecl;
193 class VisibilityAttr;
194 class VisibleDeclConsumer;
195 class IndirectFieldDecl;
196 struct DeductionFailureInfo;
197 class TemplateSpecCandidateSet;
198
199namespace sema {
200 class AccessedEntity;
201 class BlockScopeInfo;
202 class Capture;
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 SemaPPCallbacks;
212 class TemplateDeductionInfo;
213}
214
215namespace threadSafety {
216 class BeforeSet;
217 void threadSafetyCleanup(BeforeSet* Cache);
218}
219
220// FIXME: No way to easily map from TemplateTypeParmTypes to
221// TemplateTypeParmDecls, so we have this horrible PointerUnion.
222typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
223 SourceLocation> UnexpandedParameterPack;
224
225/// Describes whether we've seen any nullability information for the given
226/// file.
227struct FileNullability {
228 /// The first pointer declarator (of any pointer kind) in the file that does
229 /// not have a corresponding nullability annotation.
230 SourceLocation PointerLoc;
231
232 /// The end location for the first pointer declarator in the file. Used for
233 /// placing fix-its.
234 SourceLocation PointerEndLoc;
235
236 /// Which kind of pointer declarator we saw.
237 uint8_t PointerKind;
238
239 /// Whether we saw any type nullability annotations in the given file.
240 bool SawTypeNullability = false;
241};
242
243/// A mapping from file IDs to a record of whether we've seen nullability
244/// information in that file.
245class FileNullabilityMap {
246 /// A mapping from file IDs to the nullability information for each file ID.
247 llvm::DenseMap<FileID, FileNullability> Map;
248
249 /// A single-element cache based on the file ID.
250 struct {
251 FileID File;
252 FileNullability Nullability;
253 } Cache;
254
255public:
256 FileNullability &operator[](FileID file) {
257 // Check the single-element cache.
258 if (file == Cache.File)
259 return Cache.Nullability;
260
261 // It's not in the single-element cache; flush the cache if we have one.
262 if (!Cache.File.isInvalid()) {
263 Map[Cache.File] = Cache.Nullability;
264 }
265
266 // Pull this entry into the cache.
267 Cache.File = file;
268 Cache.Nullability = Map[file];
269 return Cache.Nullability;
270 }
271};
272
273/// Sema - This implements semantic analysis and AST building for C.
274class Sema {
Excessive padding in 'class clang::Sema' (75 padding bytes, where 3 is optimal). Optimal fields order: ExternalSource, LangOpts, PP, Context, Consumer, Diags, SourceMgr, CodeCompleter, CurContext, OriginalLexicalContext, VAListTagName, CurInitSeg, VisContext, PragmaAttributeCurrentTargetDecl, PreallocatedFunctionScope, FieldCollector, PureVirtualClassDiagSet, LateTemplateParser, LateTemplateParserCleanup, OpaqueParser, DelayedDiagnostics, TUScope, StdNamespace, StdBadAlloc, StdAlignValT, StdExperimentalNamespaceCache, StdInitializerList, CXXTypeInfoDecl, MSVCGuidDecl, NSAPIObj, NSNumberDecl, NSValueDecl, NSNumberPointer, NSValuePointer, NSStringDecl, NSStringPointer, StringWithUTF8StringMethod, ValueWithBytesObjCTypeMethod, NSArrayDecl, ArrayWithObjectsMethod, NSDictionaryDecl, DictionaryWithObjectsMethod, QIDNSCopying, RespondsToSelectorSel, CXXThisTypeOverride, CurrentInstantiationScope, ThreadSafetyDeclCache, VarDataSharingAttributesStack, TypeTagForDatatypeMagicValues, CurScope, Ident_super, Ident___float128, Ident__Nonnull, Ident__Nullable, Ident__Null_unspecified, Ident_NSError, SemaPPCallbackHandler, CFError, IdResolver, SpecialMemberCache, TemplateInstCallbacks, OpenCLFeatures, ExtnameUndeclaredIdentifiers, FlagBitsCache, UnparsedDefaultArgInstantiations, UnparsedDefaultArgLocs, MethodPool, VisibleModules, ShadowingDecls, VTablesUsed, InstantiatingSpecializations, InstantiatedNonDependentTypes, LookupModulesCache, VisibleNamespaceCache, SuppressedDiagnostics, TypoCorrectionFailures, CurrOpenCLExtension, OpenCLTypeExtMap, OpenCLDeclExtMap, CUDADeferredDiags, LocsWithCUDACallDiags, CUDAKnownEmittedFns, CUDACallGraph, CurrentSEHFinally, PragmaClangBSSSection, PragmaClangDataSection, PragmaClangRodataSection, PragmaClangTextSection, WeakTopLevelDecl, NullabilityMap, LateParsedInstantiations, MaybeODRUseExprs, FunctionScopes, DeleteExprs, DelayedExceptionSpecChecks, DelayedDefaultedMemberExceptionSpecs, LateParsedTemplateMap, WeakUndeclaredIdentifiers, UndefinedButUsed, ReferencedSelectors, CurrentParameterCopyTypes, DelayedTypos, KnownNamespaces, DelayedDllExportClasses, ParsingInitForAutoVars, SpecialMembersBeingDeclared, TypoCorrectedFunctionDefinitions, ExtVectorDecls, TentativeDefinitions, UnusedFileScopedDecls, DelegatingCtorDecls, PendingInstantiations, PendingLocalImplicitInstantiations, ExprCleanupObjects, AnalysisWarnings, VtorDispStack, PackStack, UnusedLocalTypedefNameCandidates, DataSegStack, BSSSegStack, ConstSegStack, CodeSegStack, PackIncludeStack, NSNumberLiteralMethods, BumpAlloc, PragmaAttributeStack, CodeSynthesisContextLookupModules, MisalignedMembers, VTableUses, UnusedPrivateFields, ModuleScopes, CodeSynthesisContexts, ExprEvalContexts, FPFeatures, MSPointerToMemberRepresentationMethod, ImplicitMSInheritanceAttrLoc, CurInitSegLoc, OptimizeOffPragmaLocation, TUKind, NumSFINAEErrors, NonInstantiationEntries, LastEmittedCodeSynthesisContextDepth, ArgumentPackSubstitutionIndex, TyposCorrected, ForceCUDAHostDeviceDepth, isMultiplexExternalSource, CollectStats, MSStructPragmaOn, IsBuildingRecoveryCallExpr, GlobalNewDeleteDeclared, AllowAbstractFieldReference, LoadedExternalKnownNamespaces, AccessCheckingSFINAE, InNonInstantiationSFINAEContext, DisableTypoCorrection, IsInOpenMPDeclareTargetContext, Cleanup, consider reordering the fields or adding explicit padding members
275 Sema(const Sema &) = delete;
276 void operator=(const Sema &) = delete;
277
278 ///\brief Source of additional semantic information.
279 ExternalSemaSource *ExternalSource;
280
281 ///\brief Whether Sema has generated a multiplexer and has to delete it.
282 bool isMultiplexExternalSource;
283
284 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
285
286 bool isVisibleSlow(const NamedDecl *D);
287
288 /// Determine whether two declarations should be linked together, given that
289 /// the old declaration might not be visible and the new declaration might
290 /// not have external linkage.
291 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
292 const NamedDecl *New) {
293 if (isVisible(Old))
294 return true;
295 // See comment in below overload for why it's safe to compute the linkage
296 // of the new declaration here.
297 if (New->isExternallyDeclarable()) {
298 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 299, __extension__ __PRETTY_FUNCTION__))
299 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return true;
301 }
302 return false;
303 }
304 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
305
306public:
307 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
308 typedef OpaquePtr<TemplateName> TemplateTy;
309 typedef OpaquePtr<QualType> TypeTy;
310
311 OpenCLOptions OpenCLFeatures;
312 FPOptions FPFeatures;
313
314 const LangOptions &LangOpts;
315 Preprocessor &PP;
316 ASTContext &Context;
317 ASTConsumer &Consumer;
318 DiagnosticsEngine &Diags;
319 SourceManager &SourceMgr;
320
321 /// \brief Flag indicating whether or not to collect detailed statistics.
322 bool CollectStats;
323
324 /// \brief Code-completion consumer.
325 CodeCompleteConsumer *CodeCompleter;
326
327 /// CurContext - This is the current declaration context of parsing.
328 DeclContext *CurContext;
329
330 /// \brief Generally null except when we temporarily switch decl contexts,
331 /// like in \see ActOnObjCTemporaryExitContainerContext.
332 DeclContext *OriginalLexicalContext;
333
334 /// VAListTagName - The declaration name corresponding to __va_list_tag.
335 /// This is used as part of a hack to omit that class from ADL results.
336 DeclarationName VAListTagName;
337
338 bool MSStructPragmaOn; // True when \#pragma ms_struct on
339
340 /// \brief Controls member pointer representation format under the MS ABI.
341 LangOptions::PragmaMSPointersToMembersKind
342 MSPointerToMemberRepresentationMethod;
343
344 /// Stack of active SEH __finally scopes. Can be empty.
345 SmallVector<Scope*, 2> CurrentSEHFinally;
346
347 /// \brief Source location for newly created implicit MSInheritanceAttrs
348 SourceLocation ImplicitMSInheritanceAttrLoc;
349
350 /// \brief pragma clang section kind
351 enum PragmaClangSectionKind {
352 PCSK_Invalid = 0,
353 PCSK_BSS = 1,
354 PCSK_Data = 2,
355 PCSK_Rodata = 3,
356 PCSK_Text = 4
357 };
358
359 enum PragmaClangSectionAction {
360 PCSA_Set = 0,
361 PCSA_Clear = 1
362 };
363
364 struct PragmaClangSection {
365 std::string SectionName;
366 bool Valid = false;
367 SourceLocation PragmaLocation;
368
369 void Act(SourceLocation PragmaLocation,
370 PragmaClangSectionAction Action,
371 StringLiteral* Name);
372 };
373
374 PragmaClangSection PragmaClangBSSSection;
375 PragmaClangSection PragmaClangDataSection;
376 PragmaClangSection PragmaClangRodataSection;
377 PragmaClangSection PragmaClangTextSection;
378
379 enum PragmaMsStackAction {
380 PSK_Reset = 0x0, // #pragma ()
381 PSK_Set = 0x1, // #pragma (value)
382 PSK_Push = 0x2, // #pragma (push[, id])
383 PSK_Pop = 0x4, // #pragma (pop[, id])
384 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
385 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
386 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
387 };
388
389 template<typename ValueType>
390 struct PragmaStack {
391 struct Slot {
392 llvm::StringRef StackSlotLabel;
393 ValueType Value;
394 SourceLocation PragmaLocation;
395 SourceLocation PragmaPushLocation;
396 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
397 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
398 : StackSlotLabel(StackSlotLabel), Value(Value),
399 PragmaLocation(PragmaLocation),
400 PragmaPushLocation(PragmaPushLocation) {}
401 };
402 void Act(SourceLocation PragmaLocation,
403 PragmaMsStackAction Action,
404 llvm::StringRef StackSlotLabel,
405 ValueType Value);
406
407 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
408 // method body to restore the stacks on exit, so it works like this:
409 //
410 // struct S {
411 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
412 // void Method {}
413 // #pragma <name>(pop, InternalPragmaSlot)
414 // };
415 //
416 // It works even with #pragma vtordisp, although MSVC doesn't support
417 // #pragma vtordisp(push [, id], n)
418 // syntax.
419 //
420 // Push / pop a named sentinel slot.
421 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
422 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 423, __extension__ __PRETTY_FUNCTION__))
423 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 423, __extension__ __PRETTY_FUNCTION__))
;
424 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
425 }
426
427 // Constructors.
428 explicit PragmaStack(const ValueType &Default)
429 : DefaultValue(Default), CurrentValue(Default) {}
430
431 bool hasValue() const { return CurrentValue != DefaultValue; }
432
433 SmallVector<Slot, 2> Stack;
434 ValueType DefaultValue; // Value used for PSK_Reset action.
435 ValueType CurrentValue;
436 SourceLocation CurrentPragmaLocation;
437 };
438 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
439 // we shouldn't do so if they're in a module).
440
441 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
442 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
443 ///
444 /// 0: Suppress all vtordisps
445 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
446 /// structors
447 /// 2: Always insert vtordisps to support RTTI on partially constructed
448 /// objects
449 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
450 // #pragma pack.
451 // Sentinel to represent when the stack is set to mac68k alignment.
452 static const unsigned kMac68kAlignmentSentinel = ~0U;
453 PragmaStack<unsigned> PackStack;
454 // The current #pragma pack values and locations at each #include.
455 struct PackIncludeState {
456 unsigned CurrentValue;
457 SourceLocation CurrentPragmaLocation;
458 bool HasNonDefaultValue, ShouldWarnOnInclude;
459 };
460 SmallVector<PackIncludeState, 8> PackIncludeStack;
461 // Segment #pragmas.
462 PragmaStack<StringLiteral *> DataSegStack;
463 PragmaStack<StringLiteral *> BSSSegStack;
464 PragmaStack<StringLiteral *> ConstSegStack;
465 PragmaStack<StringLiteral *> CodeSegStack;
466
467 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
468 // Actions should be performed only if we enter / exit a C++ method body.
469 class PragmaStackSentinelRAII {
470 public:
471 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
472 ~PragmaStackSentinelRAII();
473
474 private:
475 Sema &S;
476 StringRef SlotLabel;
477 bool ShouldAct;
478 };
479
480 /// A mapping that describes the nullability we've seen in each header file.
481 FileNullabilityMap NullabilityMap;
482
483 /// Last section used with #pragma init_seg.
484 StringLiteral *CurInitSeg;
485 SourceLocation CurInitSegLoc;
486
487 /// VisContext - Manages the stack for \#pragma GCC visibility.
488 void *VisContext; // Really a "PragmaVisStack*"
489
490 /// \brief This represents the stack of attributes that were pushed by
491 /// \#pragma clang attribute.
492 struct PragmaAttributeEntry {
493 SourceLocation Loc;
494 AttributeList *Attribute;
495 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
496 bool IsUsed;
497 };
498 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
499
500 /// \brief The declaration that is currently receiving an attribute from the
501 /// #pragma attribute stack.
502 const Decl *PragmaAttributeCurrentTargetDecl;
503
504 /// \brief This represents the last location of a "#pragma clang optimize off"
505 /// directive if such a directive has not been closed by an "on" yet. If
506 /// optimizations are currently "on", this is set to an invalid location.
507 SourceLocation OptimizeOffPragmaLocation;
508
509 /// \brief Flag indicating if Sema is building a recovery call expression.
510 ///
511 /// This flag is used to avoid building recovery call expressions
512 /// if Sema is already doing so, which would cause infinite recursions.
513 bool IsBuildingRecoveryCallExpr;
514
515 /// Used to control the generation of ExprWithCleanups.
516 CleanupInfo Cleanup;
517
518 /// ExprCleanupObjects - This is the stack of objects requiring
519 /// cleanup that are created by the current full expression. The
520 /// element type here is ExprWithCleanups::Object.
521 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
522
523 /// \brief Store a list of either DeclRefExprs or MemberExprs
524 /// that contain a reference to a variable (constant) that may or may not
525 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
526 /// and discarded value conversions have been applied to all subexpressions
527 /// of the enclosing full expression. This is cleared at the end of each
528 /// full expression.
529 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
530
531 std::unique_ptr<sema::FunctionScopeInfo> PreallocatedFunctionScope;
532
533 /// \brief Stack containing information about each of the nested
534 /// function, block, and method scopes that are currently active.
535 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
536
537 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
538 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
539 ExtVectorDeclsType;
540
541 /// ExtVectorDecls - This is a list all the extended vector types. This allows
542 /// us to associate a raw vector type with one of the ext_vector type names.
543 /// This is only necessary for issuing pretty diagnostics.
544 ExtVectorDeclsType ExtVectorDecls;
545
546 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
547 std::unique_ptr<CXXFieldCollector> FieldCollector;
548
549 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
550
551 /// \brief Set containing all declared private fields that are not used.
552 NamedDeclSetType UnusedPrivateFields;
553
554 /// \brief Set containing all typedefs that are likely unused.
555 llvm::SmallSetVector<const TypedefNameDecl *, 4>
556 UnusedLocalTypedefNameCandidates;
557
558 /// \brief Delete-expressions to be analyzed at the end of translation unit
559 ///
560 /// This list contains class members, and locations of delete-expressions
561 /// that could not be proven as to whether they mismatch with new-expression
562 /// used in initializer of the field.
563 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
564 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
565 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
566
567 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
568
569 /// PureVirtualClassDiagSet - a set of class declarations which we have
570 /// emitted a list of pure virtual functions. Used to prevent emitting the
571 /// same list more than once.
572 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
573
574 /// ParsingInitForAutoVars - a set of declarations with auto types for which
575 /// we are currently parsing the initializer.
576 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
577
578 /// \brief Look for a locally scoped extern "C" declaration by the given name.
579 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
580
581 typedef LazyVector<VarDecl *, ExternalSemaSource,
582 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
583 TentativeDefinitionsType;
584
585 /// \brief All the tentative definitions encountered in the TU.
586 TentativeDefinitionsType TentativeDefinitions;
587
588 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
589 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
590 UnusedFileScopedDeclsType;
591
592 /// \brief The set of file scoped decls seen so far that have not been used
593 /// and must warn if not used. Only contains the first declaration.
594 UnusedFileScopedDeclsType UnusedFileScopedDecls;
595
596 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
597 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
598 DelegatingCtorDeclsType;
599
600 /// \brief All the delegating constructors seen so far in the file, used for
601 /// cycle detection at the end of the TU.
602 DelegatingCtorDeclsType DelegatingCtorDecls;
603
604 /// \brief All the overriding functions seen during a class definition
605 /// that had their exception spec checks delayed, plus the overridden
606 /// function.
607 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
608 DelayedExceptionSpecChecks;
609
610 /// \brief All the members seen during a class definition which were both
611 /// explicitly defaulted and had explicitly-specified exception
612 /// specifications, along with the function type containing their
613 /// user-specified exception specification. Those exception specifications
614 /// were overridden with the default specifications, but we still need to
615 /// check whether they are compatible with the default specification, and
616 /// we can't do that until the nesting set of class definitions is complete.
617 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
618 DelayedDefaultedMemberExceptionSpecs;
619
620 typedef llvm::MapVector<const FunctionDecl *,
621 std::unique_ptr<LateParsedTemplate>>
622 LateParsedTemplateMapT;
623 LateParsedTemplateMapT LateParsedTemplateMap;
624
625 /// \brief Callback to the parser to parse templated functions when needed.
626 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
627 typedef void LateTemplateParserCleanupCB(void *P);
628 LateTemplateParserCB *LateTemplateParser;
629 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
630 void *OpaqueParser;
631
632 void SetLateTemplateParser(LateTemplateParserCB *LTP,
633 LateTemplateParserCleanupCB *LTPCleanup,
634 void *P) {
635 LateTemplateParser = LTP;
636 LateTemplateParserCleanup = LTPCleanup;
637 OpaqueParser = P;
638 }
639
640 class DelayedDiagnostics;
641
642 class DelayedDiagnosticsState {
643 sema::DelayedDiagnosticPool *SavedPool;
644 friend class Sema::DelayedDiagnostics;
645 };
646 typedef DelayedDiagnosticsState ParsingDeclState;
647 typedef DelayedDiagnosticsState ProcessingContextState;
648
649 /// A class which encapsulates the logic for delaying diagnostics
650 /// during parsing and other processing.
651 class DelayedDiagnostics {
652 /// \brief The current pool of diagnostics into which delayed
653 /// diagnostics should go.
654 sema::DelayedDiagnosticPool *CurPool;
655
656 public:
657 DelayedDiagnostics() : CurPool(nullptr) {}
658
659 /// Adds a delayed diagnostic.
660 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
661
662 /// Determines whether diagnostics should be delayed.
663 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
664
665 /// Returns the current delayed-diagnostics pool.
666 sema::DelayedDiagnosticPool *getCurrentPool() const {
667 return CurPool;
668 }
669
670 /// Enter a new scope. Access and deprecation diagnostics will be
671 /// collected in this pool.
672 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
673 DelayedDiagnosticsState state;
674 state.SavedPool = CurPool;
675 CurPool = &pool;
676 return state;
677 }
678
679 /// Leave a delayed-diagnostic state that was previously pushed.
680 /// Do not emit any of the diagnostics. This is performed as part
681 /// of the bookkeeping of popping a pool "properly".
682 void popWithoutEmitting(DelayedDiagnosticsState state) {
683 CurPool = state.SavedPool;
684 }
685
686 /// Enter a new scope where access and deprecation diagnostics are
687 /// not delayed.
688 DelayedDiagnosticsState pushUndelayed() {
689 DelayedDiagnosticsState state;
690 state.SavedPool = CurPool;
691 CurPool = nullptr;
692 return state;
693 }
694
695 /// Undo a previous pushUndelayed().
696 void popUndelayed(DelayedDiagnosticsState state) {
697 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 697, __extension__ __PRETTY_FUNCTION__))
;
698 CurPool = state.SavedPool;
699 }
700 } DelayedDiagnostics;
701
702 /// A RAII object to temporarily push a declaration context.
703 class ContextRAII {
704 private:
705 Sema &S;
706 DeclContext *SavedContext;
707 ProcessingContextState SavedContextState;
708 QualType SavedCXXThisTypeOverride;
709
710 public:
711 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
712 : S(S), SavedContext(S.CurContext),
713 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
714 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
715 {
716 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 716, __extension__ __PRETTY_FUNCTION__))
;
717 S.CurContext = ContextToPush;
718 if (NewThisContext)
719 S.CXXThisTypeOverride = QualType();
720 }
721
722 void pop() {
723 if (!SavedContext) return;
724 S.CurContext = SavedContext;
725 S.DelayedDiagnostics.popUndelayed(SavedContextState);
726 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
727 SavedContext = nullptr;
728 }
729
730 ~ContextRAII() {
731 pop();
732 }
733 };
734
735 /// \brief RAII object to handle the state changes required to synthesize
736 /// a function body.
737 class SynthesizedFunctionScope {
738 Sema &S;
739 Sema::ContextRAII SavedContext;
740 bool PushedCodeSynthesisContext = false;
741
742 public:
743 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
744 : S(S), SavedContext(S, DC) {
745 S.PushFunctionScope();
746 S.PushExpressionEvaluationContext(
747 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
748 if (auto *FD = dyn_cast<FunctionDecl>(DC))
749 FD->setWillHaveBody(true);
750 else
751 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 751, __extension__ __PRETTY_FUNCTION__))
;
752 }
753
754 void addContextNote(SourceLocation UseLoc) {
755 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 755, __extension__ __PRETTY_FUNCTION__))
;
756
757 Sema::CodeSynthesisContext Ctx;
758 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
759 Ctx.PointOfInstantiation = UseLoc;
760 Ctx.Entity = cast<Decl>(S.CurContext);
761 S.pushCodeSynthesisContext(Ctx);
762
763 PushedCodeSynthesisContext = true;
764 }
765
766 ~SynthesizedFunctionScope() {
767 if (PushedCodeSynthesisContext)
768 S.popCodeSynthesisContext();
769 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
770 FD->setWillHaveBody(false);
771 S.PopExpressionEvaluationContext();
772 S.PopFunctionScopeInfo();
773 }
774 };
775
776 /// WeakUndeclaredIdentifiers - Identifiers contained in
777 /// \#pragma weak before declared. rare. may alias another
778 /// identifier, declared or undeclared
779 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
780
781 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
782 /// \#pragma redefine_extname before declared. Used in Solaris system headers
783 /// to define functions that occur in multiple standards to call the version
784 /// in the currently selected standard.
785 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
786
787
788 /// \brief Load weak undeclared identifiers from the external source.
789 void LoadExternalWeakUndeclaredIdentifiers();
790
791 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
792 /// \#pragma weak during processing of other Decls.
793 /// I couldn't figure out a clean way to generate these in-line, so
794 /// we store them here and handle separately -- which is a hack.
795 /// It would be best to refactor this.
796 SmallVector<Decl*,2> WeakTopLevelDecl;
797
798 IdentifierResolver IdResolver;
799
800 /// Translation Unit Scope - useful to Objective-C actions that need
801 /// to lookup file scope declarations in the "ordinary" C decl namespace.
802 /// For example, user-defined classes, built-in "id" type, etc.
803 Scope *TUScope;
804
805 /// \brief The C++ "std" namespace, where the standard library resides.
806 LazyDeclPtr StdNamespace;
807
808 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
809 /// standard library.
810 LazyDeclPtr StdBadAlloc;
811
812 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
813 /// standard library.
814 LazyDeclPtr StdAlignValT;
815
816 /// \brief The C++ "std::experimental" namespace, where the experimental parts
817 /// of the standard library resides.
818 NamespaceDecl *StdExperimentalNamespaceCache;
819
820 /// \brief The C++ "std::initializer_list" template, which is defined in
821 /// \<initializer_list>.
822 ClassTemplateDecl *StdInitializerList;
823
824 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
825 RecordDecl *CXXTypeInfoDecl;
826
827 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
828 RecordDecl *MSVCGuidDecl;
829
830 /// \brief Caches identifiers/selectors for NSFoundation APIs.
831 std::unique_ptr<NSAPI> NSAPIObj;
832
833 /// \brief The declaration of the Objective-C NSNumber class.
834 ObjCInterfaceDecl *NSNumberDecl;
835
836 /// \brief The declaration of the Objective-C NSValue class.
837 ObjCInterfaceDecl *NSValueDecl;
838
839 /// \brief Pointer to NSNumber type (NSNumber *).
840 QualType NSNumberPointer;
841
842 /// \brief Pointer to NSValue type (NSValue *).
843 QualType NSValuePointer;
844
845 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
846 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
847
848 /// \brief The declaration of the Objective-C NSString class.
849 ObjCInterfaceDecl *NSStringDecl;
850
851 /// \brief Pointer to NSString type (NSString *).
852 QualType NSStringPointer;
853
854 /// \brief The declaration of the stringWithUTF8String: method.
855 ObjCMethodDecl *StringWithUTF8StringMethod;
856
857 /// \brief The declaration of the valueWithBytes:objCType: method.
858 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
859
860 /// \brief The declaration of the Objective-C NSArray class.
861 ObjCInterfaceDecl *NSArrayDecl;
862
863 /// \brief The declaration of the arrayWithObjects:count: method.
864 ObjCMethodDecl *ArrayWithObjectsMethod;
865
866 /// \brief The declaration of the Objective-C NSDictionary class.
867 ObjCInterfaceDecl *NSDictionaryDecl;
868
869 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
870 ObjCMethodDecl *DictionaryWithObjectsMethod;
871
872 /// \brief id<NSCopying> type.
873 QualType QIDNSCopying;
874
875 /// \brief will hold 'respondsToSelector:'
876 Selector RespondsToSelectorSel;
877
878 /// A flag to remember whether the implicit forms of operator new and delete
879 /// have been declared.
880 bool GlobalNewDeleteDeclared;
881
882 /// A flag to indicate that we're in a context that permits abstract
883 /// references to fields. This is really a
884 bool AllowAbstractFieldReference;
885
886 /// \brief Describes how the expressions currently being parsed are
887 /// evaluated at run-time, if at all.
888 enum class ExpressionEvaluationContext {
889 /// \brief The current expression and its subexpressions occur within an
890 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
891 /// \c sizeof, where the type of the expression may be significant but
892 /// no code will be generated to evaluate the value of the expression at
893 /// run time.
894 Unevaluated,
895
896 /// \brief The current expression occurs within a braced-init-list within
897 /// an unevaluated operand. This is mostly like a regular unevaluated
898 /// context, except that we still instantiate constexpr functions that are
899 /// referenced here so that we can perform narrowing checks correctly.
900 UnevaluatedList,
901
902 /// \brief The current expression occurs within a discarded statement.
903 /// This behaves largely similarly to an unevaluated operand in preventing
904 /// definitions from being required, but not in other ways.
905 DiscardedStatement,
906
907 /// \brief The current expression occurs within an unevaluated
908 /// operand that unconditionally permits abstract references to
909 /// fields, such as a SIZE operator in MS-style inline assembly.
910 UnevaluatedAbstract,
911
912 /// \brief The current context is "potentially evaluated" in C++11 terms,
913 /// but the expression is evaluated at compile-time (like the values of
914 /// cases in a switch statement).
915 ConstantEvaluated,
916
917 /// \brief The current expression is potentially evaluated at run time,
918 /// which means that code may be generated to evaluate the value of the
919 /// expression at run time.
920 PotentiallyEvaluated,
921
922 /// \brief The current expression is potentially evaluated, but any
923 /// declarations referenced inside that expression are only used if
924 /// in fact the current expression is used.
925 ///
926 /// This value is used when parsing default function arguments, for which
927 /// we would like to provide diagnostics (e.g., passing non-POD arguments
928 /// through varargs) but do not want to mark declarations as "referenced"
929 /// until the default argument is used.
930 PotentiallyEvaluatedIfUsed
931 };
932
933 /// \brief Data structure used to record current or nested
934 /// expression evaluation contexts.
935 struct ExpressionEvaluationContextRecord {
936 /// \brief The expression evaluation context.
937 ExpressionEvaluationContext Context;
938
939 /// \brief Whether the enclosing context needed a cleanup.
940 CleanupInfo ParentCleanup;
941
942 /// \brief Whether we are in a decltype expression.
943 bool IsDecltype;
944
945 /// \brief The number of active cleanup objects when we entered
946 /// this expression evaluation context.
947 unsigned NumCleanupObjects;
948
949 /// \brief The number of typos encountered during this expression evaluation
950 /// context (i.e. the number of TypoExprs created).
951 unsigned NumTypos;
952
953 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
954
955 /// \brief The lambdas that are present within this context, if it
956 /// is indeed an unevaluated context.
957 SmallVector<LambdaExpr *, 2> Lambdas;
958
959 /// \brief The declaration that provides context for lambda expressions
960 /// and block literals if the normal declaration context does not
961 /// suffice, e.g., in a default function argument.
962 Decl *ManglingContextDecl;
963
964 /// \brief The context information used to mangle lambda expressions
965 /// and block literals within this context.
966 ///
967 /// This mangling information is allocated lazily, since most contexts
968 /// do not have lambda expressions or block literals.
969 std::unique_ptr<MangleNumberingContext> MangleNumbering;
970
971 /// \brief If we are processing a decltype type, a set of call expressions
972 /// for which we have deferred checking the completeness of the return type.
973 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
974
975 /// \brief If we are processing a decltype type, a set of temporary binding
976 /// expressions for which we have deferred checking the destructor.
977 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
978
979 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
980 unsigned NumCleanupObjects,
981 CleanupInfo ParentCleanup,
982 Decl *ManglingContextDecl,
983 bool IsDecltype)
984 : Context(Context), ParentCleanup(ParentCleanup),
985 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
986 NumTypos(0),
987 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
988
989 /// \brief Retrieve the mangling numbering context, used to consistently
990 /// number constructs like lambdas for mangling.
991 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
992
993 bool isUnevaluated() const {
994 return Context == ExpressionEvaluationContext::Unevaluated ||
995 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
996 Context == ExpressionEvaluationContext::UnevaluatedList;
997 }
998 bool isConstantEvaluated() const {
999 return Context == ExpressionEvaluationContext::ConstantEvaluated;
1000 }
1001 };
1002
1003 /// A stack of expression evaluation contexts.
1004 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1005
1006 /// \brief Compute the mangling number context for a lambda expression or
1007 /// block literal.
1008 ///
1009 /// \param DC - The DeclContext containing the lambda expression or
1010 /// block literal.
1011 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
1012 /// associated with the context, if relevant.
1013 MangleNumberingContext *getCurrentMangleNumberContext(
1014 const DeclContext *DC,
1015 Decl *&ManglingContextDecl);
1016
1017
1018 /// SpecialMemberOverloadResult - The overloading result for a special member
1019 /// function.
1020 ///
1021 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1022 /// integer are used to determine whether overload resolution succeeded.
1023 class SpecialMemberOverloadResult {
1024 public:
1025 enum Kind {
1026 NoMemberOrDeleted,
1027 Ambiguous,
1028 Success
1029 };
1030
1031 private:
1032 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
1033
1034 public:
1035 SpecialMemberOverloadResult() : Pair() {}
1036 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1037 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1038
1039 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1040 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1041
1042 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1043 void setKind(Kind K) { Pair.setInt(K); }
1044 };
1045
1046 class SpecialMemberOverloadResultEntry
1047 : public llvm::FastFoldingSetNode,
1048 public SpecialMemberOverloadResult {
1049 public:
1050 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1051 : FastFoldingSetNode(ID)
1052 {}
1053 };
1054
1055 /// \brief A cache of special member function overload resolution results
1056 /// for C++ records.
1057 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1058
1059 /// \brief A cache of the flags available in enumerations with the flag_bits
1060 /// attribute.
1061 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1062
1063 /// \brief The kind of translation unit we are processing.
1064 ///
1065 /// When we're processing a complete translation unit, Sema will perform
1066 /// end-of-translation-unit semantic tasks (such as creating
1067 /// initializers for tentative definitions in C) once parsing has
1068 /// completed. Modules and precompiled headers perform different kinds of
1069 /// checks.
1070 TranslationUnitKind TUKind;
1071
1072 llvm::BumpPtrAllocator BumpAlloc;
1073
1074 /// \brief The number of SFINAE diagnostics that have been trapped.
1075 unsigned NumSFINAEErrors;
1076
1077 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1078 UnparsedDefaultArgInstantiationsMap;
1079
1080 /// \brief A mapping from parameters with unparsed default arguments to the
1081 /// set of instantiations of each parameter.
1082 ///
1083 /// This mapping is a temporary data structure used when parsing
1084 /// nested class templates or nested classes of class templates,
1085 /// where we might end up instantiating an inner class before the
1086 /// default arguments of its methods have been parsed.
1087 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1088
1089 // Contains the locations of the beginning of unparsed default
1090 // argument locations.
1091 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1092
1093 /// UndefinedInternals - all the used, undefined objects which require a
1094 /// definition in this translation unit.
1095 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1096
1097 /// Determine if VD, which must be a variable or function, is an external
1098 /// symbol that nonetheless can't be referenced from outside this translation
1099 /// unit because its type has no linkage and it's not extern "C".
1100 bool isExternalWithNoLinkageType(ValueDecl *VD);
1101
1102 /// Obtain a sorted list of functions that are undefined but ODR-used.
1103 void getUndefinedButUsed(
1104 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1105
1106 /// Retrieves list of suspicious delete-expressions that will be checked at
1107 /// the end of translation unit.
1108 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1109 getMismatchingDeleteExpressions() const;
1110
1111 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1112 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1113
1114 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1115 /// We need to maintain a list, since selectors can have differing signatures
1116 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1117 /// of selectors are "overloaded").
1118 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1119 /// methods inside categories with a particular selector.
1120 GlobalMethodPool MethodPool;
1121
1122 /// Method selectors used in a \@selector expression. Used for implementation
1123 /// of -Wselector.
1124 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1125
1126 /// Kinds of C++ special members.
1127 enum CXXSpecialMember {
1128 CXXDefaultConstructor,
1129 CXXCopyConstructor,
1130 CXXMoveConstructor,
1131 CXXCopyAssignment,
1132 CXXMoveAssignment,
1133 CXXDestructor,
1134 CXXInvalid
1135 };
1136
1137 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1138 SpecialMemberDecl;
1139
1140 /// The C++ special members which we are currently in the process of
1141 /// declaring. If this process recursively triggers the declaration of the
1142 /// same special member, we should act as if it is not yet declared.
1143 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1144
1145 /// The function definitions which were renamed as part of typo-correction
1146 /// to match their respective declarations. We want to keep track of them
1147 /// to ensure that we don't emit a "redefinition" error if we encounter a
1148 /// correctly named definition after the renamed definition.
1149 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1150
1151 /// Stack of types that correspond to the parameter entities that are
1152 /// currently being copy-initialized. Can be empty.
1153 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1154
1155 void ReadMethodPool(Selector Sel);
1156 void updateOutOfDateSelector(Selector Sel);
1157
1158 /// Private Helper predicate to check for 'self'.
1159 bool isSelfExpr(Expr *RExpr);
1160 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1161
1162 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1163 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1164 /// should not be used elsewhere.
1165 void EmitCurrentDiagnostic(unsigned DiagID);
1166
1167 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1168 /// statements.
1169 class FPContractStateRAII {
1170 public:
1171 FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1172 ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1173
1174 private:
1175 Sema& S;
1176 FPOptions OldFPFeaturesState;
1177 };
1178
1179 void addImplicitTypedef(StringRef Name, QualType T);
1180
1181public:
1182 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1183 TranslationUnitKind TUKind = TU_Complete,
1184 CodeCompleteConsumer *CompletionConsumer = nullptr);
1185 ~Sema();
1186
1187 /// \brief Perform initialization that occurs after the parser has been
1188 /// initialized but before it parses anything.
1189 void Initialize();
1190
1191 const LangOptions &getLangOpts() const { return LangOpts; }
1192 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1193 FPOptions &getFPOptions() { return FPFeatures; }
1194
1195 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1196 SourceManager &getSourceManager() const { return SourceMgr; }
1197 Preprocessor &getPreprocessor() const { return PP; }
1198 ASTContext &getASTContext() const { return Context; }
1199 ASTConsumer &getASTConsumer() const { return Consumer; }
1200 ASTMutationListener *getASTMutationListener() const;
1201 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1202
1203 ///\brief Registers an external source. If an external source already exists,
1204 /// creates a multiplex external source and appends to it.
1205 ///
1206 ///\param[in] E - A non-null external sema source.
1207 ///
1208 void addExternalSource(ExternalSemaSource *E);
1209
1210 void PrintStats() const;
1211
1212 /// \brief Helper class that creates diagnostics with optional
1213 /// template instantiation stacks.
1214 ///
1215 /// This class provides a wrapper around the basic DiagnosticBuilder
1216 /// class that emits diagnostics. SemaDiagnosticBuilder is
1217 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1218 /// does) and, if the diagnostic comes from inside a template
1219 /// instantiation, printing the template instantiation stack as
1220 /// well.
1221 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1222 Sema &SemaRef;
1223 unsigned DiagID;
1224
1225 public:
1226 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1227 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1228
1229 // This is a cunning lie. DiagnosticBuilder actually performs move
1230 // construction in its copy constructor (but due to varied uses, it's not
1231 // possible to conveniently express this as actual move construction). So
1232 // the default copy ctor here is fine, because the base class disables the
1233 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1234 // in that case anwyay.
1235 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1236
1237 ~SemaDiagnosticBuilder() {
1238 // If we aren't active, there is nothing to do.
1239 if (!isActive()) return;
1240
1241 // Otherwise, we need to emit the diagnostic. First flush the underlying
1242 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1243 // won't emit the diagnostic in its own destructor.
1244 //
1245 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1246 // do its own needless checks to see if the diagnostic needs to be
1247 // emitted. However, because we take care to ensure that the builder
1248 // objects never escape, a sufficiently smart compiler will be able to
1249 // eliminate that code.
1250 FlushCounts();
1251 Clear();
1252
1253 // Dispatch to Sema to emit the diagnostic.
1254 SemaRef.EmitCurrentDiagnostic(DiagID);
1255 }
1256
1257 /// Teach operator<< to produce an object of the correct type.
1258 template<typename T>
1259 friend const SemaDiagnosticBuilder &operator<<(
1260 const SemaDiagnosticBuilder &Diag, const T &Value) {
1261 const DiagnosticBuilder &BaseDiag = Diag;
1262 BaseDiag << Value;
1263 return Diag;
1264 }
1265 };
1266
1267 /// \brief Emit a diagnostic.
1268 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1269 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1270 return SemaDiagnosticBuilder(DB, *this, DiagID);
1271 }
1272
1273 /// \brief Emit a partial diagnostic.
1274 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1275
1276 /// \brief Build a partial diagnostic.
1277 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1278
1279 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1280
1281 /// \brief Get a string to suggest for zero-initialization of a type.
1282 std::string
1283 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1284 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1285
1286 /// \brief Calls \c Lexer::getLocForEndOfToken()
1287 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1288
1289 /// \brief Retrieve the module loader associated with the preprocessor.
1290 ModuleLoader &getModuleLoader() const;
1291
1292 void emitAndClearUnusedLocalTypedefWarnings();
1293
1294 void ActOnStartOfTranslationUnit();
1295 void ActOnEndOfTranslationUnit();
1296
1297 void CheckDelegatingCtorCycles();
1298
1299 Scope *getScopeForContext(DeclContext *Ctx);
1300
1301 void PushFunctionScope();
1302 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1303 sema::LambdaScopeInfo *PushLambdaScope();
1304
1305 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1306 /// is during Parsing. Currently it is used to pass on the depth
1307 /// when parsing generic lambda 'auto' parameters.
1308 void RecordParsingTemplateParameterDepth(unsigned Depth);
1309
1310 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1311 RecordDecl *RD,
1312 CapturedRegionKind K);
1313 void
1314 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1315 const Decl *D = nullptr,
1316 const BlockExpr *blkExpr = nullptr);
1317
1318 sema::FunctionScopeInfo *getCurFunction() const {
1319 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1320 }
1321
1322 sema::FunctionScopeInfo *getEnclosingFunction() const;
1323
1324 void setFunctionHasBranchIntoScope();
1325 void setFunctionHasBranchProtectedScope();
1326 void setFunctionHasIndirectGoto();
1327
1328 void PushCompoundScope(bool IsStmtExpr);
1329 void PopCompoundScope();
1330
1331 sema::CompoundScopeInfo &getCurCompoundScope() const;
1332
1333 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1334
1335 /// \brief Retrieve the current block, if any.
1336 sema::BlockScopeInfo *getCurBlock();
1337
1338 /// Retrieve the current lambda scope info, if any.
1339 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1340 /// lambda scope info ignoring all inner capturing scopes that are not
1341 /// lambda scopes.
1342 sema::LambdaScopeInfo *
1343 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1344
1345 /// \brief Retrieve the current generic lambda info, if any.
1346 sema::LambdaScopeInfo *getCurGenericLambda();
1347
1348 /// \brief Retrieve the current captured region, if any.
1349 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1350
1351 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1352 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1353
1354 void ActOnComment(SourceRange Comment);
1355
1356 //===--------------------------------------------------------------------===//
1357 // Type Analysis / Processing: SemaType.cpp.
1358 //
1359
1360 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1361 const DeclSpec *DS = nullptr);
1362 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1363 const DeclSpec *DS = nullptr);
1364 QualType BuildPointerType(QualType T,
1365 SourceLocation Loc, DeclarationName Entity);
1366 QualType BuildReferenceType(QualType T, bool LValueRef,
1367 SourceLocation Loc, DeclarationName Entity);
1368 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1369 Expr *ArraySize, unsigned Quals,
1370 SourceRange Brackets, DeclarationName Entity);
1371 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1372 SourceLocation AttrLoc);
1373 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
1374 SourceLocation AttrLoc);
1375
1376 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1377
1378 /// \brief Build a function type.
1379 ///
1380 /// This routine checks the function type according to C++ rules and
1381 /// under the assumption that the result type and parameter types have
1382 /// just been instantiated from a template. It therefore duplicates
1383 /// some of the behavior of GetTypeForDeclarator, but in a much
1384 /// simpler form that is only suitable for this narrow use case.
1385 ///
1386 /// \param T The return type of the function.
1387 ///
1388 /// \param ParamTypes The parameter types of the function. This array
1389 /// will be modified to account for adjustments to the types of the
1390 /// function parameters.
1391 ///
1392 /// \param Loc The location of the entity whose type involves this
1393 /// function type or, if there is no such entity, the location of the
1394 /// type that will have function type.
1395 ///
1396 /// \param Entity The name of the entity that involves the function
1397 /// type, if known.
1398 ///
1399 /// \param EPI Extra information about the function type. Usually this will
1400 /// be taken from an existing function with the same prototype.
1401 ///
1402 /// \returns A suitable function type, if there are no errors. The
1403 /// unqualified type will always be a FunctionProtoType.
1404 /// Otherwise, returns a NULL type.
1405 QualType BuildFunctionType(QualType T,
1406 MutableArrayRef<QualType> ParamTypes,
1407 SourceLocation Loc, DeclarationName Entity,
1408 const FunctionProtoType::ExtProtoInfo &EPI);
1409
1410 QualType BuildMemberPointerType(QualType T, QualType Class,
1411 SourceLocation Loc,
1412 DeclarationName Entity);
1413 QualType BuildBlockPointerType(QualType T,
1414 SourceLocation Loc, DeclarationName Entity);
1415 QualType BuildParenType(QualType T);
1416 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1417 QualType BuildReadPipeType(QualType T,
1418 SourceLocation Loc);
1419 QualType BuildWritePipeType(QualType T,
1420 SourceLocation Loc);
1421
1422 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1423 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1424 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1425 TypeSourceInfo *ReturnTypeInfo);
1426
1427 /// \brief Package the given type and TSI into a ParsedType.
1428 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1429 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1430 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1431 static QualType GetTypeFromParser(ParsedType Ty,
1432 TypeSourceInfo **TInfo = nullptr);
1433 CanThrowResult canThrow(const Expr *E);
1434 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1435 const FunctionProtoType *FPT);
1436 void UpdateExceptionSpec(FunctionDecl *FD,
1437 const FunctionProtoType::ExceptionSpecInfo &ESI);
1438 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1439 bool CheckDistantExceptionSpec(QualType T);
1440 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1441 bool CheckEquivalentExceptionSpec(
1442 const FunctionProtoType *Old, SourceLocation OldLoc,
1443 const FunctionProtoType *New, SourceLocation NewLoc);
1444 bool CheckEquivalentExceptionSpec(
1445 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1446 const FunctionProtoType *Old, SourceLocation OldLoc,
1447 const FunctionProtoType *New, SourceLocation NewLoc);
1448 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
1449 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1450 const PartialDiagnostic &NestedDiagID,
1451 const PartialDiagnostic &NoteID,
1452 const FunctionProtoType *Superset,
1453 SourceLocation SuperLoc,
1454 const FunctionProtoType *Subset,
1455 SourceLocation SubLoc);
1456 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1457 const PartialDiagnostic &NoteID,
1458 const FunctionProtoType *Target,
1459 SourceLocation TargetLoc,
1460 const FunctionProtoType *Source,
1461 SourceLocation SourceLoc);
1462
1463 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1464
1465 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1466 /// in an Objective-C message declaration. Return the appropriate type.
1467 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1468
1469 /// \brief Abstract class used to diagnose incomplete types.
1470 struct TypeDiagnoser {
1471 TypeDiagnoser() {}
1472
1473 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1474 virtual ~TypeDiagnoser() {}
1475 };
1476
1477 static int getPrintable(int I) { return I; }
1478 static unsigned getPrintable(unsigned I) { return I; }
1479 static bool getPrintable(bool B) { return B; }
1480 static const char * getPrintable(const char *S) { return S; }
1481 static StringRef getPrintable(StringRef S) { return S; }
1482 static const std::string &getPrintable(const std::string &S) { return S; }
1483 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1484 return II;
1485 }
1486 static DeclarationName getPrintable(DeclarationName N) { return N; }
1487 static QualType getPrintable(QualType T) { return T; }
1488 static SourceRange getPrintable(SourceRange R) { return R; }
1489 static SourceRange getPrintable(SourceLocation L) { return L; }
1490 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1491 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1492
1493 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1494 unsigned DiagID;
1495 std::tuple<const Ts &...> Args;
1496
1497 template <std::size_t... Is>
1498 void emit(const SemaDiagnosticBuilder &DB,
1499 llvm::index_sequence<Is...>) const {
1500 // Apply all tuple elements to the builder in order.
1501 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1502 (void)Dummy;
1503 }
1504
1505 public:
1506 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1507 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1508 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1508, __extension__ __PRETTY_FUNCTION__))
;
1509 }
1510
1511 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1512 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1513 emit(DB, llvm::index_sequence_for<Ts...>());
1514 DB << T;
1515 }
1516 };
1517
1518private:
1519 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1520 TypeDiagnoser *Diagnoser);
1521
1522 struct ModuleScope {
1523 clang::Module *Module = nullptr;
1524 bool ModuleInterface = false;
1525 VisibleModuleSet OuterVisibleModules;
1526 };
1527 /// The modules we're currently parsing.
1528 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1529
1530 /// Get the module whose scope we are currently within.
1531 Module *getCurrentModule() const {
1532 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
1533 }
1534
1535 VisibleModuleSet VisibleModules;
1536
1537public:
1538 /// \brief Get the module owning an entity.
1539 Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
1540
1541 /// \brief Make a merged definition of an existing hidden definition \p ND
1542 /// visible at the specified location.
1543 void makeMergedDefinitionVisible(NamedDecl *ND);
1544
1545 bool isModuleVisible(const Module *M) { return VisibleModules.isVisible(M); }
1546
1547 /// Determine whether a declaration is visible to name lookup.
1548 bool isVisible(const NamedDecl *D) {
1549 return !D->isHidden() || isVisibleSlow(D);
1550 }
1551
1552 /// Determine whether any declaration of an entity is visible.
1553 bool
1554 hasVisibleDeclaration(const NamedDecl *D,
1555 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1556 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1557 }
1558 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1559 llvm::SmallVectorImpl<Module *> *Modules);
1560
1561 bool hasVisibleMergedDefinition(NamedDecl *Def);
1562 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
1563
1564 /// Determine if \p D and \p Suggested have a structurally compatible
1565 /// layout as described in C11 6.2.7/1.
1566 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
1567
1568 /// Determine if \p D has a visible definition. If not, suggest a declaration
1569 /// that should be made visible to expose the definition.
1570 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1571 bool OnlyNeedComplete = false);
1572 bool hasVisibleDefinition(const NamedDecl *D) {
1573 NamedDecl *Hidden;
1574 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1575 }
1576
1577 /// Determine if the template parameter \p D has a visible default argument.
1578 bool
1579 hasVisibleDefaultArgument(const NamedDecl *D,
1580 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1581
1582 /// Determine if there is a visible declaration of \p D that is an explicit
1583 /// specialization declaration for a specialization of a template. (For a
1584 /// member specialization, use hasVisibleMemberSpecialization.)
1585 bool hasVisibleExplicitSpecialization(
1586 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1587
1588 /// Determine if there is a visible declaration of \p D that is a member
1589 /// specialization declaration (as opposed to an instantiated declaration).
1590 bool hasVisibleMemberSpecialization(
1591 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1592
1593 /// Determine if \p A and \p B are equivalent internal linkage declarations
1594 /// from different modules, and thus an ambiguity error can be downgraded to
1595 /// an extension warning.
1596 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1597 const NamedDecl *B);
1598 void diagnoseEquivalentInternalLinkageDeclarations(
1599 SourceLocation Loc, const NamedDecl *D,
1600 ArrayRef<const NamedDecl *> Equiv);
1601
1602 bool isCompleteType(SourceLocation Loc, QualType T) {
1603 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1604 }
1605 bool RequireCompleteType(SourceLocation Loc, QualType T,
1606 TypeDiagnoser &Diagnoser);
1607 bool RequireCompleteType(SourceLocation Loc, QualType T,
1608 unsigned DiagID);
1609
1610 template <typename... Ts>
1611 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1612 const Ts &...Args) {
1613 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1614 return RequireCompleteType(Loc, T, Diagnoser);
1615 }
1616
1617 void completeExprArrayBound(Expr *E);
1618 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1619 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1620
1621 template <typename... Ts>
1622 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1623 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1624 return RequireCompleteExprType(E, Diagnoser);
1625 }
1626
1627 bool RequireLiteralType(SourceLocation Loc, QualType T,
1628 TypeDiagnoser &Diagnoser);
1629 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1630
1631 template <typename... Ts>
1632 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1633 const Ts &...Args) {
1634 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1635 return RequireLiteralType(Loc, T, Diagnoser);
1636 }
1637
1638 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1639 const CXXScopeSpec &SS, QualType T);
1640
1641 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1642 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1643 /// context, such as when building a type for decltype(auto).
1644 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1645 bool AsUnevaluated = true);
1646 QualType BuildUnaryTransformType(QualType BaseType,
1647 UnaryTransformType::UTTKind UKind,
1648 SourceLocation Loc);
1649
1650 //===--------------------------------------------------------------------===//
1651 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1652 //
1653
1654 struct SkipBodyInfo {
1655 SkipBodyInfo()
1656 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
1657 New(nullptr) {}
1658 bool ShouldSkip;
1659 bool CheckSameAsPrevious;
1660 NamedDecl *Previous;
1661 NamedDecl *New;
1662 };
1663
1664 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1665
1666 void DiagnoseUseOfUnimplementedSelectors();
1667
1668 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1669
1670 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1671 Scope *S, CXXScopeSpec *SS = nullptr,
1672 bool isClassName = false, bool HasTrailingDot = false,
1673 ParsedType ObjectType = nullptr,
1674 bool IsCtorOrDtorName = false,
1675 bool WantNontrivialTypeSourceInfo = false,
1676 bool IsClassTemplateDeductionContext = true,
1677 IdentifierInfo **CorrectedII = nullptr);
1678 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1679 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1680 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1681 SourceLocation IILoc,
1682 Scope *S,
1683 CXXScopeSpec *SS,
1684 ParsedType &SuggestedType,
1685 bool IsTemplateName = false);
1686
1687 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1688 /// type name has failed in a dependent context. In these situations, we
1689 /// automatically form a DependentTypeName that will retry lookup in a related
1690 /// scope during instantiation.
1691 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1692 SourceLocation NameLoc,
1693 bool IsTemplateTypeArg);
1694
1695 /// \brief Describes the result of the name lookup and resolution performed
1696 /// by \c ClassifyName().
1697 enum NameClassificationKind {
1698 NC_Unknown,
1699 NC_Error,
1700 NC_Keyword,
1701 NC_Type,
1702 NC_Expression,
1703 NC_NestedNameSpecifier,
1704 NC_TypeTemplate,
1705 NC_VarTemplate,
1706 NC_FunctionTemplate
1707 };
1708
1709 class NameClassification {
1710 NameClassificationKind Kind;
1711 ExprResult Expr;
1712 TemplateName Template;
1713 ParsedType Type;
1714
1715 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1716
1717 public:
1718 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1719
1720 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1721
1722 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
1723
1724 static NameClassification Error() {
1725 return NameClassification(NC_Error);
1726 }
1727
1728 static NameClassification Unknown() {
1729 return NameClassification(NC_Unknown);
1730 }
1731
1732 static NameClassification NestedNameSpecifier() {
1733 return NameClassification(NC_NestedNameSpecifier);
1734 }
1735
1736 static NameClassification TypeTemplate(TemplateName Name) {
1737 NameClassification Result(NC_TypeTemplate);
1738 Result.Template = Name;
1739 return Result;
1740 }
1741
1742 static NameClassification VarTemplate(TemplateName Name) {
1743 NameClassification Result(NC_VarTemplate);
1744 Result.Template = Name;
1745 return Result;
1746 }
1747
1748 static NameClassification FunctionTemplate(TemplateName Name) {
1749 NameClassification Result(NC_FunctionTemplate);
1750 Result.Template = Name;
1751 return Result;
1752 }
1753
1754 NameClassificationKind getKind() const { return Kind; }
1755
1756 ParsedType getType() const {
1757 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1757, __extension__ __PRETTY_FUNCTION__))
;
1758 return Type;
1759 }
1760
1761 ExprResult getExpression() const {
1762 assert(Kind == NC_Expression)(static_cast <bool> (Kind == NC_Expression) ? void (0) :
__assert_fail ("Kind == NC_Expression", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1762, __extension__ __PRETTY_FUNCTION__))
;
1763 return Expr;
1764 }
1765
1766 TemplateName getTemplateName() const {
1767 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1768, __extension__ __PRETTY_FUNCTION__))
1768 Kind == NC_VarTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1768, __extension__ __PRETTY_FUNCTION__))
;
1769 return Template;
1770 }
1771
1772 TemplateNameKind getTemplateNameKind() const {
1773 switch (Kind) {
1774 case NC_TypeTemplate:
1775 return TNK_Type_template;
1776 case NC_FunctionTemplate:
1777 return TNK_Function_template;
1778 case NC_VarTemplate:
1779 return TNK_Var_template;
1780 default:
1781 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 1781)
;
1782 }
1783 }
1784 };
1785
1786 /// \brief Perform name lookup on the given name, classifying it based on
1787 /// the results of name lookup and the following token.
1788 ///
1789 /// This routine is used by the parser to resolve identifiers and help direct
1790 /// parsing. When the identifier cannot be found, this routine will attempt
1791 /// to correct the typo and classify based on the resulting name.
1792 ///
1793 /// \param S The scope in which we're performing name lookup.
1794 ///
1795 /// \param SS The nested-name-specifier that precedes the name.
1796 ///
1797 /// \param Name The identifier. If typo correction finds an alternative name,
1798 /// this pointer parameter will be updated accordingly.
1799 ///
1800 /// \param NameLoc The location of the identifier.
1801 ///
1802 /// \param NextToken The token following the identifier. Used to help
1803 /// disambiguate the name.
1804 ///
1805 /// \param IsAddressOfOperand True if this name is the operand of a unary
1806 /// address of ('&') expression, assuming it is classified as an
1807 /// expression.
1808 ///
1809 /// \param CCC The correction callback, if typo correction is desired.
1810 NameClassification
1811 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1812 SourceLocation NameLoc, const Token &NextToken,
1813 bool IsAddressOfOperand,
1814 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1815
1816 /// Describes the detailed kind of a template name. Used in diagnostics.
1817 enum class TemplateNameKindForDiagnostics {
1818 ClassTemplate,
1819 FunctionTemplate,
1820 VarTemplate,
1821 AliasTemplate,
1822 TemplateTemplateParam,
1823 DependentTemplate
1824 };
1825 TemplateNameKindForDiagnostics
1826 getTemplateNameKindForDiagnostics(TemplateName Name);
1827
1828 /// Determine whether it's plausible that E was intended to be a
1829 /// template-name.
1830 bool mightBeIntendedToBeTemplateName(ExprResult E) {
1831 if (!getLangOpts().CPlusPlus || E.isInvalid())
1832 return false;
1833 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
1834 return !DRE->hasExplicitTemplateArgs();
1835 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
1836 return !ME->hasExplicitTemplateArgs();
1837 // Any additional cases recognized here should also be handled by
1838 // diagnoseExprIntendedAsTemplateName.
1839 return false;
1840 }
1841 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
1842 SourceLocation Less,
1843 SourceLocation Greater);
1844
1845 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1846
1847 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1848 MultiTemplateParamsArg TemplateParameterLists);
1849 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1850 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1851 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1852 DeclarationName Name, SourceLocation Loc,
1853 bool IsTemplateId);
1854 void
1855 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1856 SourceLocation FallbackLoc,
1857 SourceLocation ConstQualLoc = SourceLocation(),
1858 SourceLocation VolatileQualLoc = SourceLocation(),
1859 SourceLocation RestrictQualLoc = SourceLocation(),
1860 SourceLocation AtomicQualLoc = SourceLocation(),
1861 SourceLocation UnalignedQualLoc = SourceLocation());
1862
1863 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1864 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1865 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1866 const LookupResult &R);
1867 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1868 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1869 const LookupResult &R);
1870 void CheckShadow(Scope *S, VarDecl *D);
1871
1872 /// Warn if 'E', which is an expression that is about to be modified, refers
1873 /// to a shadowing declaration.
1874 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1875
1876 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1877
1878private:
1879 /// Map of current shadowing declarations to shadowed declarations. Warn if
1880 /// it looks like the user is trying to modify the shadowing declaration.
1881 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1882
1883public:
1884 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1885 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1886 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1887 TypedefNameDecl *NewTD);
1888 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1889 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1890 TypeSourceInfo *TInfo,
1891 LookupResult &Previous);
1892 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1893 LookupResult &Previous, bool &Redeclaration);
1894 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1895 TypeSourceInfo *TInfo,
1896 LookupResult &Previous,
1897 MultiTemplateParamsArg TemplateParamLists,
1898 bool &AddToScope,
1899 ArrayRef<BindingDecl *> Bindings = None);
1900 NamedDecl *
1901 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1902 MultiTemplateParamsArg TemplateParamLists);
1903 // Returns true if the variable declaration is a redeclaration
1904 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1905 void CheckVariableDeclarationType(VarDecl *NewVD);
1906 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1907 Expr *Init);
1908 void CheckCompleteVariableDeclaration(VarDecl *VD);
1909 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1910 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1911
1912 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1913 TypeSourceInfo *TInfo,
1914 LookupResult &Previous,
1915 MultiTemplateParamsArg TemplateParamLists,
1916 bool &AddToScope);
1917 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1918
1919 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1920 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1921
1922 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1923 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1924 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1925 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1926 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1927 // Returns true if the function declaration is a redeclaration
1928 bool CheckFunctionDeclaration(Scope *S,
1929 FunctionDecl *NewFD, LookupResult &Previous,
1930 bool IsMemberSpecialization);
1931 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1932 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1933 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1934 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1935 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1936 SourceLocation Loc,
1937 QualType T);
1938 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1939 SourceLocation NameLoc, IdentifierInfo *Name,
1940 QualType T, TypeSourceInfo *TSInfo,
1941 StorageClass SC);
1942 void ActOnParamDefaultArgument(Decl *param,
1943 SourceLocation EqualLoc,
1944 Expr *defarg);
1945 void ActOnParamUnparsedDefaultArgument(Decl *param,
1946 SourceLocation EqualLoc,
1947 SourceLocation ArgLoc);
1948 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1949 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1950 SourceLocation EqualLoc);
1951
1952 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1953 void ActOnUninitializedDecl(Decl *dcl);
1954 void ActOnInitializerError(Decl *Dcl);
1955
1956 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1957 void ActOnCXXForRangeDecl(Decl *D);
1958 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1959 IdentifierInfo *Ident,
1960 ParsedAttributes &Attrs,
1961 SourceLocation AttrEnd);
1962 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1963 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1964 void FinalizeDeclaration(Decl *D);
1965 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1966 ArrayRef<Decl *> Group);
1967 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1968
1969 /// Should be called on all declarations that might have attached
1970 /// documentation comments.
1971 void ActOnDocumentableDecl(Decl *D);
1972 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1973
1974 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1975 SourceLocation LocAfterDecls);
1976 void CheckForFunctionRedefinition(
1977 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1978 SkipBodyInfo *SkipBody = nullptr);
1979 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1980 MultiTemplateParamsArg TemplateParamLists,
1981 SkipBodyInfo *SkipBody = nullptr);
1982 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1983 SkipBodyInfo *SkipBody = nullptr);
1984 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1985 bool isObjCMethodDecl(Decl *D) {
1986 return D && isa<ObjCMethodDecl>(D);
1987 }
1988
1989 /// \brief Determine whether we can delay parsing the body of a function or
1990 /// function template until it is used, assuming we don't care about emitting
1991 /// code for that function.
1992 ///
1993 /// This will be \c false if we may need the body of the function in the
1994 /// middle of parsing an expression (where it's impractical to switch to
1995 /// parsing a different function), for instance, if it's constexpr in C++11
1996 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1997 bool canDelayFunctionBody(const Declarator &D);
1998
1999 /// \brief Determine whether we can skip parsing the body of a function
2000 /// definition, assuming we don't care about analyzing its body or emitting
2001 /// code for that function.
2002 ///
2003 /// This will be \c false only if we may need the body of the function in
2004 /// order to parse the rest of the program (for instance, if it is
2005 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2006 bool canSkipFunctionBody(Decl *D);
2007
2008 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2009 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2010 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2011 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2012 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2013
2014 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2015 /// attribute for which parsing is delayed.
2016 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2017
2018 /// \brief Diagnose any unused parameters in the given sequence of
2019 /// ParmVarDecl pointers.
2020 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2021
2022 /// \brief Diagnose whether the size of parameters or return value of a
2023 /// function or obj-c method definition is pass-by-value and larger than a
2024 /// specified threshold.
2025 void
2026 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2027 QualType ReturnTy, NamedDecl *D);
2028
2029 void DiagnoseInvalidJumps(Stmt *Body);
2030 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2031 SourceLocation AsmLoc,
2032 SourceLocation RParenLoc);
2033
2034 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
2035 Decl *ActOnEmptyDeclaration(Scope *S,
2036 AttributeList *AttrList,
2037 SourceLocation SemiLoc);
2038
2039 enum class ModuleDeclKind {
2040 Interface, ///< 'export module X;'
2041 Implementation, ///< 'module X;'
2042 Partition, ///< 'module partition X;'
2043 };
2044
2045 /// The parser has processed a module-declaration that begins the definition
2046 /// of a module interface or implementation.
2047 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
2048 SourceLocation ModuleLoc, ModuleDeclKind MDK,
2049 ModuleIdPath Path);
2050
2051 /// \brief The parser has processed a module import declaration.
2052 ///
2053 /// \param AtLoc The location of the '@' symbol, if any.
2054 ///
2055 /// \param ImportLoc The location of the 'import' keyword.
2056 ///
2057 /// \param Path The module access path.
2058 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
2059 ModuleIdPath Path);
2060
2061 /// \brief The parser has processed a module import translated from a
2062 /// #include or similar preprocessing directive.
2063 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2064 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
2065
2066 /// \brief The parsed has entered a submodule.
2067 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
2068 /// \brief The parser has left a submodule.
2069 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
2070
2071 /// \brief Create an implicit import of the given module at the given
2072 /// source location, for error recovery, if possible.
2073 ///
2074 /// This routine is typically used when an entity found by name lookup
2075 /// is actually hidden within a module that we know about but the user
2076 /// has forgotten to import.
2077 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
2078 Module *Mod);
2079
2080 /// Kinds of missing import. Note, the values of these enumerators correspond
2081 /// to %select values in diagnostics.
2082 enum class MissingImportKind {
2083 Declaration,
2084 Definition,
2085 DefaultArgument,
2086 ExplicitSpecialization,
2087 PartialSpecialization
2088 };
2089
2090 /// \brief Diagnose that the specified declaration needs to be visible but
2091 /// isn't, and suggest a module import that would resolve the problem.
2092 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2093 MissingImportKind MIK, bool Recover = true);
2094 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
2095 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
2096 MissingImportKind MIK, bool Recover);
2097
2098 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
2099 SourceLocation LBraceLoc);
2100 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
2101 SourceLocation RBraceLoc);
2102
2103 /// \brief We've found a use of a templated declaration that would trigger an
2104 /// implicit instantiation. Check that any relevant explicit specializations
2105 /// and partial specializations are visible, and diagnose if not.
2106 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
2107
2108 /// \brief We've found a use of a template specialization that would select a
2109 /// partial specialization. Check that the partial specialization is visible,
2110 /// and diagnose if not.
2111 void checkPartialSpecializationVisibility(SourceLocation Loc,
2112 NamedDecl *Spec);
2113
2114 /// \brief Retrieve a suitable printing policy.
2115 PrintingPolicy getPrintingPolicy() const {
2116 return getPrintingPolicy(Context, PP);
2117 }
2118
2119 /// \brief Retrieve a suitable printing policy.
2120 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
2121 const Preprocessor &PP);
2122
2123 /// Scope actions.
2124 void ActOnPopScope(SourceLocation Loc, Scope *S);
2125 void ActOnTranslationUnitScope(Scope *S);
2126
2127 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2128 RecordDecl *&AnonRecord);
2129 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2130 MultiTemplateParamsArg TemplateParams,
2131 bool IsExplicitInstantiation,
2132 RecordDecl *&AnonRecord);
2133
2134 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2135 AccessSpecifier AS,
2136 RecordDecl *Record,
2137 const PrintingPolicy &Policy);
2138
2139 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2140 RecordDecl *Record);
2141
2142 /// Common ways to introduce type names without a tag for use in diagnostics.
2143 /// Keep in sync with err_tag_reference_non_tag.
2144 enum NonTagKind {
2145 NTK_NonStruct,
2146 NTK_NonClass,
2147 NTK_NonUnion,
2148 NTK_NonEnum,
2149 NTK_Typedef,
2150 NTK_TypeAlias,
2151 NTK_Template,
2152 NTK_TypeAliasTemplate,
2153 NTK_TemplateTemplateArgument,
2154 };
2155
2156 /// Given a non-tag type declaration, returns an enum useful for indicating
2157 /// what kind of non-tag type this is.
2158 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2159
2160 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2161 TagTypeKind NewTag, bool isDefinition,
2162 SourceLocation NewTagLoc,
2163 const IdentifierInfo *Name);
2164
2165 enum TagUseKind {
2166 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2167 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2168 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2169 TUK_Friend // Friend declaration: 'friend struct foo;'
2170 };
2171
2172 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2173 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
2174 SourceLocation NameLoc, AttributeList *Attr,
2175 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
2176 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
2177 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
2178 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2179 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
2180 SkipBodyInfo *SkipBody = nullptr);
2181
2182 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2183 unsigned TagSpec, SourceLocation TagLoc,
2184 CXXScopeSpec &SS,
2185 IdentifierInfo *Name, SourceLocation NameLoc,
2186 AttributeList *Attr,
2187 MultiTemplateParamsArg TempParamLists);
2188
2189 TypeResult ActOnDependentTag(Scope *S,
2190 unsigned TagSpec,
2191 TagUseKind TUK,
2192 const CXXScopeSpec &SS,
2193 IdentifierInfo *Name,
2194 SourceLocation TagLoc,
2195 SourceLocation NameLoc);
2196
2197 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2198 IdentifierInfo *ClassName,
2199 SmallVectorImpl<Decl *> &Decls);
2200 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2201 Declarator &D, Expr *BitfieldWidth);
2202
2203 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2204 Declarator &D, Expr *BitfieldWidth,
2205 InClassInitStyle InitStyle,
2206 AccessSpecifier AS);
2207 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2208 SourceLocation DeclStart,
2209 Declarator &D, Expr *BitfieldWidth,
2210 InClassInitStyle InitStyle,
2211 AccessSpecifier AS,
2212 AttributeList *MSPropertyAttr);
2213
2214 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2215 TypeSourceInfo *TInfo,
2216 RecordDecl *Record, SourceLocation Loc,
2217 bool Mutable, Expr *BitfieldWidth,
2218 InClassInitStyle InitStyle,
2219 SourceLocation TSSL,
2220 AccessSpecifier AS, NamedDecl *PrevDecl,
2221 Declarator *D = nullptr);
2222
2223 bool CheckNontrivialField(FieldDecl *FD);
2224 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2225
2226 enum TrivialABIHandling {
2227 /// The triviality of a method unaffected by "trivial_abi".
2228 TAH_IgnoreTrivialABI,
2229
2230 /// The triviality of a method affected by "trivial_abi".
2231 TAH_ConsiderTrivialABI
2232 };
2233
2234 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2235 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
2236 bool Diagnose = false);
2237 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2238 void ActOnLastBitfield(SourceLocation DeclStart,
2239 SmallVectorImpl<Decl *> &AllIvarDecls);
2240 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2241 Declarator &D, Expr *BitfieldWidth,
2242 tok::ObjCKeywordKind visibility);
2243
2244 // This is used for both record definitions and ObjC interface declarations.
2245 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2246 ArrayRef<Decl *> Fields,
2247 SourceLocation LBrac, SourceLocation RBrac,
2248 AttributeList *AttrList);
2249
2250 /// ActOnTagStartDefinition - Invoked when we have entered the
2251 /// scope of a tag's definition (e.g., for an enumeration, class,
2252 /// struct, or union).
2253 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2254
2255 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
2256 /// Differently from C++, actually parse the body and reject / error out
2257 /// in case of a structural mismatch.
2258 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
2259 SkipBodyInfo &SkipBody);
2260
2261 typedef void *SkippedDefinitionContext;
2262
2263 /// \brief Invoked when we enter a tag definition that we're skipping.
2264 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2265
2266 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2267
2268 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2269 /// C++ record definition's base-specifiers clause and are starting its
2270 /// member declarations.
2271 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2272 SourceLocation FinalLoc,
2273 bool IsFinalSpelledSealed,
2274 SourceLocation LBraceLoc);
2275
2276 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2277 /// the definition of a tag (enumeration, class, struct, or union).
2278 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2279 SourceRange BraceRange);
2280
2281 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2282
2283 void ActOnObjCContainerFinishDefinition();
2284
2285 /// \brief Invoked when we must temporarily exit the objective-c container
2286 /// scope for parsing/looking-up C constructs.
2287 ///
2288 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2289 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2290 void ActOnObjCReenterContainerContext(DeclContext *DC);
2291
2292 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2293 /// error parsing the definition of a tag.
2294 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2295
2296 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2297 EnumConstantDecl *LastEnumConst,
2298 SourceLocation IdLoc,
2299 IdentifierInfo *Id,
2300 Expr *val);
2301 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2302 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2303 QualType EnumUnderlyingTy, bool IsFixed,
2304 const EnumDecl *Prev);
2305
2306 /// Determine whether the body of an anonymous enumeration should be skipped.
2307 /// \param II The name of the first enumerator.
2308 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2309 SourceLocation IILoc);
2310
2311 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2312 SourceLocation IdLoc, IdentifierInfo *Id,
2313 AttributeList *Attrs, SourceLocation EqualLoc,
2314 Expr *Val);
2315 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2316 Decl *EnumDecl,
2317 ArrayRef<Decl *> Elements,
2318 Scope *S, AttributeList *Attr);
2319
2320 DeclContext *getContainingDC(DeclContext *DC);
2321
2322 /// Set the current declaration context until it gets popped.
2323 void PushDeclContext(Scope *S, DeclContext *DC);
2324 void PopDeclContext();
2325
2326 /// EnterDeclaratorContext - Used when we must lookup names in the context
2327 /// of a declarator's nested name specifier.
2328 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2329 void ExitDeclaratorContext(Scope *S);
2330
2331 /// Push the parameters of D, which must be a function, into scope.
2332 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2333 void ActOnExitFunctionContext();
2334
2335 DeclContext *getFunctionLevelDeclContext();
2336
2337 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2338 /// to the function decl for the function being parsed. If we're currently
2339 /// in a 'block', this returns the containing context.
2340 FunctionDecl *getCurFunctionDecl();
2341
2342 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2343 /// the method decl for the method being parsed. If we're currently
2344 /// in a 'block', this returns the containing context.
2345 ObjCMethodDecl *getCurMethodDecl();
2346
2347 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2348 /// or C function we're in, otherwise return null. If we're currently
2349 /// in a 'block', this returns the containing context.
2350 NamedDecl *getCurFunctionOrMethodDecl();
2351
2352 /// Add this decl to the scope shadowed decl chains.
2353 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2354
2355 /// \brief Make the given externally-produced declaration visible at the
2356 /// top level scope.
2357 ///
2358 /// \param D The externally-produced declaration to push.
2359 ///
2360 /// \param Name The name of the externally-produced declaration.
2361 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2362
2363 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2364 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2365 /// true if 'D' belongs to the given declaration context.
2366 ///
2367 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2368 /// enclosing namespace set of the context, rather than contained
2369 /// directly within it.
2370 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2371 bool AllowInlineNamespace = false);
2372
2373 /// Finds the scope corresponding to the given decl context, if it
2374 /// happens to be an enclosing scope. Otherwise return NULL.
2375 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2376
2377 /// Subroutines of ActOnDeclarator().
2378 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2379 TypeSourceInfo *TInfo);
2380 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2381
2382 /// \brief Describes the kind of merge to perform for availability
2383 /// attributes (including "deprecated", "unavailable", and "availability").
2384 enum AvailabilityMergeKind {
2385 /// \brief Don't merge availability attributes at all.
2386 AMK_None,
2387 /// \brief Merge availability attributes for a redeclaration, which requires
2388 /// an exact match.
2389 AMK_Redeclaration,
2390 /// \brief Merge availability attributes for an override, which requires
2391 /// an exact match or a weakening of constraints.
2392 AMK_Override,
2393 /// \brief Merge availability attributes for an implementation of
2394 /// a protocol requirement.
2395 AMK_ProtocolImplementation,
2396 };
2397
2398 /// Attribute merging methods. Return true if a new attribute was added.
2399 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2400 IdentifierInfo *Platform,
2401 bool Implicit,
2402 VersionTuple Introduced,
2403 VersionTuple Deprecated,
2404 VersionTuple Obsoleted,
2405 bool IsUnavailable,
2406 StringRef Message,
2407 bool IsStrict, StringRef Replacement,
2408 AvailabilityMergeKind AMK,
2409 unsigned AttrSpellingListIndex);
2410 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2411 TypeVisibilityAttr::VisibilityType Vis,
2412 unsigned AttrSpellingListIndex);
2413 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2414 VisibilityAttr::VisibilityType Vis,
2415 unsigned AttrSpellingListIndex);
2416 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2417 unsigned AttrSpellingListIndex, StringRef Uuid);
2418 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2419 unsigned AttrSpellingListIndex);
2420 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2421 unsigned AttrSpellingListIndex);
2422 MSInheritanceAttr *
2423 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2424 unsigned AttrSpellingListIndex,
2425 MSInheritanceAttr::Spelling SemanticSpelling);
2426 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2427 IdentifierInfo *Format, int FormatIdx,
2428 int FirstArg, unsigned AttrSpellingListIndex);
2429 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2430 unsigned AttrSpellingListIndex);
2431 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2432 IdentifierInfo *Ident,
2433 unsigned AttrSpellingListIndex);
2434 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2435 unsigned AttrSpellingListIndex);
2436 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2437 unsigned AttrSpellingListIndex);
2438 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2439 IdentifierInfo *Ident,
2440 unsigned AttrSpellingListIndex);
2441 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2442 unsigned AttrSpellingListIndex);
2443
2444 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2445 AvailabilityMergeKind AMK = AMK_Redeclaration);
2446 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2447 LookupResult &OldDecls);
2448 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2449 bool MergeTypeWithOld);
2450 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2451 Scope *S, bool MergeTypeWithOld);
2452 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2453 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2454 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2455 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2456 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2457 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
2458 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2459
2460 // AssignmentAction - This is used by all the assignment diagnostic functions
2461 // to represent what is actually causing the operation
2462 enum AssignmentAction {
2463 AA_Assigning,
2464 AA_Passing,
2465 AA_Returning,
2466 AA_Converting,
2467 AA_Initializing,
2468 AA_Sending,
2469 AA_Casting,
2470 AA_Passing_CFAudited
2471 };
2472
2473 /// C++ Overloading.
2474 enum OverloadKind {
2475 /// This is a legitimate overload: the existing declarations are
2476 /// functions or function templates with different signatures.
2477 Ovl_Overload,
2478
2479 /// This is not an overload because the signature exactly matches
2480 /// an existing declaration.
2481 Ovl_Match,
2482
2483 /// This is not an overload because the lookup results contain a
2484 /// non-function.
2485 Ovl_NonFunction
2486 };
2487 OverloadKind CheckOverload(Scope *S,
2488 FunctionDecl *New,
2489 const LookupResult &OldDecls,
2490 NamedDecl *&OldDecl,
2491 bool IsForUsingDecl);
2492 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2493 bool ConsiderCudaAttrs = true);
2494
2495 /// \brief Checks availability of the function depending on the current
2496 /// function context.Inside an unavailable function,unavailability is ignored.
2497 ///
2498 /// \returns true if \p FD is unavailable and current context is inside
2499 /// an available function, false otherwise.
2500 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2501
2502 ImplicitConversionSequence
2503 TryImplicitConversion(Expr *From, QualType ToType,
2504 bool SuppressUserConversions,
2505 bool AllowExplicit,
2506 bool InOverloadResolution,
2507 bool CStyle,
2508 bool AllowObjCWritebackConversion);
2509
2510 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2511 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2512 bool IsComplexPromotion(QualType FromType, QualType ToType);
2513 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2514 bool InOverloadResolution,
2515 QualType& ConvertedType, bool &IncompatibleObjC);
2516 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2517 QualType& ConvertedType, bool &IncompatibleObjC);
2518 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2519 QualType &ConvertedType);
2520 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2521 QualType& ConvertedType);
2522 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2523 const FunctionProtoType *NewType,
2524 unsigned *ArgPos = nullptr);
2525 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2526 QualType FromType, QualType ToType);
2527
2528 void maybeExtendBlockObject(ExprResult &E);
2529 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2530 bool CheckPointerConversion(Expr *From, QualType ToType,
2531 CastKind &Kind,
2532 CXXCastPath& BasePath,
2533 bool IgnoreBaseAccess,
2534 bool Diagnose = true);
2535 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2536 bool InOverloadResolution,
2537 QualType &ConvertedType);
2538 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2539 CastKind &Kind,
2540 CXXCastPath &BasePath,
2541 bool IgnoreBaseAccess);
2542 bool IsQualificationConversion(QualType FromType, QualType ToType,
2543 bool CStyle, bool &ObjCLifetimeConversion);
2544 bool IsFunctionConversion(QualType FromType, QualType ToType,
2545 QualType &ResultTy);
2546 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2547 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2548
2549 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2550 const VarDecl *NRVOCandidate,
2551 QualType ResultType,
2552 Expr *Value,
2553 bool AllowNRVO = true);
2554
2555 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2556 ExprResult Init);
2557 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2558 SourceLocation EqualLoc,
2559 ExprResult Init,
2560 bool TopLevelOfInitList = false,
2561 bool AllowExplicit = false);
2562 ExprResult PerformObjectArgumentInitialization(Expr *From,
2563 NestedNameSpecifier *Qualifier,
2564 NamedDecl *FoundDecl,
2565 CXXMethodDecl *Method);
2566
2567 ExprResult PerformContextuallyConvertToBool(Expr *From);
2568 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2569
2570 /// Contexts in which a converted constant expression is required.
2571 enum CCEKind {
2572 CCEK_CaseValue, ///< Expression in a case label.
2573 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2574 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2575 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2576 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2577 };
2578 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2579 llvm::APSInt &Value, CCEKind CCE);
2580 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2581 APValue &Value, CCEKind CCE);
2582
2583 /// \brief Abstract base class used to perform a contextual implicit
2584 /// conversion from an expression to any type passing a filter.
2585 class ContextualImplicitConverter {
2586 public:
2587 bool Suppress;
2588 bool SuppressConversion;
2589
2590 ContextualImplicitConverter(bool Suppress = false,
2591 bool SuppressConversion = false)
2592 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2593
2594 /// \brief Determine whether the specified type is a valid destination type
2595 /// for this conversion.
2596 virtual bool match(QualType T) = 0;
2597
2598 /// \brief Emits a diagnostic complaining that the expression does not have
2599 /// integral or enumeration type.
2600 virtual SemaDiagnosticBuilder
2601 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2602
2603 /// \brief Emits a diagnostic when the expression has incomplete class type.
2604 virtual SemaDiagnosticBuilder
2605 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2606
2607 /// \brief Emits a diagnostic when the only matching conversion function
2608 /// is explicit.
2609 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2610 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2611
2612 /// \brief Emits a note for the explicit conversion function.
2613 virtual SemaDiagnosticBuilder
2614 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2615
2616 /// \brief Emits a diagnostic when there are multiple possible conversion
2617 /// functions.
2618 virtual SemaDiagnosticBuilder
2619 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2620
2621 /// \brief Emits a note for one of the candidate conversions.
2622 virtual SemaDiagnosticBuilder
2623 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2624
2625 /// \brief Emits a diagnostic when we picked a conversion function
2626 /// (for cases when we are not allowed to pick a conversion function).
2627 virtual SemaDiagnosticBuilder diagnoseConversion(
2628 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2629
2630 virtual ~ContextualImplicitConverter() {}
2631 };
2632
2633 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2634 bool AllowScopedEnumerations;
2635
2636 public:
2637 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2638 bool Suppress, bool SuppressConversion)
2639 : ContextualImplicitConverter(Suppress, SuppressConversion),
2640 AllowScopedEnumerations(AllowScopedEnumerations) {}
2641
2642 /// Match an integral or (possibly scoped) enumeration type.
2643 bool match(QualType T) override;
2644
2645 SemaDiagnosticBuilder
2646 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2647 return diagnoseNotInt(S, Loc, T);
2648 }
2649
2650 /// \brief Emits a diagnostic complaining that the expression does not have
2651 /// integral or enumeration type.
2652 virtual SemaDiagnosticBuilder
2653 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2654 };
2655
2656 /// Perform a contextual implicit conversion.
2657 ExprResult PerformContextualImplicitConversion(
2658 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2659
2660
2661 enum ObjCSubscriptKind {
2662 OS_Array,
2663 OS_Dictionary,
2664 OS_Error
2665 };
2666 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2667
2668 // Note that LK_String is intentionally after the other literals, as
2669 // this is used for diagnostics logic.
2670 enum ObjCLiteralKind {
2671 LK_Array,
2672 LK_Dictionary,
2673 LK_Numeric,
2674 LK_Boxed,
2675 LK_String,
2676 LK_Block,
2677 LK_None
2678 };
2679 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2680
2681 ExprResult PerformObjectMemberConversion(Expr *From,
2682 NestedNameSpecifier *Qualifier,
2683 NamedDecl *FoundDecl,
2684 NamedDecl *Member);
2685
2686 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2687 // TODO: make this is a typesafe union.
2688 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2689 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2690
2691 void AddOverloadCandidate(FunctionDecl *Function,
2692 DeclAccessPair FoundDecl,
2693 ArrayRef<Expr *> Args,
2694 OverloadCandidateSet &CandidateSet,
2695 bool SuppressUserConversions = false,
2696 bool PartialOverloading = false,
2697 bool AllowExplicit = false,
2698 ConversionSequenceList EarlyConversions = None);
2699 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2700 ArrayRef<Expr *> Args,
2701 OverloadCandidateSet &CandidateSet,
2702 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2703 bool SuppressUserConversions = false,
2704 bool PartialOverloading = false,
2705 bool FirstArgumentIsBase = false);
2706 void AddMethodCandidate(DeclAccessPair FoundDecl,
2707 QualType ObjectType,
2708 Expr::Classification ObjectClassification,
2709 ArrayRef<Expr *> Args,
2710 OverloadCandidateSet& CandidateSet,
2711 bool SuppressUserConversion = false);
2712 void AddMethodCandidate(CXXMethodDecl *Method,
2713 DeclAccessPair FoundDecl,
2714 CXXRecordDecl *ActingContext, QualType ObjectType,
2715 Expr::Classification ObjectClassification,
2716 ArrayRef<Expr *> Args,
2717 OverloadCandidateSet& CandidateSet,
2718 bool SuppressUserConversions = false,
2719 bool PartialOverloading = false,
2720 ConversionSequenceList EarlyConversions = None);
2721 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2722 DeclAccessPair FoundDecl,
2723 CXXRecordDecl *ActingContext,
2724 TemplateArgumentListInfo *ExplicitTemplateArgs,
2725 QualType ObjectType,
2726 Expr::Classification ObjectClassification,
2727 ArrayRef<Expr *> Args,
2728 OverloadCandidateSet& CandidateSet,
2729 bool SuppressUserConversions = false,
2730 bool PartialOverloading = false);
2731 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2732 DeclAccessPair FoundDecl,
2733 TemplateArgumentListInfo *ExplicitTemplateArgs,
2734 ArrayRef<Expr *> Args,
2735 OverloadCandidateSet& CandidateSet,
2736 bool SuppressUserConversions = false,
2737 bool PartialOverloading = false);
2738 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2739 ArrayRef<QualType> ParamTypes,
2740 ArrayRef<Expr *> Args,
2741 OverloadCandidateSet &CandidateSet,
2742 ConversionSequenceList &Conversions,
2743 bool SuppressUserConversions,
2744 CXXRecordDecl *ActingContext = nullptr,
2745 QualType ObjectType = QualType(),
2746 Expr::Classification
2747 ObjectClassification = {});
2748 void AddConversionCandidate(CXXConversionDecl *Conversion,
2749 DeclAccessPair FoundDecl,
2750 CXXRecordDecl *ActingContext,
2751 Expr *From, QualType ToType,
2752 OverloadCandidateSet& CandidateSet,
2753 bool AllowObjCConversionOnExplicit,
2754 bool AllowResultConversion = true);
2755 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2756 DeclAccessPair FoundDecl,
2757 CXXRecordDecl *ActingContext,
2758 Expr *From, QualType ToType,
2759 OverloadCandidateSet &CandidateSet,
2760 bool AllowObjCConversionOnExplicit,
2761 bool AllowResultConversion = true);
2762 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2763 DeclAccessPair FoundDecl,
2764 CXXRecordDecl *ActingContext,
2765 const FunctionProtoType *Proto,
2766 Expr *Object, ArrayRef<Expr *> Args,
2767 OverloadCandidateSet& CandidateSet);
2768 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2769 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2770 OverloadCandidateSet& CandidateSet,
2771 SourceRange OpRange = SourceRange());
2772 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
2773 OverloadCandidateSet& CandidateSet,
2774 bool IsAssignmentOperator = false,
2775 unsigned NumContextualBoolArguments = 0);
2776 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2777 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2778 OverloadCandidateSet& CandidateSet);
2779 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2780 SourceLocation Loc,
2781 ArrayRef<Expr *> Args,
2782 TemplateArgumentListInfo *ExplicitTemplateArgs,
2783 OverloadCandidateSet& CandidateSet,
2784 bool PartialOverloading = false);
2785
2786 // Emit as a 'note' the specific overload candidate
2787 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2788 QualType DestType = QualType(),
2789 bool TakingAddress = false);
2790
2791 // Emit as a series of 'note's all template and non-templates identified by
2792 // the expression Expr
2793 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2794 bool TakingAddress = false);
2795
2796 /// Check the enable_if expressions on the given function. Returns the first
2797 /// failing attribute, or NULL if they were all successful.
2798 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2799 bool MissingImplicitThis = false);
2800
2801 /// Find the failed Boolean condition within a given Boolean
2802 /// constant expression, and describe it with a string.
2803 ///
2804 /// \param AllowTopLevelCond Whether to allow the result to be the
2805 /// complete top-level condition.
2806 std::pair<Expr *, std::string>
2807 findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond);
2808
2809 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2810 /// non-ArgDependent DiagnoseIfAttrs.
2811 ///
2812 /// Argument-dependent diagnose_if attributes should be checked each time a
2813 /// function is used as a direct callee of a function call.
2814 ///
2815 /// Returns true if any errors were emitted.
2816 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2817 const Expr *ThisArg,
2818 ArrayRef<const Expr *> Args,
2819 SourceLocation Loc);
2820
2821 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2822 /// ArgDependent DiagnoseIfAttrs.
2823 ///
2824 /// Argument-independent diagnose_if attributes should be checked on every use
2825 /// of a function.
2826 ///
2827 /// Returns true if any errors were emitted.
2828 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
2829 SourceLocation Loc);
2830
2831 /// Returns whether the given function's address can be taken or not,
2832 /// optionally emitting a diagnostic if the address can't be taken.
2833 ///
2834 /// Returns false if taking the address of the function is illegal.
2835 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2836 bool Complain = false,
2837 SourceLocation Loc = SourceLocation());
2838
2839 // [PossiblyAFunctionType] --> [Return]
2840 // NonFunctionType --> NonFunctionType
2841 // R (A) --> R(A)
2842 // R (*)(A) --> R (A)
2843 // R (&)(A) --> R (A)
2844 // R (S::*)(A) --> R (A)
2845 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2846
2847 FunctionDecl *
2848 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2849 QualType TargetType,
2850 bool Complain,
2851 DeclAccessPair &Found,
2852 bool *pHadMultipleCandidates = nullptr);
2853
2854 FunctionDecl *
2855 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2856 DeclAccessPair &FoundResult);
2857
2858 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2859 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2860
2861 FunctionDecl *
2862 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2863 bool Complain = false,
2864 DeclAccessPair *Found = nullptr);
2865
2866 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2867 ExprResult &SrcExpr,
2868 bool DoFunctionPointerConverion = false,
2869 bool Complain = false,
2870 SourceRange OpRangeForComplaining = SourceRange(),
2871 QualType DestTypeForComplaining = QualType(),
2872 unsigned DiagIDForComplaining = 0);
2873
2874
2875 Expr *FixOverloadedFunctionReference(Expr *E,
2876 DeclAccessPair FoundDecl,
2877 FunctionDecl *Fn);
2878 ExprResult FixOverloadedFunctionReference(ExprResult,
2879 DeclAccessPair FoundDecl,
2880 FunctionDecl *Fn);
2881
2882 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2883 ArrayRef<Expr *> Args,
2884 OverloadCandidateSet &CandidateSet,
2885 bool PartialOverloading = false);
2886
2887 // An enum used to represent the different possible results of building a
2888 // range-based for loop.
2889 enum ForRangeStatus {
2890 FRS_Success,
2891 FRS_NoViableFunction,
2892 FRS_DiagnosticIssued
2893 };
2894
2895 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2896 SourceLocation RangeLoc,
2897 const DeclarationNameInfo &NameInfo,
2898 LookupResult &MemberLookup,
2899 OverloadCandidateSet *CandidateSet,
2900 Expr *Range, ExprResult *CallExpr);
2901
2902 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2903 UnresolvedLookupExpr *ULE,
2904 SourceLocation LParenLoc,
2905 MultiExprArg Args,
2906 SourceLocation RParenLoc,
2907 Expr *ExecConfig,
2908 bool AllowTypoCorrection=true,
2909 bool CalleesAddressIsTaken=false);
2910
2911 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2912 MultiExprArg Args, SourceLocation RParenLoc,
2913 OverloadCandidateSet *CandidateSet,
2914 ExprResult *Result);
2915
2916 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2917 UnaryOperatorKind Opc,
2918 const UnresolvedSetImpl &Fns,
2919 Expr *input, bool RequiresADL = true);
2920
2921 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2922 BinaryOperatorKind Opc,
2923 const UnresolvedSetImpl &Fns,
2924 Expr *LHS, Expr *RHS,
2925 bool RequiresADL = true);
2926
2927 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2928 SourceLocation RLoc,
2929 Expr *Base,Expr *Idx);
2930
2931 ExprResult
2932 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2933 SourceLocation LParenLoc,
2934 MultiExprArg Args,
2935 SourceLocation RParenLoc);
2936 ExprResult
2937 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2938 MultiExprArg Args,
2939 SourceLocation RParenLoc);
2940
2941 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2942 SourceLocation OpLoc,
2943 bool *NoArrowOperatorFound = nullptr);
2944
2945 /// CheckCallReturnType - Checks that a call expression's return type is
2946 /// complete. Returns true on failure. The location passed in is the location
2947 /// that best represents the call.
2948 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2949 CallExpr *CE, FunctionDecl *FD);
2950
2951 /// Helpers for dealing with blocks and functions.
2952 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2953 bool CheckParameterNames);
2954 void CheckCXXDefaultArguments(FunctionDecl *FD);
2955 void CheckExtraCXXDefaultArguments(Declarator &D);
2956 Scope *getNonFieldDeclScope(Scope *S);
2957
2958 /// \name Name lookup
2959 ///
2960 /// These routines provide name lookup that is used during semantic
2961 /// analysis to resolve the various kinds of names (identifiers,
2962 /// overloaded operator names, constructor names, etc.) into zero or
2963 /// more declarations within a particular scope. The major entry
2964 /// points are LookupName, which performs unqualified name lookup,
2965 /// and LookupQualifiedName, which performs qualified name lookup.
2966 ///
2967 /// All name lookup is performed based on some specific criteria,
2968 /// which specify what names will be visible to name lookup and how
2969 /// far name lookup should work. These criteria are important both
2970 /// for capturing language semantics (certain lookups will ignore
2971 /// certain names, for example) and for performance, since name
2972 /// lookup is often a bottleneck in the compilation of C++. Name
2973 /// lookup criteria is specified via the LookupCriteria enumeration.
2974 ///
2975 /// The results of name lookup can vary based on the kind of name
2976 /// lookup performed, the current language, and the translation
2977 /// unit. In C, for example, name lookup will either return nothing
2978 /// (no entity found) or a single declaration. In C++, name lookup
2979 /// can additionally refer to a set of overloaded functions or
2980 /// result in an ambiguity. All of the possible results of name
2981 /// lookup are captured by the LookupResult class, which provides
2982 /// the ability to distinguish among them.
2983 //@{
2984
2985 /// @brief Describes the kind of name lookup to perform.
2986 enum LookupNameKind {
2987 /// Ordinary name lookup, which finds ordinary names (functions,
2988 /// variables, typedefs, etc.) in C and most kinds of names
2989 /// (functions, variables, members, types, etc.) in C++.
2990 LookupOrdinaryName = 0,
2991 /// Tag name lookup, which finds the names of enums, classes,
2992 /// structs, and unions.
2993 LookupTagName,
2994 /// Label name lookup.
2995 LookupLabel,
2996 /// Member name lookup, which finds the names of
2997 /// class/struct/union members.
2998 LookupMemberName,
2999 /// Look up of an operator name (e.g., operator+) for use with
3000 /// operator overloading. This lookup is similar to ordinary name
3001 /// lookup, but will ignore any declarations that are class members.
3002 LookupOperatorName,
3003 /// Look up of a name that precedes the '::' scope resolution
3004 /// operator in C++. This lookup completely ignores operator, object,
3005 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
3006 LookupNestedNameSpecifierName,
3007 /// Look up a namespace name within a C++ using directive or
3008 /// namespace alias definition, ignoring non-namespace names (C++
3009 /// [basic.lookup.udir]p1).
3010 LookupNamespaceName,
3011 /// Look up all declarations in a scope with the given name,
3012 /// including resolved using declarations. This is appropriate
3013 /// for checking redeclarations for a using declaration.
3014 LookupUsingDeclName,
3015 /// Look up an ordinary name that is going to be redeclared as a
3016 /// name with linkage. This lookup ignores any declarations that
3017 /// are outside of the current scope unless they have linkage. See
3018 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
3019 LookupRedeclarationWithLinkage,
3020 /// Look up a friend of a local class. This lookup does not look
3021 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
3022 LookupLocalFriendName,
3023 /// Look up the name of an Objective-C protocol.
3024 LookupObjCProtocolName,
3025 /// Look up implicit 'self' parameter of an objective-c method.
3026 LookupObjCImplicitSelfParam,
3027 /// \brief Look up the name of an OpenMP user-defined reduction operation.
3028 LookupOMPReductionName,
3029 /// \brief Look up any declaration with any name.
3030 LookupAnyName
3031 };
3032
3033 /// \brief Specifies whether (or how) name lookup is being performed for a
3034 /// redeclaration (vs. a reference).
3035 enum RedeclarationKind {
3036 /// \brief The lookup is a reference to this name that is not for the
3037 /// purpose of redeclaring the name.
3038 NotForRedeclaration = 0,
3039 /// \brief The lookup results will be used for redeclaration of a name,
3040 /// if an entity by that name already exists and is visible.
3041 ForVisibleRedeclaration,
3042 /// \brief The lookup results will be used for redeclaration of a name
3043 /// with external linkage; non-visible lookup results with external linkage
3044 /// may also be found.
3045 ForExternalRedeclaration
3046 };
3047
3048 RedeclarationKind forRedeclarationInCurContext() {
3049 // A declaration with an owning module for linkage can never link against
3050 // anything that is not visible. We don't need to check linkage here; if
3051 // the context has internal linkage, redeclaration lookup won't find things
3052 // from other TUs, and we can't safely compute linkage yet in general.
3053 if (cast<Decl>(CurContext)
3054 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
3055 return ForVisibleRedeclaration;
3056 return ForExternalRedeclaration;
3057 }
3058
3059 /// \brief The possible outcomes of name lookup for a literal operator.
3060 enum LiteralOperatorLookupResult {
3061 /// \brief The lookup resulted in an error.
3062 LOLR_Error,
3063 /// \brief The lookup found no match but no diagnostic was issued.
3064 LOLR_ErrorNoDiagnostic,
3065 /// \brief The lookup found a single 'cooked' literal operator, which
3066 /// expects a normal literal to be built and passed to it.
3067 LOLR_Cooked,
3068 /// \brief The lookup found a single 'raw' literal operator, which expects
3069 /// a string literal containing the spelling of the literal token.
3070 LOLR_Raw,
3071 /// \brief The lookup found an overload set of literal operator templates,
3072 /// which expect the characters of the spelling of the literal token to be
3073 /// passed as a non-type template argument pack.
3074 LOLR_Template,
3075 /// \brief The lookup found an overload set of literal operator templates,
3076 /// which expect the character type and characters of the spelling of the
3077 /// string literal token to be passed as template arguments.
3078 LOLR_StringTemplate
3079 };
3080
3081 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
3082 CXXSpecialMember SM,
3083 bool ConstArg,
3084 bool VolatileArg,
3085 bool RValueThis,
3086 bool ConstThis,
3087 bool VolatileThis);
3088
3089 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
3090 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
3091 TypoRecoveryCallback;
3092
3093private:
3094 bool CppLookupName(LookupResult &R, Scope *S);
3095
3096 struct TypoExprState {
3097 std::unique_ptr<TypoCorrectionConsumer> Consumer;
3098 TypoDiagnosticGenerator DiagHandler;
3099 TypoRecoveryCallback RecoveryHandler;
3100 TypoExprState();
3101 TypoExprState(TypoExprState &&other) noexcept;
3102 TypoExprState &operator=(TypoExprState &&other) noexcept;
3103 };
3104
3105 /// \brief The set of unhandled TypoExprs and their associated state.
3106 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
3107
3108 /// \brief Creates a new TypoExpr AST node.
3109 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
3110 TypoDiagnosticGenerator TDG,
3111 TypoRecoveryCallback TRC);
3112
3113 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
3114 //
3115 // The boolean value will be true to indicate that the namespace was loaded
3116 // from an AST/PCH file, or false otherwise.
3117 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
3118
3119 /// \brief Whether we have already loaded known namespaces from an extenal
3120 /// source.
3121 bool LoadedExternalKnownNamespaces;
3122
3123 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
3124 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
3125 /// should be skipped entirely.
3126 std::unique_ptr<TypoCorrectionConsumer>
3127 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
3128 Sema::LookupNameKind LookupKind, Scope *S,
3129 CXXScopeSpec *SS,
3130 std::unique_ptr<CorrectionCandidateCallback> CCC,
3131 DeclContext *MemberContext, bool EnteringContext,
3132 const ObjCObjectPointerType *OPT,
3133 bool ErrorRecovery);
3134
3135public:
3136 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
3137
3138 /// \brief Clears the state of the given TypoExpr.
3139 void clearDelayedTypo(TypoExpr *TE);
3140
3141 /// \brief Look up a name, looking for a single declaration. Return
3142 /// null if the results were absent, ambiguous, or overloaded.
3143 ///
3144 /// It is preferable to use the elaborated form and explicitly handle
3145 /// ambiguity and overloaded.
3146 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
3147 SourceLocation Loc,
3148 LookupNameKind NameKind,
3149 RedeclarationKind Redecl
3150 = NotForRedeclaration);
3151 bool LookupName(LookupResult &R, Scope *S,
3152 bool AllowBuiltinCreation = false);
3153 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3154 bool InUnqualifiedLookup = false);
3155 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
3156 CXXScopeSpec &SS);
3157 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
3158 bool AllowBuiltinCreation = false,
3159 bool EnteringContext = false);
3160 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
3161 RedeclarationKind Redecl
3162 = NotForRedeclaration);
3163 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
3164
3165 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3166 QualType T1, QualType T2,
3167 UnresolvedSetImpl &Functions);
3168
3169 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3170 SourceLocation GnuLabelLoc = SourceLocation());
3171
3172 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3173 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3174 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3175 unsigned Quals);
3176 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3177 bool RValueThis, unsigned ThisQuals);
3178 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3179 unsigned Quals);
3180 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3181 bool RValueThis, unsigned ThisQuals);
3182 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3183
3184 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3185 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3186 ArrayRef<QualType> ArgTys,
3187 bool AllowRaw,
3188 bool AllowTemplate,
3189 bool AllowStringTemplate,
3190 bool DiagnoseMissing);
3191 bool isKnownName(StringRef name);
3192
3193 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3194 ArrayRef<Expr *> Args, ADLResult &Functions);
3195
3196 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3197 VisibleDeclConsumer &Consumer,
3198 bool IncludeGlobalScope = true,
3199 bool LoadExternal = true);
3200 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3201 VisibleDeclConsumer &Consumer,
3202 bool IncludeGlobalScope = true,
3203 bool IncludeDependentBases = false,
3204 bool LoadExternal = true);
3205
3206 enum CorrectTypoKind {
3207 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3208 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3209 };
3210
3211 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3212 Sema::LookupNameKind LookupKind,
3213 Scope *S, CXXScopeSpec *SS,
3214 std::unique_ptr<CorrectionCandidateCallback> CCC,
3215 CorrectTypoKind Mode,
3216 DeclContext *MemberContext = nullptr,
3217 bool EnteringContext = false,
3218 const ObjCObjectPointerType *OPT = nullptr,
3219 bool RecordFailure = true);
3220
3221 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3222 Sema::LookupNameKind LookupKind, Scope *S,
3223 CXXScopeSpec *SS,
3224 std::unique_ptr<CorrectionCandidateCallback> CCC,
3225 TypoDiagnosticGenerator TDG,
3226 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3227 DeclContext *MemberContext = nullptr,
3228 bool EnteringContext = false,
3229 const ObjCObjectPointerType *OPT = nullptr);
3230
3231 /// \brief Process any TypoExprs in the given Expr and its children,
3232 /// generating diagnostics as appropriate and returning a new Expr if there
3233 /// were typos that were all successfully corrected and ExprError if one or
3234 /// more typos could not be corrected.
3235 ///
3236 /// \param E The Expr to check for TypoExprs.
3237 ///
3238 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3239 /// initializer.
3240 ///
3241 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3242 /// it is an acceptable/usable result from a single combination of typo
3243 /// corrections. As long as the filter returns ExprError, different
3244 /// combinations of corrections will be tried until all are exhausted.
3245 ExprResult
3246 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3247 llvm::function_ref<ExprResult(Expr *)> Filter =
3248 [](Expr *E) -> ExprResult { return E; });
3249
3250 ExprResult
3251 CorrectDelayedTyposInExpr(Expr *E,
3252 llvm::function_ref<ExprResult(Expr *)> Filter) {
3253 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3254 }
3255
3256 ExprResult
3257 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3258 llvm::function_ref<ExprResult(Expr *)> Filter =
3259 [](Expr *E) -> ExprResult { return E; }) {
3260 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3261 }
3262
3263 ExprResult
3264 CorrectDelayedTyposInExpr(ExprResult ER,
3265 llvm::function_ref<ExprResult(Expr *)> Filter) {
3266 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3267 }
3268
3269 void diagnoseTypo(const TypoCorrection &Correction,
3270 const PartialDiagnostic &TypoDiag,
3271 bool ErrorRecovery = true);
3272
3273 void diagnoseTypo(const TypoCorrection &Correction,
3274 const PartialDiagnostic &TypoDiag,
3275 const PartialDiagnostic &PrevNote,
3276 bool ErrorRecovery = true);
3277
3278 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
3279
3280 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3281 ArrayRef<Expr *> Args,
3282 AssociatedNamespaceSet &AssociatedNamespaces,
3283 AssociatedClassSet &AssociatedClasses);
3284
3285 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3286 bool ConsiderLinkage, bool AllowInlineNamespace);
3287
3288 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
3289
3290 void DiagnoseAmbiguousLookup(LookupResult &Result);
3291 //@}
3292
3293 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3294 SourceLocation IdLoc,
3295 bool TypoCorrection = false);
3296 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3297 Scope *S, bool ForRedeclaration,
3298 SourceLocation Loc);
3299 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3300 Scope *S);
3301 void AddKnownFunctionAttributes(FunctionDecl *FD);
3302
3303 // More parsing and symbol table subroutines.
3304
3305 void ProcessPragmaWeak(Scope *S, Decl *D);
3306 // Decl attributes - this routine is the top level dispatcher.
3307 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3308 // Helper for delayed processing of attributes.
3309 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3310 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3311 bool IncludeCXX11Attributes = true);
3312 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3313 const AttributeList *AttrList);
3314
3315 void checkUnusedDeclAttributes(Declarator &D);
3316
3317 /// Determine if type T is a valid subject for a nonnull and similar
3318 /// attributes. By default, we look through references (the behavior used by
3319 /// nonnull), but if the second parameter is true, then we treat a reference
3320 /// type as valid.
3321 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3322
3323 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3324 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3325 const FunctionDecl *FD = nullptr);
3326 bool CheckAttrTarget(const AttributeList &CurrAttr);
3327 bool CheckAttrNoArgs(const AttributeList &CurrAttr);
3328 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3329 unsigned ArgNum, StringRef &Str,
3330 SourceLocation *ArgLocation = nullptr);
3331 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3332 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3333 bool checkMSInheritanceAttrOnDefinition(
3334 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3335 MSInheritanceAttr::Spelling SemanticSpelling);
3336
3337 void CheckAlignasUnderalignment(Decl *D);
3338
3339 /// Adjust the calling convention of a method to be the ABI default if it
3340 /// wasn't specified explicitly. This handles method types formed from
3341 /// function type typedefs and typename template arguments.
3342 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3343 SourceLocation Loc);
3344
3345 // Check if there is an explicit attribute, but only look through parens.
3346 // The intent is to look for an attribute on the current declarator, but not
3347 // one that came from a typedef.
3348 bool hasExplicitCallingConv(QualType &T);
3349
3350 /// Get the outermost AttributedType node that sets a calling convention.
3351 /// Valid types should not have multiple attributes with different CCs.
3352 const AttributedType *getCallingConvAttributedType(QualType T) const;
3353
3354 /// Check whether a nullability type specifier can be added to the given
3355 /// type.
3356 ///
3357 /// \param type The type to which the nullability specifier will be
3358 /// added. On success, this type will be updated appropriately.
3359 ///
3360 /// \param nullability The nullability specifier to add.
3361 ///
3362 /// \param nullabilityLoc The location of the nullability specifier.
3363 ///
3364 /// \param isContextSensitive Whether this nullability specifier was
3365 /// written as a context-sensitive keyword (in an Objective-C
3366 /// method) or an Objective-C property attribute, rather than as an
3367 /// underscored type specifier.
3368 ///
3369 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3370 /// array type (e.g., because it will decay to a pointer).
3371 ///
3372 /// \returns true if nullability cannot be applied, false otherwise.
3373 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3374 SourceLocation nullabilityLoc,
3375 bool isContextSensitive,
3376 bool allowArrayTypes);
3377
3378 /// \brief Stmt attributes - this routine is the top level dispatcher.
3379 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3380 SourceRange Range);
3381
3382 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3383 ObjCMethodDecl *MethodDecl,
3384 bool IsProtocolMethodDecl);
3385
3386 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3387 ObjCMethodDecl *Overridden,
3388 bool IsProtocolMethodDecl);
3389
3390 /// WarnExactTypedMethods - This routine issues a warning if method
3391 /// implementation declaration matches exactly that of its declaration.
3392 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3393 ObjCMethodDecl *MethodDecl,
3394 bool IsProtocolMethodDecl);
3395
3396 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3397
3398 /// CheckImplementationIvars - This routine checks if the instance variables
3399 /// listed in the implelementation match those listed in the interface.
3400 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3401 ObjCIvarDecl **Fields, unsigned nIvars,
3402 SourceLocation Loc);
3403
3404 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3405 /// remains unimplemented in the class or category \@implementation.
3406 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3407 ObjCContainerDecl* IDecl,
3408 bool IncompleteImpl = false);
3409
3410 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3411 /// which must be implemented by this implementation.
3412 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3413 ObjCContainerDecl *CDecl,
3414 bool SynthesizeProperties);
3415
3416 /// Diagnose any null-resettable synthesized setters.
3417 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3418
3419 /// DefaultSynthesizeProperties - This routine default synthesizes all
3420 /// properties which must be synthesized in the class's \@implementation.
3421 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
3422 ObjCInterfaceDecl *IDecl,
3423 SourceLocation AtEnd);
3424 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
3425
3426 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3427 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3428 /// declared in class 'IFace'.
3429 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3430 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3431
3432 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3433 /// backs the property is not used in the property's accessor.
3434 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3435 const ObjCImplementationDecl *ImplD);
3436
3437 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3438 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3439 /// It also returns ivar's property on success.
3440 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3441 const ObjCPropertyDecl *&PDecl) const;
3442
3443 /// Called by ActOnProperty to handle \@property declarations in
3444 /// class extensions.
3445 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3446 SourceLocation AtLoc,
3447 SourceLocation LParenLoc,
3448 FieldDeclarator &FD,
3449 Selector GetterSel,
3450 SourceLocation GetterNameLoc,
3451 Selector SetterSel,
3452 SourceLocation SetterNameLoc,
3453 const bool isReadWrite,
3454 unsigned &Attributes,
3455 const unsigned AttributesAsWritten,
3456 QualType T,
3457 TypeSourceInfo *TSI,
3458 tok::ObjCKeywordKind MethodImplKind);
3459
3460 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3461 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3462 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3463 ObjCContainerDecl *CDecl,
3464 SourceLocation AtLoc,
3465 SourceLocation LParenLoc,
3466 FieldDeclarator &FD,
3467 Selector GetterSel,
3468 SourceLocation GetterNameLoc,
3469 Selector SetterSel,
3470 SourceLocation SetterNameLoc,
3471 const bool isReadWrite,
3472 const unsigned Attributes,
3473 const unsigned AttributesAsWritten,
3474 QualType T,
3475 TypeSourceInfo *TSI,
3476 tok::ObjCKeywordKind MethodImplKind,
3477 DeclContext *lexicalDC = nullptr);
3478
3479 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3480 /// warning) when atomic property has one but not the other user-declared
3481 /// setter or getter.
3482 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3483 ObjCInterfaceDecl* IDecl);
3484
3485 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3486
3487 void DiagnoseMissingDesignatedInitOverrides(
3488 const ObjCImplementationDecl *ImplD,
3489 const ObjCInterfaceDecl *IFD);
3490
3491 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3492
3493 enum MethodMatchStrategy {
3494 MMS_loose,
3495 MMS_strict
3496 };
3497
3498 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3499 /// true, or false, accordingly.
3500 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3501 const ObjCMethodDecl *PrevMethod,
3502 MethodMatchStrategy strategy = MMS_strict);
3503
3504 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3505 /// or protocol against those declared in their implementations.
3506 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3507 const SelectorSet &ClsMap,
3508 SelectorSet &InsMapSeen,
3509 SelectorSet &ClsMapSeen,
3510 ObjCImplDecl* IMPDecl,
3511 ObjCContainerDecl* IDecl,
3512 bool &IncompleteImpl,
3513 bool ImmediateClass,
3514 bool WarnCategoryMethodImpl=false);
3515
3516 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3517 /// category matches with those implemented in its primary class and
3518 /// warns each time an exact match is found.
3519 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3520
3521 /// \brief Add the given method to the list of globally-known methods.
3522 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3523
3524private:
3525 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3526 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3527 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3528
3529 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3530 /// optionally warns if there are multiple signatures.
3531 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3532 bool receiverIdOrClass,
3533 bool instance);
3534
3535public:
3536 /// \brief - Returns instance or factory methods in global method pool for
3537 /// given selector. It checks the desired kind first, if none is found, and
3538 /// parameter checkTheOther is set, it then checks the other kind. If no such
3539 /// method or only one method is found, function returns false; otherwise, it
3540 /// returns true.
3541 bool
3542 CollectMultipleMethodsInGlobalPool(Selector Sel,
3543 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3544 bool InstanceFirst, bool CheckTheOther,
3545 const ObjCObjectType *TypeBound = nullptr);
3546
3547 bool
3548 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3549 SourceRange R, bool receiverIdOrClass,
3550 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3551
3552 void
3553 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3554 Selector Sel, SourceRange R,
3555 bool receiverIdOrClass);
3556
3557private:
3558 /// \brief - Returns a selector which best matches given argument list or
3559 /// nullptr if none could be found
3560 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3561 bool IsInstance,
3562 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3563
3564
3565 /// \brief Record the typo correction failure and return an empty correction.
3566 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3567 bool RecordFailure = true) {
3568 if (RecordFailure)
3569 TypoCorrectionFailures[Typo].insert(TypoLoc);
3570 return TypoCorrection();
3571 }
3572
3573public:
3574 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3575 /// unit are added to a global pool. This allows us to efficiently associate
3576 /// a selector with a method declaraation for purposes of typechecking
3577 /// messages sent to "id" (where the class of the object is unknown).
3578 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3579 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3580 }
3581
3582 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3583 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3584 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3585 }
3586
3587 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3588 /// pool.
3589 void AddAnyMethodToGlobalPool(Decl *D);
3590
3591 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3592 /// there are multiple signatures.
3593 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3594 bool receiverIdOrClass=false) {
3595 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3596 /*instance*/true);
3597 }
3598
3599 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3600 /// there are multiple signatures.
3601 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3602 bool receiverIdOrClass=false) {
3603 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3604 /*instance*/false);
3605 }
3606
3607 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3608 QualType ObjectType=QualType());
3609 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3610 /// implementation.
3611 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3612
3613 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3614 /// initialization.
3615 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3616 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3617
3618 //===--------------------------------------------------------------------===//
3619 // Statement Parsing Callbacks: SemaStmt.cpp.
3620public:
3621 class FullExprArg {
3622 public:
3623 FullExprArg() : E(nullptr) { }
3624 FullExprArg(Sema &actions) : E(nullptr) { }
3625
3626 ExprResult release() {
3627 return E;
3628 }
3629
3630 Expr *get() const { return E; }
3631
3632 Expr *operator->() {
3633 return E;
3634 }
3635
3636 private:
3637 // FIXME: No need to make the entire Sema class a friend when it's just
3638 // Sema::MakeFullExpr that needs access to the constructor below.
3639 friend class Sema;
3640
3641 explicit FullExprArg(Expr *expr) : E(expr) {}
3642
3643 Expr *E;
3644 };
3645
3646 FullExprArg MakeFullExpr(Expr *Arg) {
3647 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3648 }
3649 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3650 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3651 }
3652 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3653 ExprResult FE =
3654 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3655 /*DiscardedValue*/ true);
3656 return FullExprArg(FE.get());
3657 }
3658
3659 StmtResult ActOnExprStmt(ExprResult Arg);
3660 StmtResult ActOnExprStmtError();
3661
3662 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3663 bool HasLeadingEmptyMacro = false);
3664
3665 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
3666 void ActOnFinishOfCompoundStmt();
3667 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3668 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3669
3670 /// \brief A RAII object to enter scope of a compound statement.
3671 class CompoundScopeRAII {
3672 public:
3673 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
3674 S.ActOnStartOfCompoundStmt(IsStmtExpr);
3675 }
3676
3677 ~CompoundScopeRAII() {
3678 S.ActOnFinishOfCompoundStmt();
3679 }
3680
3681 private:
3682 Sema &S;
3683 };
3684
3685 /// An RAII helper that pops function a function scope on exit.
3686 struct FunctionScopeRAII {
3687 Sema &S;
3688 bool Active;
3689 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3690 ~FunctionScopeRAII() {
3691 if (Active)
3692 S.PopFunctionScopeInfo();
3693 }
3694 void disable() { Active = false; }
3695 };
3696
3697 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3698 SourceLocation StartLoc,
3699 SourceLocation EndLoc);
3700 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3701 StmtResult ActOnForEachLValueExpr(Expr *E);
3702 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3703 SourceLocation DotDotDotLoc, Expr *RHSVal,
3704 SourceLocation ColonLoc);
3705 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3706
3707 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3708 SourceLocation ColonLoc,
3709 Stmt *SubStmt, Scope *CurScope);
3710 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3711 SourceLocation ColonLoc, Stmt *SubStmt);
3712
3713 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3714 ArrayRef<const Attr*> Attrs,
3715 Stmt *SubStmt);
3716
3717 class ConditionResult;
3718 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3719 Stmt *InitStmt,
3720 ConditionResult Cond, Stmt *ThenVal,
3721 SourceLocation ElseLoc, Stmt *ElseVal);
3722 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3723 Stmt *InitStmt,
3724 ConditionResult Cond, Stmt *ThenVal,
3725 SourceLocation ElseLoc, Stmt *ElseVal);
3726 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3727 Stmt *InitStmt,
3728 ConditionResult Cond);
3729 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3730 Stmt *Switch, Stmt *Body);
3731 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3732 Stmt *Body);
3733 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3734 SourceLocation WhileLoc, SourceLocation CondLParen,
3735 Expr *Cond, SourceLocation CondRParen);
3736
3737 StmtResult ActOnForStmt(SourceLocation ForLoc,
3738 SourceLocation LParenLoc,
3739 Stmt *First,
3740 ConditionResult Second,
3741 FullExprArg Third,
3742 SourceLocation RParenLoc,
3743 Stmt *Body);
3744 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3745 Expr *collection);
3746 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3747 Stmt *First, Expr *collection,
3748 SourceLocation RParenLoc);
3749 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3750
3751 enum BuildForRangeKind {
3752 /// Initial building of a for-range statement.
3753 BFRK_Build,
3754 /// Instantiation or recovery rebuild of a for-range statement. Don't
3755 /// attempt any typo-correction.
3756 BFRK_Rebuild,
3757 /// Determining whether a for-range statement could be built. Avoid any
3758 /// unnecessary or irreversible actions.
3759 BFRK_Check
3760 };
3761
3762 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3763 SourceLocation CoawaitLoc,
3764 Stmt *LoopVar,
3765 SourceLocation ColonLoc, Expr *Collection,
3766 SourceLocation RParenLoc,
3767 BuildForRangeKind Kind);
3768 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3769 SourceLocation CoawaitLoc,
3770 SourceLocation ColonLoc,
3771 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3772 Expr *Cond, Expr *Inc,
3773 Stmt *LoopVarDecl,
3774 SourceLocation RParenLoc,
3775 BuildForRangeKind Kind);
3776 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3777
3778 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3779 SourceLocation LabelLoc,
3780 LabelDecl *TheDecl);
3781 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3782 SourceLocation StarLoc,
3783 Expr *DestExp);
3784 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3785 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3786
3787 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3788 CapturedRegionKind Kind, unsigned NumParams);
3789 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3790 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3791 CapturedRegionKind Kind,
3792 ArrayRef<CapturedParamNameType> Params);
3793 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3794 void ActOnCapturedRegionError();
3795 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3796 SourceLocation Loc,
3797 unsigned NumParams);
3798
3799 enum CopyElisionSemanticsKind {
3800 CES_Strict = 0,
3801 CES_AllowParameters = 1,
3802 CES_AllowDifferentTypes = 2,
3803 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
3804 };
3805
3806 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3807 CopyElisionSemanticsKind CESK);
3808 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3809 CopyElisionSemanticsKind CESK);
3810
3811 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3812 Scope *CurScope);
3813 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3814 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3815
3816 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3817 bool IsVolatile, unsigned NumOutputs,
3818 unsigned NumInputs, IdentifierInfo **Names,
3819 MultiExprArg Constraints, MultiExprArg Exprs,
3820 Expr *AsmString, MultiExprArg Clobbers,
3821 SourceLocation RParenLoc);
3822
3823 void FillInlineAsmIdentifierInfo(Expr *Res,
3824 llvm::InlineAsmIdentifierInfo &Info);
3825 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3826 SourceLocation TemplateKWLoc,
3827 UnqualifiedId &Id,
3828 bool IsUnevaluatedContext);
3829 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3830 unsigned &Offset, SourceLocation AsmLoc);
3831 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3832 SourceLocation AsmLoc);
3833 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3834 ArrayRef<Token> AsmToks,
3835 StringRef AsmString,
3836 unsigned NumOutputs, unsigned NumInputs,
3837 ArrayRef<StringRef> Constraints,
3838 ArrayRef<StringRef> Clobbers,
3839 ArrayRef<Expr*> Exprs,
3840 SourceLocation EndLoc);
3841 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3842 SourceLocation Location,
3843 bool AlwaysCreate);
3844
3845 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3846 SourceLocation StartLoc,
3847 SourceLocation IdLoc, IdentifierInfo *Id,
3848 bool Invalid = false);
3849
3850 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3851
3852 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3853 Decl *Parm, Stmt *Body);
3854
3855 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3856
3857 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3858 MultiStmtArg Catch, Stmt *Finally);
3859
3860 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3861 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3862 Scope *CurScope);
3863 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3864 Expr *operand);
3865 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3866 Expr *SynchExpr,
3867 Stmt *SynchBody);
3868
3869 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3870
3871 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3872 SourceLocation StartLoc,
3873 SourceLocation IdLoc,
3874 IdentifierInfo *Id);
3875
3876 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3877
3878 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3879 Decl *ExDecl, Stmt *HandlerBlock);
3880 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3881 ArrayRef<Stmt *> Handlers);
3882
3883 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3884 SourceLocation TryLoc, Stmt *TryBlock,
3885 Stmt *Handler);
3886 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3887 Expr *FilterExpr,
3888 Stmt *Block);
3889 void ActOnStartSEHFinallyBlock();
3890 void ActOnAbortSEHFinallyBlock();
3891 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3892 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3893
3894 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3895
3896 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3897
3898 /// \brief If it's a file scoped decl that must warn if not used, keep track
3899 /// of it.
3900 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3901
3902 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3903 /// whose result is unused, warn.
3904 void DiagnoseUnusedExprResult(const Stmt *S);
3905 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3906 void DiagnoseUnusedDecl(const NamedDecl *ND);
3907
3908 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3909 /// statement as a \p Body, and it is located on the same line.
3910 ///
3911 /// This helps prevent bugs due to typos, such as:
3912 /// if (condition);
3913 /// do_stuff();
3914 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3915 const Stmt *Body,
3916 unsigned DiagID);
3917
3918 /// Warn if a for/while loop statement \p S, which is followed by
3919 /// \p PossibleBody, has a suspicious null statement as a body.
3920 void DiagnoseEmptyLoopBody(const Stmt *S,
3921 const Stmt *PossibleBody);
3922
3923 /// Warn if a value is moved to itself.
3924 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3925 SourceLocation OpLoc);
3926
3927 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3928 /// _Nonnull one.
3929 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3930 SourceLocation Loc);
3931
3932 /// Warn when implicitly casting 0 to nullptr.
3933 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
3934
3935 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3936 return DelayedDiagnostics.push(pool);
3937 }
3938 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3939
3940 typedef ProcessingContextState ParsingClassState;
3941 ParsingClassState PushParsingClass() {
3942 return DelayedDiagnostics.pushUndelayed();
3943 }
3944 void PopParsingClass(ParsingClassState state) {
3945 DelayedDiagnostics.popUndelayed(state);
3946 }
3947
3948 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3949
3950 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
3951 const ObjCInterfaceDecl *UnknownObjCClass,
3952 bool ObjCPropertyAccess,
3953 bool AvoidPartialAvailabilityChecks = false);
3954
3955 bool makeUnavailableInSystemHeader(SourceLocation loc,
3956 UnavailableAttr::ImplicitReason reason);
3957
3958 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3959 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3960
3961 //===--------------------------------------------------------------------===//
3962 // Expression Parsing Callbacks: SemaExpr.cpp.
3963
3964 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3965 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
3966 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
3967 bool ObjCPropertyAccess = false,
3968 bool AvoidPartialAvailabilityChecks = false);
3969 void NoteDeletedFunction(FunctionDecl *FD);
3970 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3971 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3972 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3973 ObjCMethodDecl *Getter,
3974 SourceLocation Loc);
3975 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3976 ArrayRef<Expr *> Args);
3977
3978 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3979 Decl *LambdaContextDecl = nullptr,
3980 bool IsDecltype = false);
3981 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3982 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3983 ReuseLambdaContextDecl_t,
3984 bool IsDecltype = false);
3985 void PopExpressionEvaluationContext();
3986
3987 void DiscardCleanupsInEvaluationContext();
3988
3989 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3990 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3991
3992 ExprResult ActOnConstantExpression(ExprResult Res);
3993
3994 // Functions for marking a declaration referenced. These functions also
3995 // contain the relevant logic for marking if a reference to a function or
3996 // variable is an odr-use (in the C++11 sense). There are separate variants
3997 // for expressions referring to a decl; these exist because odr-use marking
3998 // needs to be delayed for some constant variables when we build one of the
3999 // named expressions.
4000 //
4001 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
4002 // should usually be true. This only needs to be set to false if the lack of
4003 // odr-use cannot be determined from the current context (for instance,
4004 // because the name denotes a virtual function and was written without an
4005 // explicit nested-name-specifier).
4006 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
4007 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
4008 bool MightBeOdrUse = true);
4009 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
4010 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
4011 void MarkMemberReferenced(MemberExpr *E);
4012
4013 void UpdateMarkingForLValueToRValue(Expr *E);
4014 void CleanupVarDeclMarking();
4015
4016 enum TryCaptureKind {
4017 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
4018 };
4019
4020 /// \brief Try to capture the given variable.
4021 ///
4022 /// \param Var The variable to capture.
4023 ///
4024 /// \param Loc The location at which the capture occurs.
4025 ///
4026 /// \param Kind The kind of capture, which may be implicit (for either a
4027 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
4028 ///
4029 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
4030 /// an explicit lambda capture.
4031 ///
4032 /// \param BuildAndDiagnose Whether we are actually supposed to add the
4033 /// captures or diagnose errors. If false, this routine merely check whether
4034 /// the capture can occur without performing the capture itself or complaining
4035 /// if the variable cannot be captured.
4036 ///
4037 /// \param CaptureType Will be set to the type of the field used to capture
4038 /// this variable in the innermost block or lambda. Only valid when the
4039 /// variable can be captured.
4040 ///
4041 /// \param DeclRefType Will be set to the type of a reference to the capture
4042 /// from within the current scope. Only valid when the variable can be
4043 /// captured.
4044 ///
4045 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4046 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4047 /// This is useful when enclosing lambdas must speculatively capture
4048 /// variables that may or may not be used in certain specializations of
4049 /// a nested generic lambda.
4050 ///
4051 /// \returns true if an error occurred (i.e., the variable cannot be
4052 /// captured) and false if the capture succeeded.
4053 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
4054 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
4055 QualType &CaptureType,
4056 QualType &DeclRefType,
4057 const unsigned *const FunctionScopeIndexToStopAt);
4058
4059 /// \brief Try to capture the given variable.
4060 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
4061 TryCaptureKind Kind = TryCapture_Implicit,
4062 SourceLocation EllipsisLoc = SourceLocation());
4063
4064 /// \brief Checks if the variable must be captured.
4065 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4066
4067 /// \brief Given a variable, determine the type that a reference to that
4068 /// variable will have in the given scope.
4069 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4070
4071 /// Mark all of the declarations referenced within a particular AST node as
4072 /// referenced. Used when template instantiation instantiates a non-dependent
4073 /// type -- entities referenced by the type are now referenced.
4074 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4075 void MarkDeclarationsReferencedInExpr(Expr *E,
4076 bool SkipLocalVariables = false);
4077
4078 /// \brief Try to recover by turning the given expression into a
4079 /// call. Returns true if recovery was attempted or an error was
4080 /// emitted; this may also leave the ExprResult invalid.
4081 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4082 bool ForceComplain = false,
4083 bool (*IsPlausibleResult)(QualType) = nullptr);
4084
4085 /// \brief Figure out if an expression could be turned into a call.
4086 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4087 UnresolvedSetImpl &NonTemplateOverloads);
4088
4089 /// \brief Conditionally issue a diagnostic based on the current
4090 /// evaluation context.
4091 ///
4092 /// \param Statement If Statement is non-null, delay reporting the
4093 /// diagnostic until the function body is parsed, and then do a basic
4094 /// reachability analysis to determine if the statement is reachable.
4095 /// If it is unreachable, the diagnostic will not be emitted.
4096 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4097 const PartialDiagnostic &PD);
4098
4099 // Primary Expressions.
4100 SourceRange getExprRange(Expr *E) const;
4101
4102 ExprResult ActOnIdExpression(
4103 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4104 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4105 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4106 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4107
4108 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4109 TemplateArgumentListInfo &Buffer,
4110 DeclarationNameInfo &NameInfo,
4111 const TemplateArgumentListInfo *&TemplateArgs);
4112
4113 bool
4114 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4115 std::unique_ptr<CorrectionCandidateCallback> CCC,
4116 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4117 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4118
4119 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4120 IdentifierInfo *II,
4121 bool AllowBuiltinCreation=false);
4122
4123 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4124 SourceLocation TemplateKWLoc,
4125 const DeclarationNameInfo &NameInfo,
4126 bool isAddressOfOperand,
4127 const TemplateArgumentListInfo *TemplateArgs);
4128
4129 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4130 ExprValueKind VK,
4131 SourceLocation Loc,
4132 const CXXScopeSpec *SS = nullptr);
4133 ExprResult
4134 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4135 const DeclarationNameInfo &NameInfo,
4136 const CXXScopeSpec *SS = nullptr,
4137 NamedDecl *FoundD = nullptr,
4138 const TemplateArgumentListInfo *TemplateArgs = nullptr);
4139 ExprResult
4140 BuildAnonymousStructUnionMemberReference(
4141 const CXXScopeSpec &SS,
4142 SourceLocation nameLoc,
4143 IndirectFieldDecl *indirectField,
4144 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4145 Expr *baseObjectExpr = nullptr,
4146 SourceLocation opLoc = SourceLocation());
4147
4148 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4149 SourceLocation TemplateKWLoc,
4150 LookupResult &R,
4151 const TemplateArgumentListInfo *TemplateArgs,
4152 const Scope *S);
4153 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4154 SourceLocation TemplateKWLoc,
4155 LookupResult &R,
4156 const TemplateArgumentListInfo *TemplateArgs,
4157 bool IsDefiniteInstance,
4158 const Scope *S);
4159 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4160 const LookupResult &R,
4161 bool HasTrailingLParen);
4162
4163 ExprResult
4164 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4165 const DeclarationNameInfo &NameInfo,
4166 bool IsAddressOfOperand, const Scope *S,
4167 TypeSourceInfo **RecoveryTSI = nullptr);
4168
4169 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4170 SourceLocation TemplateKWLoc,
4171 const DeclarationNameInfo &NameInfo,
4172 const TemplateArgumentListInfo *TemplateArgs);
4173
4174 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4175 LookupResult &R,
4176 bool NeedsADL,
4177 bool AcceptInvalidDecl = false);
4178 ExprResult BuildDeclarationNameExpr(
4179 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4180 NamedDecl *FoundD = nullptr,
4181 const TemplateArgumentListInfo *TemplateArgs = nullptr,
4182 bool AcceptInvalidDecl = false);
4183
4184 ExprResult BuildLiteralOperatorCall(LookupResult &R,
4185 DeclarationNameInfo &SuffixInfo,
4186 ArrayRef<Expr *> Args,
4187 SourceLocation LitEndLoc,
4188 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4189
4190 ExprResult BuildPredefinedExpr(SourceLocation Loc,
4191 PredefinedExpr::IdentType IT);
4192 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4193 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4194
4195 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4196
4197 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4198 ExprResult ActOnCharacterConstant(const Token &Tok,
4199 Scope *UDLScope = nullptr);
4200 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4201 ExprResult ActOnParenListExpr(SourceLocation L,
4202 SourceLocation R,
4203 MultiExprArg Val);
4204
4205 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4206 /// fragments (e.g. "foo" "bar" L"baz").
4207 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4208 Scope *UDLScope = nullptr);
4209
4210 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4211 SourceLocation DefaultLoc,
4212 SourceLocation RParenLoc,
4213 Expr *ControllingExpr,
4214 ArrayRef<ParsedType> ArgTypes,
4215 ArrayRef<Expr *> ArgExprs);
4216 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4217 SourceLocation DefaultLoc,
4218 SourceLocation RParenLoc,
4219 Expr *ControllingExpr,
4220 ArrayRef<TypeSourceInfo *> Types,
4221 ArrayRef<Expr *> Exprs);
4222
4223 // Binary/Unary Operators. 'Tok' is the token for the operator.
4224 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4225 Expr *InputExpr);
4226 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4227 UnaryOperatorKind Opc, Expr *Input);
4228 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4229 tok::TokenKind Op, Expr *Input);
4230
4231 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4232
4233 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4234 SourceLocation OpLoc,
4235 UnaryExprOrTypeTrait ExprKind,
4236 SourceRange R);
4237 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4238 UnaryExprOrTypeTrait ExprKind);
4239 ExprResult
4240 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4241 UnaryExprOrTypeTrait ExprKind,
4242 bool IsType, void *TyOrEx,
4243 SourceRange ArgRange);
4244
4245 ExprResult CheckPlaceholderExpr(Expr *E);
4246 bool CheckVecStepExpr(Expr *E);
4247
4248 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4249 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4250 SourceRange ExprRange,
4251 UnaryExprOrTypeTrait ExprKind);
4252 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4253 SourceLocation OpLoc,
4254 IdentifierInfo &Name,
4255 SourceLocation NameLoc,
4256 SourceLocation RParenLoc);
4257 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4258 tok::TokenKind Kind, Expr *Input);
4259
4260 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4261 Expr *Idx, SourceLocation RLoc);
4262 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4263 Expr *Idx, SourceLocation RLoc);
4264 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4265 Expr *LowerBound, SourceLocation ColonLoc,
4266 Expr *Length, SourceLocation RBLoc);
4267
4268 // This struct is for use by ActOnMemberAccess to allow
4269 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4270 // changing the access operator from a '.' to a '->' (to see if that is the
4271 // change needed to fix an error about an unknown member, e.g. when the class
4272 // defines a custom operator->).
4273 struct ActOnMemberAccessExtraArgs {
4274 Scope *S;
4275 UnqualifiedId &Id;
4276 Decl *ObjCImpDecl;
4277 };
4278
4279 ExprResult BuildMemberReferenceExpr(
4280 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4281 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4282 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4283 const TemplateArgumentListInfo *TemplateArgs,
4284 const Scope *S,
4285 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4286
4287 ExprResult
4288 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4289 bool IsArrow, const CXXScopeSpec &SS,
4290 SourceLocation TemplateKWLoc,
4291 NamedDecl *FirstQualifierInScope, LookupResult &R,
4292 const TemplateArgumentListInfo *TemplateArgs,
4293 const Scope *S,
4294 bool SuppressQualifierCheck = false,
4295 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4296
4297 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4298 SourceLocation OpLoc,
4299 const CXXScopeSpec &SS, FieldDecl *Field,
4300 DeclAccessPair FoundDecl,
4301 const DeclarationNameInfo &MemberNameInfo);
4302
4303 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4304
4305 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4306 const CXXScopeSpec &SS,
4307 const LookupResult &R);
4308
4309 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4310 bool IsArrow, SourceLocation OpLoc,
4311 const CXXScopeSpec &SS,
4312 SourceLocation TemplateKWLoc,
4313 NamedDecl *FirstQualifierInScope,
4314 const DeclarationNameInfo &NameInfo,
4315 const TemplateArgumentListInfo *TemplateArgs);
4316
4317 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4318 SourceLocation OpLoc,
4319 tok::TokenKind OpKind,
4320 CXXScopeSpec &SS,
4321 SourceLocation TemplateKWLoc,
4322 UnqualifiedId &Member,
4323 Decl *ObjCImpDecl);
4324
4325 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4326 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4327 FunctionDecl *FDecl,
4328 const FunctionProtoType *Proto,
4329 ArrayRef<Expr *> Args,
4330 SourceLocation RParenLoc,
4331 bool ExecConfig = false);
4332 void CheckStaticArrayArgument(SourceLocation CallLoc,
4333 ParmVarDecl *Param,
4334 const Expr *ArgExpr);
4335
4336 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4337 /// This provides the location of the left/right parens and a list of comma
4338 /// locations.
4339 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4340 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4341 Expr *ExecConfig = nullptr,
4342 bool IsExecConfig = false);
4343 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4344 SourceLocation LParenLoc,
4345 ArrayRef<Expr *> Arg,
4346 SourceLocation RParenLoc,
4347 Expr *Config = nullptr,
4348 bool IsExecConfig = false);
4349
4350 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4351 MultiExprArg ExecConfig,
4352 SourceLocation GGGLoc);
4353
4354 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4355 Declarator &D, ParsedType &Ty,
4356 SourceLocation RParenLoc, Expr *CastExpr);
4357 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4358 TypeSourceInfo *Ty,
4359 SourceLocation RParenLoc,
4360 Expr *Op);
4361 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4362
4363 /// \brief Build an altivec or OpenCL literal.
4364 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4365 SourceLocation RParenLoc, Expr *E,
4366 TypeSourceInfo *TInfo);
4367
4368 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4369
4370 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4371 ParsedType Ty,
4372 SourceLocation RParenLoc,
4373 Expr *InitExpr);
4374
4375 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4376 TypeSourceInfo *TInfo,
4377 SourceLocation RParenLoc,
4378 Expr *LiteralExpr);
4379
4380 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4381 MultiExprArg InitArgList,
4382 SourceLocation RBraceLoc);
4383
4384 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4385 SourceLocation Loc,
4386 bool GNUSyntax,
4387 ExprResult Init);
4388
4389private:
4390 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4391
4392public:
4393 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4394 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4395 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4396 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4397 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4398 Expr *LHSExpr, Expr *RHSExpr);
4399
4400 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4401
4402 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4403 /// in the case of a the GNU conditional expr extension.
4404 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4405 SourceLocation ColonLoc,
4406 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4407
4408 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4409 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4410 LabelDecl *TheDecl);
4411
4412 void ActOnStartStmtExpr();
4413 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4414 SourceLocation RPLoc); // "({..})"
4415 void ActOnStmtExprError();
4416
4417 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4418 struct OffsetOfComponent {
4419 SourceLocation LocStart, LocEnd;
4420 bool isBrackets; // true if [expr], false if .ident
4421 union {
4422 IdentifierInfo *IdentInfo;
4423 Expr *E;
4424 } U;
4425 };
4426
4427 /// __builtin_offsetof(type, a.b[123][456].c)
4428 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4429 TypeSourceInfo *TInfo,
4430 ArrayRef<OffsetOfComponent> Components,
4431 SourceLocation RParenLoc);
4432 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4433 SourceLocation BuiltinLoc,
4434 SourceLocation TypeLoc,
4435 ParsedType ParsedArgTy,
4436 ArrayRef<OffsetOfComponent> Components,
4437 SourceLocation RParenLoc);
4438
4439 // __builtin_choose_expr(constExpr, expr1, expr2)
4440 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4441 Expr *CondExpr, Expr *LHSExpr,
4442 Expr *RHSExpr, SourceLocation RPLoc);
4443
4444 // __builtin_va_arg(expr, type)
4445 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4446 SourceLocation RPLoc);
4447 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4448 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4449
4450 // __null
4451 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4452
4453 bool CheckCaseExpression(Expr *E);
4454
4455 /// \brief Describes the result of an "if-exists" condition check.
4456 enum IfExistsResult {
4457 /// \brief The symbol exists.
4458 IER_Exists,
4459
4460 /// \brief The symbol does not exist.
4461 IER_DoesNotExist,
4462
4463 /// \brief The name is a dependent name, so the results will differ
4464 /// from one instantiation to the next.
4465 IER_Dependent,
4466
4467 /// \brief An error occurred.
4468 IER_Error
4469 };
4470
4471 IfExistsResult
4472 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4473 const DeclarationNameInfo &TargetNameInfo);
4474
4475 IfExistsResult
4476 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4477 bool IsIfExists, CXXScopeSpec &SS,
4478 UnqualifiedId &Name);
4479
4480 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4481 bool IsIfExists,
4482 NestedNameSpecifierLoc QualifierLoc,
4483 DeclarationNameInfo NameInfo,
4484 Stmt *Nested);
4485 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4486 bool IsIfExists,
4487 CXXScopeSpec &SS, UnqualifiedId &Name,
4488 Stmt *Nested);
4489
4490 //===------------------------- "Block" Extension ------------------------===//
4491
4492 /// ActOnBlockStart - This callback is invoked when a block literal is
4493 /// started.
4494 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4495
4496 /// ActOnBlockArguments - This callback allows processing of block arguments.
4497 /// If there are no arguments, this is still invoked.
4498 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4499 Scope *CurScope);
4500
4501 /// ActOnBlockError - If there is an error parsing a block, this callback
4502 /// is invoked to pop the information about the block from the action impl.
4503 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4504
4505 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4506 /// literal was successfully completed. ^(int x){...}
4507 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4508 Scope *CurScope);
4509
4510 //===---------------------------- Clang Extensions ----------------------===//
4511
4512 /// __builtin_convertvector(...)
4513 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4514 SourceLocation BuiltinLoc,
4515 SourceLocation RParenLoc);
4516
4517 //===---------------------------- OpenCL Features -----------------------===//
4518
4519 /// __builtin_astype(...)
4520 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4521 SourceLocation BuiltinLoc,
4522 SourceLocation RParenLoc);
4523
4524 //===---------------------------- C++ Features --------------------------===//
4525
4526 // Act on C++ namespaces
4527 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4528 SourceLocation NamespaceLoc,
4529 SourceLocation IdentLoc,
4530 IdentifierInfo *Ident,
4531 SourceLocation LBrace,
4532 AttributeList *AttrList,
4533 UsingDirectiveDecl * &UsingDecl);
4534 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4535
4536 NamespaceDecl *getStdNamespace() const;
4537 NamespaceDecl *getOrCreateStdNamespace();
4538
4539 NamespaceDecl *lookupStdExperimentalNamespace();
4540
4541 CXXRecordDecl *getStdBadAlloc() const;
4542 EnumDecl *getStdAlignValT() const;
4543
4544 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4545 /// it is and Element is not NULL, assigns the element type to Element.
4546 bool isStdInitializerList(QualType Ty, QualType *Element);
4547
4548 /// \brief Looks for the std::initializer_list template and instantiates it
4549 /// with Element, or emits an error if it's not found.
4550 ///
4551 /// \returns The instantiated template, or null on error.
4552 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4553
4554 /// \brief Determine whether Ctor is an initializer-list constructor, as
4555 /// defined in [dcl.init.list]p2.
4556 bool isInitListConstructor(const FunctionDecl *Ctor);
4557
4558 Decl *ActOnUsingDirective(Scope *CurScope,
4559 SourceLocation UsingLoc,
4560 SourceLocation NamespcLoc,
4561 CXXScopeSpec &SS,
4562 SourceLocation IdentLoc,
4563 IdentifierInfo *NamespcName,
4564 AttributeList *AttrList);
4565
4566 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4567
4568 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4569 SourceLocation NamespaceLoc,
4570 SourceLocation AliasLoc,
4571 IdentifierInfo *Alias,
4572 CXXScopeSpec &SS,
4573 SourceLocation IdentLoc,
4574 IdentifierInfo *Ident);
4575
4576 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4577 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4578 const LookupResult &PreviousDecls,
4579 UsingShadowDecl *&PrevShadow);
4580 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4581 NamedDecl *Target,
4582 UsingShadowDecl *PrevDecl);
4583
4584 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4585 bool HasTypenameKeyword,
4586 const CXXScopeSpec &SS,
4587 SourceLocation NameLoc,
4588 const LookupResult &Previous);
4589 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4590 bool HasTypename,
4591 const CXXScopeSpec &SS,
4592 const DeclarationNameInfo &NameInfo,
4593 SourceLocation NameLoc);
4594
4595 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4596 SourceLocation UsingLoc,
4597 bool HasTypenameKeyword,
4598 SourceLocation TypenameLoc,
4599 CXXScopeSpec &SS,
4600 DeclarationNameInfo NameInfo,
4601 SourceLocation EllipsisLoc,
4602 AttributeList *AttrList,
4603 bool IsInstantiation);
4604 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4605 ArrayRef<NamedDecl *> Expansions);
4606
4607 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4608
4609 /// Given a derived-class using shadow declaration for a constructor and the
4610 /// correspnding base class constructor, find or create the implicit
4611 /// synthesized derived class constructor to use for this initialization.
4612 CXXConstructorDecl *
4613 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4614 ConstructorUsingShadowDecl *DerivedShadow);
4615
4616 Decl *ActOnUsingDeclaration(Scope *CurScope,
4617 AccessSpecifier AS,
4618 SourceLocation UsingLoc,
4619 SourceLocation TypenameLoc,
4620 CXXScopeSpec &SS,
4621 UnqualifiedId &Name,
4622 SourceLocation EllipsisLoc,
4623 AttributeList *AttrList);
4624 Decl *ActOnAliasDeclaration(Scope *CurScope,
4625 AccessSpecifier AS,
4626 MultiTemplateParamsArg TemplateParams,
4627 SourceLocation UsingLoc,
4628 UnqualifiedId &Name,
4629 AttributeList *AttrList,
4630 TypeResult Type,
4631 Decl *DeclFromDeclSpec);
4632
4633 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4634 /// including handling of its default argument expressions.
4635 ///
4636 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4637 ExprResult
4638 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4639 NamedDecl *FoundDecl,
4640 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4641 bool HadMultipleCandidates, bool IsListInitialization,
4642 bool IsStdInitListInitialization,
4643 bool RequiresZeroInit, unsigned ConstructKind,
4644 SourceRange ParenRange);
4645
4646 /// Build a CXXConstructExpr whose constructor has already been resolved if
4647 /// it denotes an inherited constructor.
4648 ExprResult
4649 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4650 CXXConstructorDecl *Constructor, bool Elidable,
4651 MultiExprArg Exprs,
4652 bool HadMultipleCandidates, bool IsListInitialization,
4653 bool IsStdInitListInitialization,
4654 bool RequiresZeroInit, unsigned ConstructKind,
4655 SourceRange ParenRange);
4656
4657 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4658 // the constructor can be elidable?
4659 ExprResult
4660 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4661 NamedDecl *FoundDecl,
4662 CXXConstructorDecl *Constructor, bool Elidable,
4663 MultiExprArg Exprs, bool HadMultipleCandidates,
4664 bool IsListInitialization,
4665 bool IsStdInitListInitialization, bool RequiresZeroInit,
4666 unsigned ConstructKind, SourceRange ParenRange);
4667
4668 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4669
4670
4671 /// Instantiate or parse a C++ default argument expression as necessary.
4672 /// Return true on error.
4673 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4674 ParmVarDecl *Param);
4675
4676 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4677 /// the default expr if needed.
4678 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4679 FunctionDecl *FD,
4680 ParmVarDecl *Param);
4681
4682 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4683 /// constructed variable.
4684 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4685
4686 /// \brief Helper class that collects exception specifications for
4687 /// implicitly-declared special member functions.
4688 class ImplicitExceptionSpecification {
4689 // Pointer to allow copying
4690 Sema *Self;
4691 // We order exception specifications thus:
4692 // noexcept is the most restrictive, but is only used in C++11.
4693 // throw() comes next.
4694 // Then a throw(collected exceptions)
4695 // Finally no specification, which is expressed as noexcept(false).
4696 // throw(...) is used instead if any called function uses it.
4697 ExceptionSpecificationType ComputedEST;
4698 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4699 SmallVector<QualType, 4> Exceptions;
4700
4701 void ClearExceptions() {
4702 ExceptionsSeen.clear();
4703 Exceptions.clear();
4704 }
4705
4706 public:
4707 explicit ImplicitExceptionSpecification(Sema &Self)
4708 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4709 if (!Self.getLangOpts().CPlusPlus11)
4710 ComputedEST = EST_DynamicNone;
4711 }
4712
4713 /// \brief Get the computed exception specification type.
4714 ExceptionSpecificationType getExceptionSpecType() const {
4715 assert(ComputedEST != EST_ComputedNoexcept &&(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 4716, __extension__ __PRETTY_FUNCTION__))
4716 "noexcept(expr) should not be a possible result")(static_cast <bool> (ComputedEST != EST_ComputedNoexcept
&& "noexcept(expr) should not be a possible result")
? void (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include/clang/Sema/Sema.h"
, 4716, __extension__ __PRETTY_FUNCTION__))
;
4717 return ComputedEST;
4718 }
4719
4720 /// \brief The number of exceptions in the exception specification.
4721 unsigned size() const { return Exceptions.size(); }
4722
4723 /// \brief The set of exceptions in the exception specification.
4724 const QualType *data() const { return Exceptions.data(); }
4725
4726 /// \brief Integrate another called method into the collected data.
4727 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4728
4729 /// \brief Integrate an invoked expression into the collected data.
4730 void CalledExpr(Expr *E);
4731
4732 /// \brief Overwrite an EPI's exception specification with this
4733 /// computed exception specification.
4734 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4735 FunctionProtoType::ExceptionSpecInfo ESI;
4736 ESI.Type = getExceptionSpecType();
4737 if (ESI.Type == EST_Dynamic) {
4738 ESI.Exceptions = Exceptions;
4739 } else if (ESI.Type == EST_None) {
4740 /// C++11 [except.spec]p14:
4741 /// The exception-specification is noexcept(false) if the set of
4742 /// potential exceptions of the special member function contains "any"
4743 ESI.Type = EST_ComputedNoexcept;
4744 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4745 tok::kw_false).get();
4746 }
4747 return ESI;
4748 }
4749 };
4750
4751 /// \brief Determine what sort of exception specification a defaulted
4752 /// copy constructor of a class will have.
4753 ImplicitExceptionSpecification
4754 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4755 CXXMethodDecl *MD);
4756
4757 /// \brief Determine what sort of exception specification a defaulted
4758 /// default constructor of a class will have, and whether the parameter
4759 /// will be const.
4760 ImplicitExceptionSpecification
4761 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4762
4763 /// \brief Determine what sort of exception specification a defautled
4764 /// copy assignment operator of a class will have, and whether the
4765 /// parameter will be const.
4766 ImplicitExceptionSpecification
4767 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4768
4769 /// \brief Determine what sort of exception specification a defaulted move
4770 /// constructor of a class will have.
4771 ImplicitExceptionSpecification
4772 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4773
4774 /// \brief Determine what sort of exception specification a defaulted move
4775 /// assignment operator of a class will have.
4776 ImplicitExceptionSpecification
4777 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4778
4779 /// \brief Determine what sort of exception specification a defaulted
4780 /// destructor of a class will have.
4781 ImplicitExceptionSpecification
4782 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4783
4784 /// \brief Determine what sort of exception specification an inheriting
4785 /// constructor of a class will have.
4786 ImplicitExceptionSpecification
4787 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4788 CXXConstructorDecl *CD);
4789
4790 /// \brief Evaluate the implicit exception specification for a defaulted
4791 /// special member function.
4792 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4793
4794 /// \brief Check the given exception-specification and update the
4795 /// exception specification information with the results.
4796 void checkExceptionSpecification(bool IsTopLevel,
4797 ExceptionSpecificationType EST,
4798 ArrayRef<ParsedType> DynamicExceptions,
4799 ArrayRef<SourceRange> DynamicExceptionRanges,
4800 Expr *NoexceptExpr,
4801 SmallVectorImpl<QualType> &Exceptions,
4802 FunctionProtoType::ExceptionSpecInfo &ESI);
4803
4804 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4805 /// parse an exception specification to work around a libstdc++ bug.
4806 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4807
4808 /// \brief Add an exception-specification to the given member function
4809 /// (or member function template). The exception-specification was parsed
4810 /// after the method itself was declared.
4811 void actOnDelayedExceptionSpecification(Decl *Method,
4812 ExceptionSpecificationType EST,
4813 SourceRange SpecificationRange,
4814 ArrayRef<ParsedType> DynamicExceptions,
4815 ArrayRef<SourceRange> DynamicExceptionRanges,
4816 Expr *NoexceptExpr);
4817
4818 class InheritedConstructorInfo;
4819
4820 /// \brief Determine if a special member function should have a deleted
4821 /// definition when it is defaulted.
4822 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4823 InheritedConstructorInfo *ICI = nullptr,
4824 bool Diagnose = false);
4825
4826 /// \brief Declare the implicit default constructor for the given class.
4827 ///
4828 /// \param ClassDecl The class declaration into which the implicit
4829 /// default constructor will be added.
4830 ///
4831 /// \returns The implicitly-declared default constructor.
4832 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4833 CXXRecordDecl *ClassDecl);
4834
4835 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4836 /// defining this constructor as the default constructor.
4837 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4838 CXXConstructorDecl *Constructor);
4839
4840 /// \brief Declare the implicit destructor for the given class.
4841 ///
4842 /// \param ClassDecl The class declaration into which the implicit
4843 /// destructor will be added.
4844 ///
4845 /// \returns The implicitly-declared destructor.
4846 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4847
4848 /// DefineImplicitDestructor - Checks for feasibility of
4849 /// defining this destructor as the default destructor.
4850 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4851 CXXDestructorDecl *Destructor);
4852
4853 /// \brief Build an exception spec for destructors that don't have one.
4854 ///
4855 /// C++11 says that user-defined destructors with no exception spec get one
4856 /// that looks as if the destructor was implicitly declared.
4857 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4858 CXXDestructorDecl *Destructor);
4859
4860 /// \brief Define the specified inheriting constructor.
4861 void DefineInheritingConstructor(SourceLocation UseLoc,
4862 CXXConstructorDecl *Constructor);
4863
4864 /// \brief Declare the implicit copy constructor for the given class.
4865 ///
4866 /// \param ClassDecl The class declaration into which the implicit
4867 /// copy constructor will be added.
4868 ///
4869 /// \returns The implicitly-declared copy constructor.
4870 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4871
4872 /// DefineImplicitCopyConstructor - Checks for feasibility of
4873 /// defining this constructor as the copy constructor.
4874 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4875 CXXConstructorDecl *Constructor);
4876
4877 /// \brief Declare the implicit move constructor for the given class.
4878 ///
4879 /// \param ClassDecl The Class declaration into which the implicit
4880 /// move constructor will be added.
4881 ///
4882 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4883 /// declared.
4884 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4885
4886 /// DefineImplicitMoveConstructor - Checks for feasibility of
4887 /// defining this constructor as the move constructor.
4888 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4889 CXXConstructorDecl *Constructor);
4890
4891 /// \brief Declare the implicit copy assignment operator for the given class.
4892 ///
4893 /// \param ClassDecl The class declaration into which the implicit
4894 /// copy assignment operator will be added.
4895 ///
4896 /// \returns The implicitly-declared copy assignment operator.
4897 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4898
4899 /// \brief Defines an implicitly-declared copy assignment operator.
4900 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4901 CXXMethodDecl *MethodDecl);
4902
4903 /// \brief Declare the implicit move assignment operator for the given class.
4904 ///
4905 /// \param ClassDecl The Class declaration into which the implicit
4906 /// move assignment operator will be added.
4907 ///
4908 /// \returns The implicitly-declared move assignment operator, or NULL if it
4909 /// wasn't declared.
4910 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4911
4912 /// \brief Defines an implicitly-declared move assignment operator.
4913 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4914 CXXMethodDecl *MethodDecl);
4915
4916 /// \brief Force the declaration of any implicitly-declared members of this
4917 /// class.
4918 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4919
4920 /// \brief Check a completed declaration of an implicit special member.
4921 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4922
4923 /// \brief Determine whether the given function is an implicitly-deleted
4924 /// special member function.
4925 bool isImplicitlyDeleted(FunctionDecl *FD);
4926
4927 /// \brief Check whether 'this' shows up in the type of a static member
4928 /// function after the (naturally empty) cv-qualifier-seq would be.
4929 ///
4930 /// \returns true if an error occurred.
4931 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4932
4933 /// \brief Whether this' shows up in the exception specification of a static
4934 /// member function.
4935 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4936
4937 /// \brief Check whether 'this' shows up in the attributes of the given
4938 /// static member function.
4939 ///
4940 /// \returns true if an error occurred.
4941 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4942
4943 /// MaybeBindToTemporary - If the passed in expression has a record type with
4944 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4945 /// it simply returns the passed in expression.
4946 ExprResult MaybeBindToTemporary(Expr *E);
4947
4948 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4949 MultiExprArg ArgsPtr,
4950 SourceLocation Loc,
4951 SmallVectorImpl<Expr*> &ConvertedArgs,
4952 bool AllowExplicit = false,
4953 bool IsListInitialization = false);
4954
4955 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4956 SourceLocation NameLoc,
4957 IdentifierInfo &Name);
4958
4959 ParsedType getDestructorName(SourceLocation TildeLoc,
4960 IdentifierInfo &II, SourceLocation NameLoc,
4961 Scope *S, CXXScopeSpec &SS,
4962 ParsedType ObjectType,
4963 bool EnteringContext);
4964
4965 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4966 ParsedType ObjectType);
4967
4968 // Checks that reinterpret casts don't have undefined behavior.
4969 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4970 bool IsDereference, SourceRange Range);
4971
4972 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4973 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4974 tok::TokenKind Kind,
4975 SourceLocation LAngleBracketLoc,
4976 Declarator &D,
4977 SourceLocation RAngleBracketLoc,
4978 SourceLocation LParenLoc,
4979 Expr *E,
4980 SourceLocation RParenLoc);
4981
4982 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4983 tok::TokenKind Kind,
4984 TypeSourceInfo *Ty,
4985 Expr *E,
4986 SourceRange AngleBrackets,
4987 SourceRange Parens);
4988
4989 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4990 SourceLocation TypeidLoc,
4991 TypeSourceInfo *Operand,
4992 SourceLocation RParenLoc);
4993 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4994 SourceLocation TypeidLoc,
4995 Expr *Operand,
4996 SourceLocation RParenLoc);
4997
4998 /// ActOnCXXTypeid - Parse typeid( something ).
4999 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
5000 SourceLocation LParenLoc, bool isType,
5001 void *TyOrExpr,
5002 SourceLocation RParenLoc);
5003
5004 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5005 SourceLocation TypeidLoc,
5006 TypeSourceInfo *Operand,
5007 SourceLocation RParenLoc);
5008 ExprResult BuildCXXUuidof(QualType TypeInfoType,
5009 SourceLocation TypeidLoc,
5010 Expr *Operand,
5011 SourceLocation RParenLoc);
5012
5013 /// ActOnCXXUuidof - Parse __uuidof( something ).
5014 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
5015 SourceLocation LParenLoc, bool isType,
5016 void *TyOrExpr,
5017 SourceLocation RParenLoc);
5018
5019 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
5020 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5021 tok::TokenKind Operator,
5022 SourceLocation EllipsisLoc, Expr *RHS,
5023 SourceLocation RParenLoc);
5024 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
5025 BinaryOperatorKind Operator,
5026 SourceLocation EllipsisLoc, Expr *RHS,
5027 SourceLocation RParenLoc);
5028 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
5029 BinaryOperatorKind Operator);
5030
5031 //// ActOnCXXThis - Parse 'this' pointer.
5032 ExprResult ActOnCXXThis(SourceLocation loc);
5033
5034 /// \brief Try to retrieve the type of the 'this' pointer.
5035 ///
5036 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
5037 QualType getCurrentThisType();
5038
5039 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
5040 /// current context not being a non-static member function. In such cases,
5041 /// this provides the type used for 'this'.
5042 QualType CXXThisTypeOverride;
5043
5044 /// \brief RAII object used to temporarily allow the C++ 'this' expression
5045 /// to be used, with the given qualifiers on the current class type.
5046 class CXXThisScopeRAII {
5047 Sema &S;
5048 QualType OldCXXThisTypeOverride;
5049 bool Enabled;
5050
5051 public:
5052 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
5053 /// using the given declaration (which is either a class template or a
5054 /// class) along with the given qualifiers.
5055 /// along with the qualifiers placed on '*this'.
5056 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
5057 bool Enabled = true);
5058
5059 ~CXXThisScopeRAII();
5060 };
5061
5062 /// \brief Make sure the value of 'this' is actually available in the current
5063 /// context, if it is a potentially evaluated context.
5064 ///
5065 /// \param Loc The location at which the capture of 'this' occurs.
5066 ///
5067 /// \param Explicit Whether 'this' is explicitly captured in a lambda
5068 /// capture list.
5069 ///
5070 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5071 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5072 /// This is useful when enclosing lambdas must speculatively capture
5073 /// 'this' that may or may not be used in certain specializations of
5074 /// a nested generic lambda (depending on whether the name resolves to
5075 /// a non-static member function or a static function).
5076 /// \return returns 'true' if failed, 'false' if success.
5077 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5078 bool BuildAndDiagnose = true,
5079 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5080 bool ByCopy = false);
5081
5082 /// \brief Determine whether the given type is the type of *this that is used
5083 /// outside of the body of a member function for a type that is currently
5084 /// being defined.
5085 bool isThisOutsideMemberFunctionBody(QualType BaseType);
5086
5087 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5088 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5089
5090
5091 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5092 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5093
5094 ExprResult
5095 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5096 SourceLocation AtLoc, SourceLocation RParen);
5097
5098 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5099 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5100
5101 //// ActOnCXXThrow - Parse throw expressions.
5102 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5103 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5104 bool IsThrownVarInScope);
5105 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5106
5107 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5108 /// Can be interpreted either as function-style casting ("int(x)")
5109 /// or class type construction ("ClassType(x,y,z)")
5110 /// or creation of a value-initialized type ("int()").
5111 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5112 SourceLocation LParenOrBraceLoc,
5113 MultiExprArg Exprs,
5114 SourceLocation RParenOrBraceLoc,
5115 bool ListInitialization);
5116
5117 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5118 SourceLocation LParenLoc,
5119 MultiExprArg Exprs,
5120 SourceLocation RParenLoc,
5121 bool ListInitialization);
5122
5123 /// ActOnCXXNew - Parsed a C++ 'new' expression.
5124 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5125 SourceLocation PlacementLParen,
5126 MultiExprArg PlacementArgs,
5127 SourceLocation PlacementRParen,
5128 SourceRange TypeIdParens, Declarator &D,
5129 Expr *Initializer);
5130 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5131 SourceLocation PlacementLParen,
5132 MultiExprArg PlacementArgs,
5133 SourceLocation PlacementRParen,
5134 SourceRange TypeIdParens,
5135 QualType AllocType,
5136 TypeSourceInfo *AllocTypeInfo,
5137 Expr *ArraySize,
5138 SourceRange DirectInitRange,
5139 Expr *Initializer);
5140
5141 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5142 SourceRange R);
5143
5144 /// \brief The scope in which to find allocation functions.
5145 enum AllocationFunctionScope {
5146 /// \brief Only look for allocation functions in the global scope.
5147 AFS_Global,
5148 /// \brief Only look for allocation functions in the scope of the
5149 /// allocated class.
5150 AFS_Class,
5151 /// \brief Look for allocation functions in both the global scope
5152 /// and in the scope of the allocated class.
5153 AFS_Both
5154 };
5155
5156 /// \brief Finds the overloads of operator new and delete that are appropriate
5157 /// for the allocation.
5158 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5159 AllocationFunctionScope NewScope,
5160 AllocationFunctionScope DeleteScope,
5161 QualType AllocType, bool IsArray,
5162 bool &PassAlignment, MultiExprArg PlaceArgs,
5163 FunctionDecl *&OperatorNew,
5164 FunctionDecl *&OperatorDelete,
5165 bool Diagnose = true);
5166 void DeclareGlobalNewDelete();
5167 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5168 ArrayRef<QualType> Params);
5169
5170 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5171 DeclarationName Name, FunctionDecl* &Operator,
5172 bool Diagnose = true);
5173 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5174 bool CanProvideSize,
5175 bool Overaligned,
5176 DeclarationName Name);
5177 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5178 CXXRecordDecl *RD);
5179
5180 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5181 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5182 bool UseGlobal, bool ArrayForm,
5183 Expr *Operand);
5184 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5185 bool IsDelete, bool CallCanBeVirtual,
5186 bool WarnOnNonAbstractTypes,
5187 SourceLocation DtorLoc);
5188
5189 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5190 Expr *Operand, SourceLocation RParen);
5191 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5192 SourceLocation RParen);
5193
5194 /// \brief Parsed one of the type trait support pseudo-functions.
5195 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5196 ArrayRef<ParsedType> Args,
5197 SourceLocation RParenLoc);
5198 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5199 ArrayRef<TypeSourceInfo *> Args,
5200 SourceLocation RParenLoc);
5201
5202 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5203 /// pseudo-functions.
5204 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5205 SourceLocation KWLoc,
5206 ParsedType LhsTy,
5207 Expr *DimExpr,
5208 SourceLocation RParen);
5209
5210 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5211 SourceLocation KWLoc,
5212 TypeSourceInfo *TSInfo,
5213 Expr *DimExpr,
5214 SourceLocation RParen);
5215
5216 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5217 /// pseudo-functions.
5218 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5219 SourceLocation KWLoc,
5220 Expr *Queried,
5221 SourceLocation RParen);
5222
5223 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5224 SourceLocation KWLoc,
5225 Expr *Queried,
5226 SourceLocation RParen);
5227
5228 ExprResult ActOnStartCXXMemberReference(Scope *S,
5229 Expr *Base,
5230 SourceLocation OpLoc,
5231 tok::TokenKind OpKind,
5232 ParsedType &ObjectType,
5233 bool &MayBePseudoDestructor);
5234
5235 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5236 SourceLocation OpLoc,
5237 tok::TokenKind OpKind,
5238 const CXXScopeSpec &SS,
5239 TypeSourceInfo *ScopeType,
5240 SourceLocation CCLoc,
5241 SourceLocation TildeLoc,
5242 PseudoDestructorTypeStorage DestroyedType);
5243
5244 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5245 SourceLocation OpLoc,
5246 tok::TokenKind OpKind,
5247 CXXScopeSpec &SS,
5248 UnqualifiedId &FirstTypeName,
5249 SourceLocation CCLoc,
5250 SourceLocation TildeLoc,
5251 UnqualifiedId &SecondTypeName);
5252
5253 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5254 SourceLocation OpLoc,
5255 tok::TokenKind OpKind,
5256 SourceLocation TildeLoc,
5257 const DeclSpec& DS);
5258
5259 /// MaybeCreateExprWithCleanups - If the current full-expression
5260 /// requires any cleanups, surround it with a ExprWithCleanups node.
5261 /// Otherwise, just returns the passed-in expression.
5262 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5263 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5264 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5265
5266 MaterializeTemporaryExpr *
5267 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5268 bool BoundToLvalueReference);
5269
5270 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5271 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5272 : SourceLocation());
5273 }
5274 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5275 bool DiscardedValue = false,
5276 bool IsConstexpr = false,
5277 bool IsLambdaInitCaptureInitializer = false);
5278 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5279
5280 // Marks SS invalid if it represents an incomplete type.
5281 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5282
5283 DeclContext *computeDeclContext(QualType T);
5284 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5285 bool EnteringContext = false);
5286 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5287 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5288
5289 /// \brief The parser has parsed a global nested-name-specifier '::'.
5290