Bug Summary

File:tools/clang/include/clang/Sema/Sema.h
Warning:line 269, column 7
Excessive padding in 'class clang::Sema' (67 padding bytes, where 3 is optimal). Optimal fields order: ExternalSource, LangOpts, PP, Context, Consumer, Diags, SourceMgr, CodeCompleter, CurContext, OriginalLexicalContext, VAListTagName, CurInitSeg, VisContext, 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, CachedFakeTopLevelModule, CXXThisTypeOverride, CurrentInstantiationScope, ThreadSafetyDeclCache, VarDataSharingAttributesStack, TypeTagForDatatypeMagicValues, CurScope, Ident_super, Ident___float128, Ident__Nonnull, Ident__Nullable, Ident__Null_unspecified, Ident_NSError, CFError, IdResolver, SpecialMemberCache, OpenCLFeatures, ExtnameUndeclaredIdentifiers, FlagBitsCache, UnparsedDefaultArgInstantiations, UnparsedDefaultArgLocs, MethodPool, VisibleModules, ShadowingDecls, VTablesUsed, InstantiatingSpecializations, InstantiatedNonDependentTypes, LookupModulesCache, VisibleNamespaceCache, SuppressedDiagnostics, TypoCorrectionFailures, CurrOpenCLExtension, OpenCLTypeExtMap, OpenCLDeclExtMap, CUDADeferredDiags, LocsWithCUDACallDiags, CUDAKnownEmittedFns, CUDACallGraph, CurrentSEHFinally, WeakTopLevelDecl, NullabilityMap, MaybeODRUseExprs, FunctionScopes, DeleteExprs, DelayedExceptionSpecChecks, DelayedDefaultedMemberExceptionSpecs, LateParsedTemplateMap, WeakUndeclaredIdentifiers, UndefinedButUsed, ReferencedSelectors, DelayedTypos, KnownNamespaces, DelayedDllExportClasses, ParsingInitForAutoVars, ExtVectorDecls, TentativeDefinitions, UnusedFileScopedDecls, DelegatingCtorDecls, PendingInstantiations, PendingLocalImplicitInstantiations, VtorDispStack, PackStack, ExprCleanupObjects, AnalysisWarnings, UnusedLocalTypedefNameCandidates, DataSegStack, BSSSegStack, ConstSegStack, CodeSegStack, NSNumberLiteralMethods, SpecialMembersBeingDeclared, BumpAlloc, 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

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/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/TypoCorrection.h"
50#include "clang/Sema/Weak.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/SetVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <vector>
61
62namespace llvm {
63 class APSInt;
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
66 class SmallBitVector;
67 class InlineAsmIdentifierInfo;
68}
69
70namespace clang {
71 class ADLResult;
72 class ASTConsumer;
73 class ASTContext;
74 class ASTMutationListener;
75 class ASTReader;
76 class ASTWriter;
77 class ArrayType;
78 class AttributeList;
79 class BindingDecl;
80 class BlockDecl;
81 class CapturedDecl;
82 class CXXBasePath;
83 class CXXBasePaths;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
88 class CXXDeleteExpr;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
92 class CXXMethodDecl;
93 class CXXScopeSpec;
94 class CXXTemporary;
95 class CXXTryStmt;
96 class CallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
106 class Decl;
107 class DeclAccessPair;
108 class DeclContext;
109 class DeclRefExpr;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
114 class Designation;
115 class EnableIfAttr;
116 class EnumConstantDecl;
117 class Expr;
118 class ExtVectorType;
119 class FormatAttr;
120 class FriendDecl;
121 class FunctionDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
126 class InitListExpr;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
131 class LabelStmt;
132 class LambdaExpr;
133 class LangOptions;
134 class LocalInstantiationScope;
135 class LookupResult;
136 class MacroInfo;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
138 class ModuleLoader;
139 class MultiLevelTemplateArgumentList;
140 class NamedDecl;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
145 class ObjCImplDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
148 class ObjCIvarDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
157 class OMPClause;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
160 class OverloadExpr;
161 class ParenListExpr;
162 class ParmVarDecl;
163 class Preprocessor;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
166 class QualType;
167 class StandardConversionSequence;
168 class Stmt;
169 class StringLiteral;
170 class SwitchStmt;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
174 class TemplateDecl;
175 class TemplateParameterList;
176 class TemplatePartialOrderingContext;
177 class TemplateTemplateParmDecl;
178 class Token;
179 class TypeAliasDecl;
180 class TypedefDecl;
181 class TypedefNameDecl;
182 class TypeLoc;
183 class TypoCorrectionConsumer;
184 class UnqualifiedId;
185 class UnresolvedLookupExpr;
186 class UnresolvedMemberExpr;
187 class UnresolvedSetImpl;
188 class UnresolvedSetIterator;
189 class UsingDecl;
190 class UsingShadowDecl;
191 class ValueDecl;
192 class VarDecl;
193 class VarTemplateSpecializationDecl;
194 class VisibilityAttr;
195 class VisibleDeclConsumer;
196 class IndirectFieldDecl;
197 struct DeductionFailureInfo;
198 class TemplateSpecCandidateSet;
199
200namespace sema {
201 class AccessedEntity;
202 class BlockScopeInfo;
203 class CapturedRegionScopeInfo;
204 class CapturingScopeInfo;
205 class CompoundScopeInfo;
206 class DelayedDiagnostic;
207 class DelayedDiagnosticPool;
208 class FunctionScopeInfo;
209 class LambdaScopeInfo;
210 class PossiblyUnreachableDiag;
211 class TemplateDeductionInfo;
212}
213
214namespace threadSafety {
215 class BeforeSet;
216 void threadSafetyCleanup(BeforeSet* Cache);
217}
218
219// FIXME: No way to easily map from TemplateTypeParmTypes to
220// TemplateTypeParmDecls, so we have this horrible PointerUnion.
221typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
222 SourceLocation> UnexpandedParameterPack;
223
224/// Describes whether we've seen any nullability information for the given
225/// file.
226struct FileNullability {
227 /// The first pointer declarator (of any pointer kind) in the file that does
228 /// not have a corresponding nullability annotation.
229 SourceLocation PointerLoc;
230
231 /// Which kind of pointer declarator we saw.
232 uint8_t PointerKind;
233
234 /// Whether we saw any type nullability annotations in the given file.
235 bool SawTypeNullability = false;
236};
237
238/// A mapping from file IDs to a record of whether we've seen nullability
239/// information in that file.
240class FileNullabilityMap {
241 /// A mapping from file IDs to the nullability information for each file ID.
242 llvm::DenseMap<FileID, FileNullability> Map;
243
244 /// A single-element cache based on the file ID.
245 struct {
246 FileID File;
247 FileNullability Nullability;
248 } Cache;
249
250public:
251 FileNullability &operator[](FileID file) {
252 // Check the single-element cache.
253 if (file == Cache.File)
254 return Cache.Nullability;
255
256 // It's not in the single-element cache; flush the cache if we have one.
257 if (!Cache.File.isInvalid()) {
258 Map[Cache.File] = Cache.Nullability;
259 }
260
261 // Pull this entry into the cache.
262 Cache.File = file;
263 Cache.Nullability = Map[file];
264 return Cache.Nullability;
265 }
266};
267
268/// Sema - This implements semantic analysis and AST building for C.
269class Sema {
Excessive padding in 'class clang::Sema' (67 padding bytes, where 3 is optimal). Optimal fields order: ExternalSource, LangOpts, PP, Context, Consumer, Diags, SourceMgr, CodeCompleter, CurContext, OriginalLexicalContext, VAListTagName, CurInitSeg, VisContext, 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, CachedFakeTopLevelModule, CXXThisTypeOverride, CurrentInstantiationScope, ThreadSafetyDeclCache, VarDataSharingAttributesStack, TypeTagForDatatypeMagicValues, CurScope, Ident_super, Ident___float128, Ident__Nonnull, Ident__Nullable, Ident__Null_unspecified, Ident_NSError, CFError, IdResolver, SpecialMemberCache, OpenCLFeatures, ExtnameUndeclaredIdentifiers, FlagBitsCache, UnparsedDefaultArgInstantiations, UnparsedDefaultArgLocs, MethodPool, VisibleModules, ShadowingDecls, VTablesUsed, InstantiatingSpecializations, InstantiatedNonDependentTypes, LookupModulesCache, VisibleNamespaceCache, SuppressedDiagnostics, TypoCorrectionFailures, CurrOpenCLExtension, OpenCLTypeExtMap, OpenCLDeclExtMap, CUDADeferredDiags, LocsWithCUDACallDiags, CUDAKnownEmittedFns, CUDACallGraph, CurrentSEHFinally, WeakTopLevelDecl, NullabilityMap, MaybeODRUseExprs, FunctionScopes, DeleteExprs, DelayedExceptionSpecChecks, DelayedDefaultedMemberExceptionSpecs, LateParsedTemplateMap, WeakUndeclaredIdentifiers, UndefinedButUsed, ReferencedSelectors, DelayedTypos, KnownNamespaces, DelayedDllExportClasses, ParsingInitForAutoVars, ExtVectorDecls, TentativeDefinitions, UnusedFileScopedDecls, DelegatingCtorDecls, PendingInstantiations, PendingLocalImplicitInstantiations, VtorDispStack, PackStack, ExprCleanupObjects, AnalysisWarnings, UnusedLocalTypedefNameCandidates, DataSegStack, BSSSegStack, ConstSegStack, CodeSegStack, NSNumberLiteralMethods, SpecialMembersBeingDeclared, BumpAlloc, 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
270 Sema(const Sema &) = delete;
271 void operator=(const Sema &) = delete;
272
273 ///\brief Source of additional semantic information.
274 ExternalSemaSource *ExternalSource;
275
276 ///\brief Whether Sema has generated a multiplexer and has to delete it.
277 bool isMultiplexExternalSource;
278
279 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
280
281 bool isVisibleSlow(const NamedDecl *D);
282
283 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
284 const NamedDecl *New) {
285 // We are about to link these. It is now safe to compute the linkage of
286 // the new decl. If the new decl has external linkage, we will
287 // link it with the hidden decl (which also has external linkage) and
288 // it will keep having external linkage. If it has internal linkage, we
289 // will not link it. Since it has no previous decls, it will remain
290 // with internal linkage.
291 return isVisible(Old) || New->isExternallyVisible();
292 }
293 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
294
295public:
296 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
297 typedef OpaquePtr<TemplateName> TemplateTy;
298 typedef OpaquePtr<QualType> TypeTy;
299
300 OpenCLOptions OpenCLFeatures;
301 FPOptions FPFeatures;
302
303 const LangOptions &LangOpts;
304 Preprocessor &PP;
305 ASTContext &Context;
306 ASTConsumer &Consumer;
307 DiagnosticsEngine &Diags;
308 SourceManager &SourceMgr;
309
310 /// \brief Flag indicating whether or not to collect detailed statistics.
311 bool CollectStats;
312
313 /// \brief Code-completion consumer.
314 CodeCompleteConsumer *CodeCompleter;
315
316 /// CurContext - This is the current declaration context of parsing.
317 DeclContext *CurContext;
318
319 /// \brief Generally null except when we temporarily switch decl contexts,
320 /// like in \see ActOnObjCTemporaryExitContainerContext.
321 DeclContext *OriginalLexicalContext;
322
323 /// VAListTagName - The declaration name corresponding to __va_list_tag.
324 /// This is used as part of a hack to omit that class from ADL results.
325 DeclarationName VAListTagName;
326
327 bool MSStructPragmaOn; // True when \#pragma ms_struct on
328
329 /// \brief Controls member pointer representation format under the MS ABI.
330 LangOptions::PragmaMSPointersToMembersKind
331 MSPointerToMemberRepresentationMethod;
332
333 /// Stack of active SEH __finally scopes. Can be empty.
334 SmallVector<Scope*, 2> CurrentSEHFinally;
335
336 /// \brief Source location for newly created implicit MSInheritanceAttrs
337 SourceLocation ImplicitMSInheritanceAttrLoc;
338
339 enum PragmaMsStackAction {
340 PSK_Reset = 0x0, // #pragma ()
341 PSK_Set = 0x1, // #pragma (value)
342 PSK_Push = 0x2, // #pragma (push[, id])
343 PSK_Pop = 0x4, // #pragma (pop[, id])
344 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
345 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
346 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
347 };
348
349 template<typename ValueType>
350 struct PragmaStack {
351 struct Slot {
352 llvm::StringRef StackSlotLabel;
353 ValueType Value;
354 SourceLocation PragmaLocation;
355 Slot(llvm::StringRef StackSlotLabel,
356 ValueType Value,
357 SourceLocation PragmaLocation)
358 : StackSlotLabel(StackSlotLabel), Value(Value),
359 PragmaLocation(PragmaLocation) {}
360 };
361 void Act(SourceLocation PragmaLocation,
362 PragmaMsStackAction Action,
363 llvm::StringRef StackSlotLabel,
364 ValueType Value);
365
366 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
367 // method body to restore the stacks on exit, so it works like this:
368 //
369 // struct S {
370 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
371 // void Method {}
372 // #pragma <name>(pop, InternalPragmaSlot)
373 // };
374 //
375 // It works even with #pragma vtordisp, although MSVC doesn't support
376 // #pragma vtordisp(push [, id], n)
377 // syntax.
378 //
379 // Push / pop a named sentinel slot.
380 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
381 assert((Action == PSK_Push || Action == PSK_Pop) &&(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 382, __PRETTY_FUNCTION__))
382 "Can only push / pop #pragma stack sentinels!")(((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"
) ? static_cast<void> (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 382, __PRETTY_FUNCTION__))
;
383 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
384 }
385
386 // Constructors.
387 explicit PragmaStack(const ValueType &Default)
388 : DefaultValue(Default), CurrentValue(Default) {}
389
390 SmallVector<Slot, 2> Stack;
391 ValueType DefaultValue; // Value used for PSK_Reset action.
392 ValueType CurrentValue;
393 SourceLocation CurrentPragmaLocation;
394 };
395 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
396 // we shouldn't do so if they're in a module).
397
398 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
399 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
400 ///
401 /// 0: Suppress all vtordisps
402 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
403 /// structors
404 /// 2: Always insert vtordisps to support RTTI on partially constructed
405 /// objects
406 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
407 // #pragma pack.
408 // Sentinel to represent when the stack is set to mac68k alignment.
409 static const unsigned kMac68kAlignmentSentinel = ~0U;
410 PragmaStack<unsigned> PackStack;
411 // Segment #pragmas.
412 PragmaStack<StringLiteral *> DataSegStack;
413 PragmaStack<StringLiteral *> BSSSegStack;
414 PragmaStack<StringLiteral *> ConstSegStack;
415 PragmaStack<StringLiteral *> CodeSegStack;
416
417 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
418 // Actions should be performed only if we enter / exit a C++ method body.
419 class PragmaStackSentinelRAII {
420 public:
421 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
422 ~PragmaStackSentinelRAII();
423
424 private:
425 Sema &S;
426 StringRef SlotLabel;
427 bool ShouldAct;
428 };
429
430 /// A mapping that describes the nullability we've seen in each header file.
431 FileNullabilityMap NullabilityMap;
432
433 /// Last section used with #pragma init_seg.
434 StringLiteral *CurInitSeg;
435 SourceLocation CurInitSegLoc;
436
437 /// VisContext - Manages the stack for \#pragma GCC visibility.
438 void *VisContext; // Really a "PragmaVisStack*"
439
440 /// \brief This represents the last location of a "#pragma clang optimize off"
441 /// directive if such a directive has not been closed by an "on" yet. If
442 /// optimizations are currently "on", this is set to an invalid location.
443 SourceLocation OptimizeOffPragmaLocation;
444
445 /// \brief Flag indicating if Sema is building a recovery call expression.
446 ///
447 /// This flag is used to avoid building recovery call expressions
448 /// if Sema is already doing so, which would cause infinite recursions.
449 bool IsBuildingRecoveryCallExpr;
450
451 /// Used to control the generation of ExprWithCleanups.
452 CleanupInfo Cleanup;
453
454 /// ExprCleanupObjects - This is the stack of objects requiring
455 /// cleanup that are created by the current full expression. The
456 /// element type here is ExprWithCleanups::Object.
457 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
458
459 /// \brief Store a list of either DeclRefExprs or MemberExprs
460 /// that contain a reference to a variable (constant) that may or may not
461 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
462 /// and discarded value conversions have been applied to all subexpressions
463 /// of the enclosing full expression. This is cleared at the end of each
464 /// full expression.
465 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
466
467 /// \brief Stack containing information about each of the nested
468 /// function, block, and method scopes that are currently active.
469 ///
470 /// This array is never empty. Clients should ignore the first
471 /// element, which is used to cache a single FunctionScopeInfo
472 /// that's used to parse every top-level function.
473 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
474
475 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
476 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
477 ExtVectorDeclsType;
478
479 /// ExtVectorDecls - This is a list all the extended vector types. This allows
480 /// us to associate a raw vector type with one of the ext_vector type names.
481 /// This is only necessary for issuing pretty diagnostics.
482 ExtVectorDeclsType ExtVectorDecls;
483
484 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
485 std::unique_ptr<CXXFieldCollector> FieldCollector;
486
487 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
488
489 /// \brief Set containing all declared private fields that are not used.
490 NamedDeclSetType UnusedPrivateFields;
491
492 /// \brief Set containing all typedefs that are likely unused.
493 llvm::SmallSetVector<const TypedefNameDecl *, 4>
494 UnusedLocalTypedefNameCandidates;
495
496 /// \brief Delete-expressions to be analyzed at the end of translation unit
497 ///
498 /// This list contains class members, and locations of delete-expressions
499 /// that could not be proven as to whether they mismatch with new-expression
500 /// used in initializer of the field.
501 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
502 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
503 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
504
505 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
506
507 /// PureVirtualClassDiagSet - a set of class declarations which we have
508 /// emitted a list of pure virtual functions. Used to prevent emitting the
509 /// same list more than once.
510 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
511
512 /// ParsingInitForAutoVars - a set of declarations with auto types for which
513 /// we are currently parsing the initializer.
514 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
515
516 /// \brief Look for a locally scoped extern "C" declaration by the given name.
517 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
518
519 typedef LazyVector<VarDecl *, ExternalSemaSource,
520 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
521 TentativeDefinitionsType;
522
523 /// \brief All the tentative definitions encountered in the TU.
524 TentativeDefinitionsType TentativeDefinitions;
525
526 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
527 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
528 UnusedFileScopedDeclsType;
529
530 /// \brief The set of file scoped decls seen so far that have not been used
531 /// and must warn if not used. Only contains the first declaration.
532 UnusedFileScopedDeclsType UnusedFileScopedDecls;
533
534 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
535 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
536 DelegatingCtorDeclsType;
537
538 /// \brief All the delegating constructors seen so far in the file, used for
539 /// cycle detection at the end of the TU.
540 DelegatingCtorDeclsType DelegatingCtorDecls;
541
542 /// \brief All the overriding functions seen during a class definition
543 /// that had their exception spec checks delayed, plus the overridden
544 /// function.
545 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
546 DelayedExceptionSpecChecks;
547
548 /// \brief All the members seen during a class definition which were both
549 /// explicitly defaulted and had explicitly-specified exception
550 /// specifications, along with the function type containing their
551 /// user-specified exception specification. Those exception specifications
552 /// were overridden with the default specifications, but we still need to
553 /// check whether they are compatible with the default specification, and
554 /// we can't do that until the nesting set of class definitions is complete.
555 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
556 DelayedDefaultedMemberExceptionSpecs;
557
558 typedef llvm::MapVector<const FunctionDecl *,
559 std::unique_ptr<LateParsedTemplate>>
560 LateParsedTemplateMapT;
561 LateParsedTemplateMapT LateParsedTemplateMap;
562
563 /// \brief Callback to the parser to parse templated functions when needed.
564 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
565 typedef void LateTemplateParserCleanupCB(void *P);
566 LateTemplateParserCB *LateTemplateParser;
567 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
568 void *OpaqueParser;
569
570 void SetLateTemplateParser(LateTemplateParserCB *LTP,
571 LateTemplateParserCleanupCB *LTPCleanup,
572 void *P) {
573 LateTemplateParser = LTP;
574 LateTemplateParserCleanup = LTPCleanup;
575 OpaqueParser = P;
576 }
577
578 class DelayedDiagnostics;
579
580 class DelayedDiagnosticsState {
581 sema::DelayedDiagnosticPool *SavedPool;
582 friend class Sema::DelayedDiagnostics;
583 };
584 typedef DelayedDiagnosticsState ParsingDeclState;
585 typedef DelayedDiagnosticsState ProcessingContextState;
586
587 /// A class which encapsulates the logic for delaying diagnostics
588 /// during parsing and other processing.
589 class DelayedDiagnostics {
590 /// \brief The current pool of diagnostics into which delayed
591 /// diagnostics should go.
592 sema::DelayedDiagnosticPool *CurPool;
593
594 public:
595 DelayedDiagnostics() : CurPool(nullptr) {}
596
597 /// Adds a delayed diagnostic.
598 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
599
600 /// Determines whether diagnostics should be delayed.
601 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
602
603 /// Returns the current delayed-diagnostics pool.
604 sema::DelayedDiagnosticPool *getCurrentPool() const {
605 return CurPool;
606 }
607
608 /// Enter a new scope. Access and deprecation diagnostics will be
609 /// collected in this pool.
610 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
611 DelayedDiagnosticsState state;
612 state.SavedPool = CurPool;
613 CurPool = &pool;
614 return state;
615 }
616
617 /// Leave a delayed-diagnostic state that was previously pushed.
618 /// Do not emit any of the diagnostics. This is performed as part
619 /// of the bookkeeping of popping a pool "properly".
620 void popWithoutEmitting(DelayedDiagnosticsState state) {
621 CurPool = state.SavedPool;
622 }
623
624 /// Enter a new scope where access and deprecation diagnostics are
625 /// not delayed.
626 DelayedDiagnosticsState pushUndelayed() {
627 DelayedDiagnosticsState state;
628 state.SavedPool = CurPool;
629 CurPool = nullptr;
630 return state;
631 }
632
633 /// Undo a previous pushUndelayed().
634 void popUndelayed(DelayedDiagnosticsState state) {
635 assert(CurPool == nullptr)((CurPool == nullptr) ? static_cast<void> (0) : __assert_fail
("CurPool == nullptr", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 635, __PRETTY_FUNCTION__))
;
636 CurPool = state.SavedPool;
637 }
638 } DelayedDiagnostics;
639
640 /// A RAII object to temporarily push a declaration context.
641 class ContextRAII {
642 private:
643 Sema &S;
644 DeclContext *SavedContext;
645 ProcessingContextState SavedContextState;
646 QualType SavedCXXThisTypeOverride;
647
648 public:
649 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
650 : S(S), SavedContext(S.CurContext),
651 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
652 SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
653 {
654 assert(ContextToPush && "pushing null context")((ContextToPush && "pushing null context") ? static_cast
<void> (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 654, __PRETTY_FUNCTION__))
;
655 S.CurContext = ContextToPush;
656 if (NewThisContext)
657 S.CXXThisTypeOverride = QualType();
658 }
659
660 void pop() {
661 if (!SavedContext) return;
662 S.CurContext = SavedContext;
663 S.DelayedDiagnostics.popUndelayed(SavedContextState);
664 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
665 SavedContext = nullptr;
666 }
667
668 ~ContextRAII() {
669 pop();
670 }
671 };
672
673 /// \brief RAII object to handle the state changes required to synthesize
674 /// a function body.
675 class SynthesizedFunctionScope {
676 Sema &S;
677 Sema::ContextRAII SavedContext;
678
679 public:
680 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
681 : S(S), SavedContext(S, DC)
682 {
683 S.PushFunctionScope();
684 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
685 }
686
687 ~SynthesizedFunctionScope() {
688 S.PopExpressionEvaluationContext();
689 S.PopFunctionScopeInfo();
690 }
691 };
692
693 /// WeakUndeclaredIdentifiers - Identifiers contained in
694 /// \#pragma weak before declared. rare. may alias another
695 /// identifier, declared or undeclared
696 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
697
698 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
699 /// \#pragma redefine_extname before declared. Used in Solaris system headers
700 /// to define functions that occur in multiple standards to call the version
701 /// in the currently selected standard.
702 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
703
704
705 /// \brief Load weak undeclared identifiers from the external source.
706 void LoadExternalWeakUndeclaredIdentifiers();
707
708 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
709 /// \#pragma weak during processing of other Decls.
710 /// I couldn't figure out a clean way to generate these in-line, so
711 /// we store them here and handle separately -- which is a hack.
712 /// It would be best to refactor this.
713 SmallVector<Decl*,2> WeakTopLevelDecl;
714
715 IdentifierResolver IdResolver;
716
717 /// Translation Unit Scope - useful to Objective-C actions that need
718 /// to lookup file scope declarations in the "ordinary" C decl namespace.
719 /// For example, user-defined classes, built-in "id" type, etc.
720 Scope *TUScope;
721
722 /// \brief The C++ "std" namespace, where the standard library resides.
723 LazyDeclPtr StdNamespace;
724
725 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
726 /// standard library.
727 LazyDeclPtr StdBadAlloc;
728
729 /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
730 /// standard library.
731 LazyDeclPtr StdAlignValT;
732
733 /// \brief The C++ "std::experimental" namespace, where the experimental parts
734 /// of the standard library resides.
735 NamespaceDecl *StdExperimentalNamespaceCache;
736
737 /// \brief The C++ "std::initializer_list" template, which is defined in
738 /// \<initializer_list>.
739 ClassTemplateDecl *StdInitializerList;
740
741 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
742 RecordDecl *CXXTypeInfoDecl;
743
744 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
745 RecordDecl *MSVCGuidDecl;
746
747 /// \brief Caches identifiers/selectors for NSFoundation APIs.
748 std::unique_ptr<NSAPI> NSAPIObj;
749
750 /// \brief The declaration of the Objective-C NSNumber class.
751 ObjCInterfaceDecl *NSNumberDecl;
752
753 /// \brief The declaration of the Objective-C NSValue class.
754 ObjCInterfaceDecl *NSValueDecl;
755
756 /// \brief Pointer to NSNumber type (NSNumber *).
757 QualType NSNumberPointer;
758
759 /// \brief Pointer to NSValue type (NSValue *).
760 QualType NSValuePointer;
761
762 /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
763 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
764
765 /// \brief The declaration of the Objective-C NSString class.
766 ObjCInterfaceDecl *NSStringDecl;
767
768 /// \brief Pointer to NSString type (NSString *).
769 QualType NSStringPointer;
770
771 /// \brief The declaration of the stringWithUTF8String: method.
772 ObjCMethodDecl *StringWithUTF8StringMethod;
773
774 /// \brief The declaration of the valueWithBytes:objCType: method.
775 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
776
777 /// \brief The declaration of the Objective-C NSArray class.
778 ObjCInterfaceDecl *NSArrayDecl;
779
780 /// \brief The declaration of the arrayWithObjects:count: method.
781 ObjCMethodDecl *ArrayWithObjectsMethod;
782
783 /// \brief The declaration of the Objective-C NSDictionary class.
784 ObjCInterfaceDecl *NSDictionaryDecl;
785
786 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
787 ObjCMethodDecl *DictionaryWithObjectsMethod;
788
789 /// \brief id<NSCopying> type.
790 QualType QIDNSCopying;
791
792 /// \brief will hold 'respondsToSelector:'
793 Selector RespondsToSelectorSel;
794
795 /// A flag to remember whether the implicit forms of operator new and delete
796 /// have been declared.
797 bool GlobalNewDeleteDeclared;
798
799 /// A flag to indicate that we're in a context that permits abstract
800 /// references to fields. This is really a
801 bool AllowAbstractFieldReference;
802
803 /// \brief Describes how the expressions currently being parsed are
804 /// evaluated at run-time, if at all.
805 enum ExpressionEvaluationContext {
806 /// \brief The current expression and its subexpressions occur within an
807 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
808 /// \c sizeof, where the type of the expression may be significant but
809 /// no code will be generated to evaluate the value of the expression at
810 /// run time.
811 Unevaluated,
812
813 /// \brief The current expression occurs within a braced-init-list within
814 /// an unevaluated operand. This is mostly like a regular unevaluated
815 /// context, except that we still instantiate constexpr functions that are
816 /// referenced here so that we can perform narrowing checks correctly.
817 UnevaluatedList,
818
819 /// \brief The current expression occurs within a discarded statement.
820 /// This behaves largely similarly to an unevaluated operand in preventing
821 /// definitions from being required, but not in other ways.
822 DiscardedStatement,
823
824 /// \brief The current expression occurs within an unevaluated
825 /// operand that unconditionally permits abstract references to
826 /// fields, such as a SIZE operator in MS-style inline assembly.
827 UnevaluatedAbstract,
828
829 /// \brief The current context is "potentially evaluated" in C++11 terms,
830 /// but the expression is evaluated at compile-time (like the values of
831 /// cases in a switch statement).
832 ConstantEvaluated,
833
834 /// \brief The current expression is potentially evaluated at run time,
835 /// which means that code may be generated to evaluate the value of the
836 /// expression at run time.
837 PotentiallyEvaluated,
838
839 /// \brief The current expression is potentially evaluated, but any
840 /// declarations referenced inside that expression are only used if
841 /// in fact the current expression is used.
842 ///
843 /// This value is used when parsing default function arguments, for which
844 /// we would like to provide diagnostics (e.g., passing non-POD arguments
845 /// through varargs) but do not want to mark declarations as "referenced"
846 /// until the default argument is used.
847 PotentiallyEvaluatedIfUsed
848 };
849
850 /// \brief Data structure used to record current or nested
851 /// expression evaluation contexts.
852 struct ExpressionEvaluationContextRecord {
853 /// \brief The expression evaluation context.
854 ExpressionEvaluationContext Context;
855
856 /// \brief Whether the enclosing context needed a cleanup.
857 CleanupInfo ParentCleanup;
858
859 /// \brief Whether we are in a decltype expression.
860 bool IsDecltype;
861
862 /// \brief The number of active cleanup objects when we entered
863 /// this expression evaluation context.
864 unsigned NumCleanupObjects;
865
866 /// \brief The number of typos encountered during this expression evaluation
867 /// context (i.e. the number of TypoExprs created).
868 unsigned NumTypos;
869
870 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
871
872 /// \brief The lambdas that are present within this context, if it
873 /// is indeed an unevaluated context.
874 SmallVector<LambdaExpr *, 2> Lambdas;
875
876 /// \brief The declaration that provides context for lambda expressions
877 /// and block literals if the normal declaration context does not
878 /// suffice, e.g., in a default function argument.
879 Decl *ManglingContextDecl;
880
881 /// \brief The context information used to mangle lambda expressions
882 /// and block literals within this context.
883 ///
884 /// This mangling information is allocated lazily, since most contexts
885 /// do not have lambda expressions or block literals.
886 std::unique_ptr<MangleNumberingContext> MangleNumbering;
887
888 /// \brief If we are processing a decltype type, a set of call expressions
889 /// for which we have deferred checking the completeness of the return type.
890 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
891
892 /// \brief If we are processing a decltype type, a set of temporary binding
893 /// expressions for which we have deferred checking the destructor.
894 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
895
896 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
897 unsigned NumCleanupObjects,
898 CleanupInfo ParentCleanup,
899 Decl *ManglingContextDecl,
900 bool IsDecltype)
901 : Context(Context), ParentCleanup(ParentCleanup),
902 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
903 NumTypos(0),
904 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
905
906 /// \brief Retrieve the mangling numbering context, used to consistently
907 /// number constructs like lambdas for mangling.
908 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
909
910 bool isUnevaluated() const {
911 return Context == Unevaluated || Context == UnevaluatedAbstract ||
912 Context == UnevaluatedList;
913 }
914 };
915
916 /// A stack of expression evaluation contexts.
917 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
918
919 /// \brief Compute the mangling number context for a lambda expression or
920 /// block literal.
921 ///
922 /// \param DC - The DeclContext containing the lambda expression or
923 /// block literal.
924 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
925 /// associated with the context, if relevant.
926 MangleNumberingContext *getCurrentMangleNumberContext(
927 const DeclContext *DC,
928 Decl *&ManglingContextDecl);
929
930
931 /// SpecialMemberOverloadResult - The overloading result for a special member
932 /// function.
933 ///
934 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
935 /// integer are used to determine whether overload resolution succeeded.
936 class SpecialMemberOverloadResult {
937 public:
938 enum Kind {
939 NoMemberOrDeleted,
940 Ambiguous,
941 Success
942 };
943
944 private:
945 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
946
947 public:
948 SpecialMemberOverloadResult() : Pair() {}
949 SpecialMemberOverloadResult(CXXMethodDecl *MD)
950 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
951
952 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
953 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
954
955 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
956 void setKind(Kind K) { Pair.setInt(K); }
957 };
958
959 class SpecialMemberOverloadResultEntry
960 : public llvm::FastFoldingSetNode,
961 public SpecialMemberOverloadResult {
962 public:
963 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
964 : FastFoldingSetNode(ID)
965 {}
966 };
967
968 /// \brief A cache of special member function overload resolution results
969 /// for C++ records.
970 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
971
972 /// \brief A cache of the flags available in enumerations with the flag_bits
973 /// attribute.
974 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
975
976 /// \brief The kind of translation unit we are processing.
977 ///
978 /// When we're processing a complete translation unit, Sema will perform
979 /// end-of-translation-unit semantic tasks (such as creating
980 /// initializers for tentative definitions in C) once parsing has
981 /// completed. Modules and precompiled headers perform different kinds of
982 /// checks.
983 TranslationUnitKind TUKind;
984
985 llvm::BumpPtrAllocator BumpAlloc;
986
987 /// \brief The number of SFINAE diagnostics that have been trapped.
988 unsigned NumSFINAEErrors;
989
990 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
991 UnparsedDefaultArgInstantiationsMap;
992
993 /// \brief A mapping from parameters with unparsed default arguments to the
994 /// set of instantiations of each parameter.
995 ///
996 /// This mapping is a temporary data structure used when parsing
997 /// nested class templates or nested classes of class templates,
998 /// where we might end up instantiating an inner class before the
999 /// default arguments of its methods have been parsed.
1000 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1001
1002 // Contains the locations of the beginning of unparsed default
1003 // argument locations.
1004 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1005
1006 /// UndefinedInternals - all the used, undefined objects which require a
1007 /// definition in this translation unit.
1008 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1009
1010 /// Obtain a sorted list of functions that are undefined but ODR-used.
1011 void getUndefinedButUsed(
1012 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1013
1014 /// Retrieves list of suspicious delete-expressions that will be checked at
1015 /// the end of translation unit.
1016 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1017 getMismatchingDeleteExpressions() const;
1018
1019 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1020 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1021
1022 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1023 /// We need to maintain a list, since selectors can have differing signatures
1024 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1025 /// of selectors are "overloaded").
1026 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1027 /// methods inside categories with a particular selector.
1028 GlobalMethodPool MethodPool;
1029
1030 /// Method selectors used in a \@selector expression. Used for implementation
1031 /// of -Wselector.
1032 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1033
1034 /// Kinds of C++ special members.
1035 enum CXXSpecialMember {
1036 CXXDefaultConstructor,
1037 CXXCopyConstructor,
1038 CXXMoveConstructor,
1039 CXXCopyAssignment,
1040 CXXMoveAssignment,
1041 CXXDestructor,
1042 CXXInvalid
1043 };
1044
1045 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1046
1047 /// The C++ special members which we are currently in the process of
1048 /// declaring. If this process recursively triggers the declaration of the
1049 /// same special member, we should act as if it is not yet declared.
1050 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1051
1052 void ReadMethodPool(Selector Sel);
1053 void updateOutOfDateSelector(Selector Sel);
1054
1055 /// Private Helper predicate to check for 'self'.
1056 bool isSelfExpr(Expr *RExpr);
1057 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1058
1059 /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1060 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1061 /// should not be used elsewhere.
1062 void EmitCurrentDiagnostic(unsigned DiagID);
1063
1064 /// Records and restores the FP_CONTRACT state on entry/exit of compound
1065 /// statements.
1066 class FPContractStateRAII {
1067 public:
1068 FPContractStateRAII(Sema& S)
1069 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
1070 ~FPContractStateRAII() {
1071 S.FPFeatures.fp_contract = OldFPContractState;
1072 }
1073 private:
1074 Sema& S;
1075 bool OldFPContractState : 1;
1076 };
1077
1078 void addImplicitTypedef(StringRef Name, QualType T);
1079
1080public:
1081 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1082 TranslationUnitKind TUKind = TU_Complete,
1083 CodeCompleteConsumer *CompletionConsumer = nullptr);
1084 ~Sema();
1085
1086 /// \brief Perform initialization that occurs after the parser has been
1087 /// initialized but before it parses anything.
1088 void Initialize();
1089
1090 const LangOptions &getLangOpts() const { return LangOpts; }
1091 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1092 FPOptions &getFPOptions() { return FPFeatures; }
1093
1094 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1095 SourceManager &getSourceManager() const { return SourceMgr; }
1096 Preprocessor &getPreprocessor() const { return PP; }
1097 ASTContext &getASTContext() const { return Context; }
1098 ASTConsumer &getASTConsumer() const { return Consumer; }
1099 ASTMutationListener *getASTMutationListener() const;
1100 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1101
1102 ///\brief Registers an external source. If an external source already exists,
1103 /// creates a multiplex external source and appends to it.
1104 ///
1105 ///\param[in] E - A non-null external sema source.
1106 ///
1107 void addExternalSource(ExternalSemaSource *E);
1108
1109 void PrintStats() const;
1110
1111 /// \brief Helper class that creates diagnostics with optional
1112 /// template instantiation stacks.
1113 ///
1114 /// This class provides a wrapper around the basic DiagnosticBuilder
1115 /// class that emits diagnostics. SemaDiagnosticBuilder is
1116 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1117 /// does) and, if the diagnostic comes from inside a template
1118 /// instantiation, printing the template instantiation stack as
1119 /// well.
1120 class SemaDiagnosticBuilder : public DiagnosticBuilder {
1121 Sema &SemaRef;
1122 unsigned DiagID;
1123
1124 public:
1125 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1126 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1127
1128 // This is a cunning lie. DiagnosticBuilder actually performs move
1129 // construction in its copy constructor (but due to varied uses, it's not
1130 // possible to conveniently express this as actual move construction). So
1131 // the default copy ctor here is fine, because the base class disables the
1132 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1133 // in that case anwyay.
1134 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1135
1136 ~SemaDiagnosticBuilder() {
1137 // If we aren't active, there is nothing to do.
1138 if (!isActive()) return;
1139
1140 // Otherwise, we need to emit the diagnostic. First flush the underlying
1141 // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1142 // won't emit the diagnostic in its own destructor.
1143 //
1144 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1145 // do its own needless checks to see if the diagnostic needs to be
1146 // emitted. However, because we take care to ensure that the builder
1147 // objects never escape, a sufficiently smart compiler will be able to
1148 // eliminate that code.
1149 FlushCounts();
1150 Clear();
1151
1152 // Dispatch to Sema to emit the diagnostic.
1153 SemaRef.EmitCurrentDiagnostic(DiagID);
1154 }
1155
1156 /// Teach operator<< to produce an object of the correct type.
1157 template<typename T>
1158 friend const SemaDiagnosticBuilder &operator<<(
1159 const SemaDiagnosticBuilder &Diag, const T &Value) {
1160 const DiagnosticBuilder &BaseDiag = Diag;
1161 BaseDiag << Value;
1162 return Diag;
1163 }
1164 };
1165
1166 /// \brief Emit a diagnostic.
1167 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1168 DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1169 return SemaDiagnosticBuilder(DB, *this, DiagID);
1170 }
1171
1172 /// \brief Emit a partial diagnostic.
1173 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1174
1175 /// \brief Build a partial diagnostic.
1176 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1177
1178 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1179
1180 /// \brief Get a string to suggest for zero-initialization of a type.
1181 std::string
1182 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1183 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1184
1185 /// \brief Calls \c Lexer::getLocForEndOfToken()
1186 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1187
1188 /// \brief Retrieve the module loader associated with the preprocessor.
1189 ModuleLoader &getModuleLoader() const;
1190
1191 void emitAndClearUnusedLocalTypedefWarnings();
1192
1193 void ActOnEndOfTranslationUnit();
1194
1195 void CheckDelegatingCtorCycles();
1196
1197 Scope *getScopeForContext(DeclContext *Ctx);
1198
1199 void PushFunctionScope();
1200 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1201 sema::LambdaScopeInfo *PushLambdaScope();
1202
1203 /// \brief This is used to inform Sema what the current TemplateParameterDepth
1204 /// is during Parsing. Currently it is used to pass on the depth
1205 /// when parsing generic lambda 'auto' parameters.
1206 void RecordParsingTemplateParameterDepth(unsigned Depth);
1207
1208 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1209 RecordDecl *RD,
1210 CapturedRegionKind K);
1211 void
1212 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1213 const Decl *D = nullptr,
1214 const BlockExpr *blkExpr = nullptr);
1215
1216 sema::FunctionScopeInfo *getCurFunction() const {
1217 return FunctionScopes.back();
1218 }
1219
1220 sema::FunctionScopeInfo *getEnclosingFunction() const {
1221 if (FunctionScopes.empty())
1222 return nullptr;
1223
1224 for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1225 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1226 continue;
1227 return FunctionScopes[e];
1228 }
1229 return nullptr;
1230 }
1231
1232 template <typename ExprT>
1233 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1234 if (!isUnevaluatedContext())
1235 getCurFunction()->recordUseOfWeak(E, IsRead);
1236 }
1237
1238 void PushCompoundScope();
1239 void PopCompoundScope();
1240
1241 sema::CompoundScopeInfo &getCurCompoundScope() const;
1242
1243 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1244
1245 /// \brief Retrieve the current block, if any.
1246 sema::BlockScopeInfo *getCurBlock();
1247
1248 /// Retrieve the current lambda scope info, if any.
1249 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1250 /// lambda scope info ignoring all inner capturing scopes that are not
1251 /// lambda scopes.
1252 sema::LambdaScopeInfo *
1253 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1254
1255 /// \brief Retrieve the current generic lambda info, if any.
1256 sema::LambdaScopeInfo *getCurGenericLambda();
1257
1258 /// \brief Retrieve the current captured region, if any.
1259 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1260
1261 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1262 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1263
1264 void ActOnComment(SourceRange Comment);
1265
1266 //===--------------------------------------------------------------------===//
1267 // Type Analysis / Processing: SemaType.cpp.
1268 //
1269
1270 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1271 const DeclSpec *DS = nullptr);
1272 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1273 const DeclSpec *DS = nullptr);
1274 QualType BuildPointerType(QualType T,
1275 SourceLocation Loc, DeclarationName Entity);
1276 QualType BuildReferenceType(QualType T, bool LValueRef,
1277 SourceLocation Loc, DeclarationName Entity);
1278 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1279 Expr *ArraySize, unsigned Quals,
1280 SourceRange Brackets, DeclarationName Entity);
1281 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1282 SourceLocation AttrLoc);
1283
1284 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1285
1286 /// \brief Build a function type.
1287 ///
1288 /// This routine checks the function type according to C++ rules and
1289 /// under the assumption that the result type and parameter types have
1290 /// just been instantiated from a template. It therefore duplicates
1291 /// some of the behavior of GetTypeForDeclarator, but in a much
1292 /// simpler form that is only suitable for this narrow use case.
1293 ///
1294 /// \param T The return type of the function.
1295 ///
1296 /// \param ParamTypes The parameter types of the function. This array
1297 /// will be modified to account for adjustments to the types of the
1298 /// function parameters.
1299 ///
1300 /// \param Loc The location of the entity whose type involves this
1301 /// function type or, if there is no such entity, the location of the
1302 /// type that will have function type.
1303 ///
1304 /// \param Entity The name of the entity that involves the function
1305 /// type, if known.
1306 ///
1307 /// \param EPI Extra information about the function type. Usually this will
1308 /// be taken from an existing function with the same prototype.
1309 ///
1310 /// \returns A suitable function type, if there are no errors. The
1311 /// unqualified type will always be a FunctionProtoType.
1312 /// Otherwise, returns a NULL type.
1313 QualType BuildFunctionType(QualType T,
1314 MutableArrayRef<QualType> ParamTypes,
1315 SourceLocation Loc, DeclarationName Entity,
1316 const FunctionProtoType::ExtProtoInfo &EPI);
1317
1318 QualType BuildMemberPointerType(QualType T, QualType Class,
1319 SourceLocation Loc,
1320 DeclarationName Entity);
1321 QualType BuildBlockPointerType(QualType T,
1322 SourceLocation Loc, DeclarationName Entity);
1323 QualType BuildParenType(QualType T);
1324 QualType BuildAtomicType(QualType T, SourceLocation Loc);
1325 QualType BuildReadPipeType(QualType T,
1326 SourceLocation Loc);
1327 QualType BuildWritePipeType(QualType T,
1328 SourceLocation Loc);
1329
1330 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1331 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1332 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1333 TypeSourceInfo *ReturnTypeInfo);
1334
1335 /// \brief Package the given type and TSI into a ParsedType.
1336 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1337 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1338 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1339 static QualType GetTypeFromParser(ParsedType Ty,
1340 TypeSourceInfo **TInfo = nullptr);
1341 CanThrowResult canThrow(const Expr *E);
1342 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1343 const FunctionProtoType *FPT);
1344 void UpdateExceptionSpec(FunctionDecl *FD,
1345 const FunctionProtoType::ExceptionSpecInfo &ESI);
1346 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1347 bool CheckDistantExceptionSpec(QualType T);
1348 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1349 bool CheckEquivalentExceptionSpec(
1350 const FunctionProtoType *Old, SourceLocation OldLoc,
1351 const FunctionProtoType *New, SourceLocation NewLoc);
1352 bool CheckEquivalentExceptionSpec(
1353 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1354 const FunctionProtoType *Old, SourceLocation OldLoc,
1355 const FunctionProtoType *New, SourceLocation NewLoc);
1356 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1357 const PartialDiagnostic &NestedDiagID,
1358 const PartialDiagnostic &NoteID,
1359 const FunctionProtoType *Superset,
1360 SourceLocation SuperLoc,
1361 const FunctionProtoType *Subset,
1362 SourceLocation SubLoc);
1363 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1364 const PartialDiagnostic &NoteID,
1365 const FunctionProtoType *Target,
1366 SourceLocation TargetLoc,
1367 const FunctionProtoType *Source,
1368 SourceLocation SourceLoc);
1369
1370 TypeResult ActOnTypeName(Scope *S, Declarator &D);
1371
1372 /// \brief The parser has parsed the context-sensitive type 'instancetype'
1373 /// in an Objective-C message declaration. Return the appropriate type.
1374 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1375
1376 /// \brief Abstract class used to diagnose incomplete types.
1377 struct TypeDiagnoser {
1378 TypeDiagnoser() {}
1379
1380 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1381 virtual ~TypeDiagnoser() {}
1382 };
1383
1384 static int getPrintable(int I) { return I; }
1385 static unsigned getPrintable(unsigned I) { return I; }
1386 static bool getPrintable(bool B) { return B; }
1387 static const char * getPrintable(const char *S) { return S; }
1388 static StringRef getPrintable(StringRef S) { return S; }
1389 static const std::string &getPrintable(const std::string &S) { return S; }
1390 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1391 return II;
1392 }
1393 static DeclarationName getPrintable(DeclarationName N) { return N; }
1394 static QualType getPrintable(QualType T) { return T; }
1395 static SourceRange getPrintable(SourceRange R) { return R; }
1396 static SourceRange getPrintable(SourceLocation L) { return L; }
1397 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1398 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1399
1400 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1401 unsigned DiagID;
1402 std::tuple<const Ts &...> Args;
1403
1404 template <std::size_t... Is>
1405 void emit(const SemaDiagnosticBuilder &DB,
1406 llvm::index_sequence<Is...>) const {
1407 // Apply all tuple elements to the builder in order.
1408 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1409 (void)Dummy;
1410 }
1411
1412 public:
1413 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1414 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1415 assert(DiagID != 0 && "no diagnostic for type diagnoser")((DiagID != 0 && "no diagnostic for type diagnoser") ?
static_cast<void> (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 1415, __PRETTY_FUNCTION__))
;
1416 }
1417
1418 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1419 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1420 emit(DB, llvm::index_sequence_for<Ts...>());
1421 DB << T;
1422 }
1423 };
1424
1425private:
1426 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1427 TypeDiagnoser *Diagnoser);
1428
1429 struct ModuleScope {
1430 clang::Module *Module;
1431 VisibleModuleSet OuterVisibleModules;
1432 };
1433 /// The modules we're currently parsing.
1434 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1435
1436 VisibleModuleSet VisibleModules;
1437
1438 Module *CachedFakeTopLevelModule;
1439
1440public:
1441 /// \brief Get the module owning an entity.
1442 Module *getOwningModule(Decl *Entity);
1443
1444 /// \brief Make a merged definition of an existing hidden definition \p ND
1445 /// visible at the specified location.
1446 void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1447
1448 bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1449
1450 /// Determine whether a declaration is visible to name lookup.
1451 bool isVisible(const NamedDecl *D) {
1452 return !D->isHidden() || isVisibleSlow(D);
1453 }
1454
1455 /// Determine whether any declaration of an entity is visible.
1456 bool
1457 hasVisibleDeclaration(const NamedDecl *D,
1458 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1459 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1460 }
1461 bool hasVisibleDeclarationSlow(const NamedDecl *D,
1462 llvm::SmallVectorImpl<Module *> *Modules);
1463
1464 bool hasVisibleMergedDefinition(NamedDecl *Def);
1465
1466 /// Determine if \p D has a visible definition. If not, suggest a declaration
1467 /// that should be made visible to expose the definition.
1468 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1469 bool OnlyNeedComplete = false);
1470 bool hasVisibleDefinition(const NamedDecl *D) {
1471 NamedDecl *Hidden;
1472 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1473 }
1474
1475 /// Determine if the template parameter \p D has a visible default argument.
1476 bool
1477 hasVisibleDefaultArgument(const NamedDecl *D,
1478 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1479
1480 /// Determine if there is a visible declaration of \p D that is a member
1481 /// specialization declaration (as opposed to an instantiated declaration).
1482 bool hasVisibleMemberSpecialization(
1483 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1484
1485 /// Determine if \p A and \p B are equivalent internal linkage declarations
1486 /// from different modules, and thus an ambiguity error can be downgraded to
1487 /// an extension warning.
1488 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1489 const NamedDecl *B);
1490 void diagnoseEquivalentInternalLinkageDeclarations(
1491 SourceLocation Loc, const NamedDecl *D,
1492 ArrayRef<const NamedDecl *> Equiv);
1493
1494 bool isCompleteType(SourceLocation Loc, QualType T) {
1495 return !RequireCompleteTypeImpl(Loc, T, nullptr);
1496 }
1497 bool RequireCompleteType(SourceLocation Loc, QualType T,
1498 TypeDiagnoser &Diagnoser);
1499 bool RequireCompleteType(SourceLocation Loc, QualType T,
1500 unsigned DiagID);
1501
1502 template <typename... Ts>
1503 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1504 const Ts &...Args) {
1505 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1506 return RequireCompleteType(Loc, T, Diagnoser);
1507 }
1508
1509 void completeExprArrayBound(Expr *E);
1510 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1511 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1512
1513 template <typename... Ts>
1514 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1515 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1516 return RequireCompleteExprType(E, Diagnoser);
1517 }
1518
1519 bool RequireLiteralType(SourceLocation Loc, QualType T,
1520 TypeDiagnoser &Diagnoser);
1521 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1522
1523 template <typename... Ts>
1524 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1525 const Ts &...Args) {
1526 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1527 return RequireLiteralType(Loc, T, Diagnoser);
1528 }
1529
1530 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1531 const CXXScopeSpec &SS, QualType T);
1532
1533 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1534 /// If AsUnevaluated is false, E is treated as though it were an evaluated
1535 /// context, such as when building a type for decltype(auto).
1536 QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1537 bool AsUnevaluated = true);
1538 QualType BuildUnaryTransformType(QualType BaseType,
1539 UnaryTransformType::UTTKind UKind,
1540 SourceLocation Loc);
1541
1542 //===--------------------------------------------------------------------===//
1543 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1544 //
1545
1546 struct SkipBodyInfo {
1547 SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1548 bool ShouldSkip;
1549 NamedDecl *Previous;
1550 };
1551
1552 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1553
1554 void DiagnoseUseOfUnimplementedSelectors();
1555
1556 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1557
1558 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1559 Scope *S, CXXScopeSpec *SS = nullptr,
1560 bool isClassName = false, bool HasTrailingDot = false,
1561 ParsedType ObjectType = nullptr,
1562 bool IsCtorOrDtorName = false,
1563 bool WantNontrivialTypeSourceInfo = false,
1564 bool IsClassTemplateDeductionContext = true,
1565 IdentifierInfo **CorrectedII = nullptr);
1566 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1567 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1568 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1569 SourceLocation IILoc,
1570 Scope *S,
1571 CXXScopeSpec *SS,
1572 ParsedType &SuggestedType,
1573 bool AllowClassTemplates = false);
1574
1575 /// Attempt to behave like MSVC in situations where lookup of an unqualified
1576 /// type name has failed in a dependent context. In these situations, we
1577 /// automatically form a DependentTypeName that will retry lookup in a related
1578 /// scope during instantiation.
1579 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1580 SourceLocation NameLoc,
1581 bool IsTemplateTypeArg);
1582
1583 /// \brief Describes the result of the name lookup and resolution performed
1584 /// by \c ClassifyName().
1585 enum NameClassificationKind {
1586 NC_Unknown,
1587 NC_Error,
1588 NC_Keyword,
1589 NC_Type,
1590 NC_Expression,
1591 NC_NestedNameSpecifier,
1592 NC_TypeTemplate,
1593 NC_VarTemplate,
1594 NC_FunctionTemplate
1595 };
1596
1597 class NameClassification {
1598 NameClassificationKind Kind;
1599 ExprResult Expr;
1600 TemplateName Template;
1601 ParsedType Type;
1602 const IdentifierInfo *Keyword;
1603
1604 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1605
1606 public:
1607 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1608
1609 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1610
1611 NameClassification(const IdentifierInfo *Keyword)
1612 : Kind(NC_Keyword), Keyword(Keyword) { }
1613
1614 static NameClassification Error() {
1615 return NameClassification(NC_Error);
1616 }
1617
1618 static NameClassification Unknown() {
1619 return NameClassification(NC_Unknown);
1620 }
1621
1622 static NameClassification NestedNameSpecifier() {
1623 return NameClassification(NC_NestedNameSpecifier);
1624 }
1625
1626 static NameClassification TypeTemplate(TemplateName Name) {
1627 NameClassification Result(NC_TypeTemplate);
1628 Result.Template = Name;
1629 return Result;
1630 }
1631
1632 static NameClassification VarTemplate(TemplateName Name) {
1633 NameClassification Result(NC_VarTemplate);
1634 Result.Template = Name;
1635 return Result;
1636 }
1637
1638 static NameClassification FunctionTemplate(TemplateName Name) {
1639 NameClassification Result(NC_FunctionTemplate);
1640 Result.Template = Name;
1641 return Result;
1642 }
1643
1644 NameClassificationKind getKind() const { return Kind; }
1645
1646 ParsedType getType() const {
1647 assert(Kind == NC_Type)((Kind == NC_Type) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Type", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 1647, __PRETTY_FUNCTION__))
;
1648 return Type;
1649 }
1650
1651 ExprResult getExpression() const {
1652 assert(Kind == NC_Expression)((Kind == NC_Expression) ? static_cast<void> (0) : __assert_fail
("Kind == NC_Expression", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 1652, __PRETTY_FUNCTION__))
;
1653 return Expr;
1654 }
1655
1656 TemplateName getTemplateName() const {
1657 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate) ? static_cast<void> (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 1658, __PRETTY_FUNCTION__))
1658 Kind == NC_VarTemplate)((Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind
== NC_VarTemplate) ? static_cast<void> (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 1658, __PRETTY_FUNCTION__))
;
1659 return Template;
1660 }
1661
1662 TemplateNameKind getTemplateNameKind() const {
1663 switch (Kind) {
1664 case NC_TypeTemplate:
1665 return TNK_Type_template;
1666 case NC_FunctionTemplate:
1667 return TNK_Function_template;
1668 case NC_VarTemplate:
1669 return TNK_Var_template;
1670 default:
1671 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 1671)
;
1672 }
1673 }
1674 };
1675
1676 /// \brief Perform name lookup on the given name, classifying it based on
1677 /// the results of name lookup and the following token.
1678 ///
1679 /// This routine is used by the parser to resolve identifiers and help direct
1680 /// parsing. When the identifier cannot be found, this routine will attempt
1681 /// to correct the typo and classify based on the resulting name.
1682 ///
1683 /// \param S The scope in which we're performing name lookup.
1684 ///
1685 /// \param SS The nested-name-specifier that precedes the name.
1686 ///
1687 /// \param Name The identifier. If typo correction finds an alternative name,
1688 /// this pointer parameter will be updated accordingly.
1689 ///
1690 /// \param NameLoc The location of the identifier.
1691 ///
1692 /// \param NextToken The token following the identifier. Used to help
1693 /// disambiguate the name.
1694 ///
1695 /// \param IsAddressOfOperand True if this name is the operand of a unary
1696 /// address of ('&') expression, assuming it is classified as an
1697 /// expression.
1698 ///
1699 /// \param CCC The correction callback, if typo correction is desired.
1700 NameClassification
1701 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1702 SourceLocation NameLoc, const Token &NextToken,
1703 bool IsAddressOfOperand,
1704 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1705
1706 /// Describes the detailed kind of a template name. Used in diagnostics.
1707 enum class TemplateNameKindForDiagnostics {
1708 ClassTemplate,
1709 FunctionTemplate,
1710 VarTemplate,
1711 AliasTemplate,
1712 TemplateTemplateParam,
1713 DependentTemplate
1714 };
1715 TemplateNameKindForDiagnostics
1716 getTemplateNameKindForDiagnostics(TemplateName Name);
1717
1718 Decl *ActOnDeclarator(Scope *S, Declarator &D);
1719
1720 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1721 MultiTemplateParamsArg TemplateParameterLists);
1722 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1723 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1724 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1725 DeclarationName Name,
1726 SourceLocation Loc);
1727 void
1728 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1729 SourceLocation FallbackLoc,
1730 SourceLocation ConstQualLoc = SourceLocation(),
1731 SourceLocation VolatileQualLoc = SourceLocation(),
1732 SourceLocation RestrictQualLoc = SourceLocation(),
1733 SourceLocation AtomicQualLoc = SourceLocation(),
1734 SourceLocation UnalignedQualLoc = SourceLocation());
1735
1736 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1737 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1738 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1739 void CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R);
1740 void CheckShadow(Scope *S, VarDecl *D);
1741
1742 /// Warn if 'E', which is an expression that is about to be modified, refers
1743 /// to a shadowing declaration.
1744 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1745
1746 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1747
1748private:
1749 /// Map of current shadowing declarations to shadowed declarations. Warn if
1750 /// it looks like the user is trying to modify the shadowing declaration.
1751 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1752
1753public:
1754 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1755 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1756 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1757 TypedefNameDecl *NewTD);
1758 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1759 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1760 TypeSourceInfo *TInfo,
1761 LookupResult &Previous);
1762 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1763 LookupResult &Previous, bool &Redeclaration);
1764 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1765 TypeSourceInfo *TInfo,
1766 LookupResult &Previous,
1767 MultiTemplateParamsArg TemplateParamLists,
1768 bool &AddToScope,
1769 ArrayRef<BindingDecl *> Bindings = None);
1770 NamedDecl *
1771 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1772 MultiTemplateParamsArg TemplateParamLists);
1773 // Returns true if the variable declaration is a redeclaration
1774 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1775 void CheckVariableDeclarationType(VarDecl *NewVD);
1776 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1777 Expr *Init);
1778 void CheckCompleteVariableDeclaration(VarDecl *VD);
1779 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1780 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1781
1782 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1783 TypeSourceInfo *TInfo,
1784 LookupResult &Previous,
1785 MultiTemplateParamsArg TemplateParamLists,
1786 bool &AddToScope);
1787 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1788
1789 bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1790 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1791
1792 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1793 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1794 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1795 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1796 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1797 // Returns true if the function declaration is a redeclaration
1798 bool CheckFunctionDeclaration(Scope *S,
1799 FunctionDecl *NewFD, LookupResult &Previous,
1800 bool IsMemberSpecialization);
1801 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1802 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1803 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1804 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1805 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1806 SourceLocation Loc,
1807 QualType T);
1808 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1809 SourceLocation NameLoc, IdentifierInfo *Name,
1810 QualType T, TypeSourceInfo *TSInfo,
1811 StorageClass SC);
1812 void ActOnParamDefaultArgument(Decl *param,
1813 SourceLocation EqualLoc,
1814 Expr *defarg);
1815 void ActOnParamUnparsedDefaultArgument(Decl *param,
1816 SourceLocation EqualLoc,
1817 SourceLocation ArgLoc);
1818 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1819 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1820 SourceLocation EqualLoc);
1821
1822 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1823 void ActOnUninitializedDecl(Decl *dcl);
1824 void ActOnInitializerError(Decl *Dcl);
1825 bool canInitializeWithParenthesizedList(QualType TargetType);
1826
1827 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1828 void ActOnCXXForRangeDecl(Decl *D);
1829 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1830 IdentifierInfo *Ident,
1831 ParsedAttributes &Attrs,
1832 SourceLocation AttrEnd);
1833 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1834 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1835 void FinalizeDeclaration(Decl *D);
1836 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1837 ArrayRef<Decl *> Group);
1838 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1839
1840 /// Should be called on all declarations that might have attached
1841 /// documentation comments.
1842 void ActOnDocumentableDecl(Decl *D);
1843 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1844
1845 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1846 SourceLocation LocAfterDecls);
1847 void CheckForFunctionRedefinition(
1848 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1849 SkipBodyInfo *SkipBody = nullptr);
1850 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1851 MultiTemplateParamsArg TemplateParamLists,
1852 SkipBodyInfo *SkipBody = nullptr);
1853 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1854 SkipBodyInfo *SkipBody = nullptr);
1855 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1856 bool isObjCMethodDecl(Decl *D) {
1857 return D && isa<ObjCMethodDecl>(D);
1858 }
1859
1860 /// \brief Determine whether we can delay parsing the body of a function or
1861 /// function template until it is used, assuming we don't care about emitting
1862 /// code for that function.
1863 ///
1864 /// This will be \c false if we may need the body of the function in the
1865 /// middle of parsing an expression (where it's impractical to switch to
1866 /// parsing a different function), for instance, if it's constexpr in C++11
1867 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1868 bool canDelayFunctionBody(const Declarator &D);
1869
1870 /// \brief Determine whether we can skip parsing the body of a function
1871 /// definition, assuming we don't care about analyzing its body or emitting
1872 /// code for that function.
1873 ///
1874 /// This will be \c false only if we may need the body of the function in
1875 /// order to parse the rest of the program (for instance, if it is
1876 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1877 bool canSkipFunctionBody(Decl *D);
1878
1879 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1880 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1881 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1882 Decl *ActOnSkippedFunctionBody(Decl *Decl);
1883 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1884
1885 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1886 /// attribute for which parsing is delayed.
1887 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1888
1889 /// \brief Diagnose any unused parameters in the given sequence of
1890 /// ParmVarDecl pointers.
1891 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1892
1893 /// \brief Diagnose whether the size of parameters or return value of a
1894 /// function or obj-c method definition is pass-by-value and larger than a
1895 /// specified threshold.
1896 void
1897 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1898 QualType ReturnTy, NamedDecl *D);
1899
1900 void DiagnoseInvalidJumps(Stmt *Body);
1901 Decl *ActOnFileScopeAsmDecl(Expr *expr,
1902 SourceLocation AsmLoc,
1903 SourceLocation RParenLoc);
1904
1905 /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1906 Decl *ActOnEmptyDeclaration(Scope *S,
1907 AttributeList *AttrList,
1908 SourceLocation SemiLoc);
1909
1910 enum class ModuleDeclKind {
1911 Module, ///< 'module X;'
1912 Partition, ///< 'module partition X;'
1913 Implementation, ///< 'module implementation X;'
1914 };
1915
1916 /// The parser has processed a module-declaration that begins the definition
1917 /// of a module interface or implementation.
1918 DeclGroupPtrTy ActOnModuleDecl(SourceLocation ModuleLoc, ModuleDeclKind MDK,
1919 ModuleIdPath Path);
1920
1921 /// \brief The parser has processed a module import declaration.
1922 ///
1923 /// \param AtLoc The location of the '@' symbol, if any.
1924 ///
1925 /// \param ImportLoc The location of the 'import' keyword.
1926 ///
1927 /// \param Path The module access path.
1928 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1929 ModuleIdPath Path);
1930
1931 /// \brief The parser has processed a module import translated from a
1932 /// #include or similar preprocessing directive.
1933 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1934 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1935
1936 /// \brief The parsed has entered a submodule.
1937 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1938 /// \brief The parser has left a submodule.
1939 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1940
1941 /// \brief Create an implicit import of the given module at the given
1942 /// source location, for error recovery, if possible.
1943 ///
1944 /// This routine is typically used when an entity found by name lookup
1945 /// is actually hidden within a module that we know about but the user
1946 /// has forgotten to import.
1947 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1948 Module *Mod);
1949
1950 /// Kinds of missing import. Note, the values of these enumerators correspond
1951 /// to %select values in diagnostics.
1952 enum class MissingImportKind {
1953 Declaration,
1954 Definition,
1955 DefaultArgument,
1956 ExplicitSpecialization,
1957 PartialSpecialization
1958 };
1959
1960 /// \brief Diagnose that the specified declaration needs to be visible but
1961 /// isn't, and suggest a module import that would resolve the problem.
1962 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1963 MissingImportKind MIK, bool Recover = true);
1964 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1965 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1966 MissingImportKind MIK, bool Recover);
1967
1968 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
1969 SourceLocation LBraceLoc);
1970 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
1971 SourceLocation RBraceLoc);
1972
1973 /// \brief We've found a use of a templated declaration that would trigger an
1974 /// implicit instantiation. Check that any relevant explicit specializations
1975 /// and partial specializations are visible, and diagnose if not.
1976 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1977
1978 /// \brief We've found a use of a template specialization that would select a
1979 /// partial specialization. Check that the partial specialization is visible,
1980 /// and diagnose if not.
1981 void checkPartialSpecializationVisibility(SourceLocation Loc,
1982 NamedDecl *Spec);
1983
1984 /// \brief Retrieve a suitable printing policy.
1985 PrintingPolicy getPrintingPolicy() const {
1986 return getPrintingPolicy(Context, PP);
1987 }
1988
1989 /// \brief Retrieve a suitable printing policy.
1990 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1991 const Preprocessor &PP);
1992
1993 /// Scope actions.
1994 void ActOnPopScope(SourceLocation Loc, Scope *S);
1995 void ActOnTranslationUnitScope(Scope *S);
1996
1997 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
1998 RecordDecl *&AnonRecord);
1999 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2000 MultiTemplateParamsArg TemplateParams,
2001 bool IsExplicitInstantiation,
2002 RecordDecl *&AnonRecord);
2003
2004 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2005 AccessSpecifier AS,
2006 RecordDecl *Record,
2007 const PrintingPolicy &Policy);
2008
2009 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2010 RecordDecl *Record);
2011
2012 /// Common ways to introduce type names without a tag for use in diagnostics.
2013 /// Keep in sync with err_tag_reference_non_tag.
2014 enum NonTagKind {
2015 NTK_NonStruct,
2016 NTK_NonClass,
2017 NTK_NonUnion,
2018 NTK_NonEnum,
2019 NTK_Typedef,
2020 NTK_TypeAlias,
2021 NTK_Template,
2022 NTK_TypeAliasTemplate,
2023 NTK_TemplateTemplateArgument,
2024 };
2025
2026 /// Given a non-tag type declaration, returns an enum useful for indicating
2027 /// what kind of non-tag type this is.
2028 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2029
2030 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2031 TagTypeKind NewTag, bool isDefinition,
2032 SourceLocation NewTagLoc,
2033 const IdentifierInfo *Name);
2034
2035 enum TagUseKind {
2036 TUK_Reference, // Reference to a tag: 'struct foo *X;'
2037 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
2038 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
2039 TUK_Friend // Friend declaration: 'friend struct foo;'
2040 };
2041
2042 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2043 SourceLocation KWLoc, CXXScopeSpec &SS,
2044 IdentifierInfo *Name, SourceLocation NameLoc,
2045 AttributeList *Attr, AccessSpecifier AS,
2046 SourceLocation ModulePrivateLoc,
2047 MultiTemplateParamsArg TemplateParameterLists,
2048 bool &OwnedDecl, bool &IsDependent,
2049 SourceLocation ScopedEnumKWLoc,
2050 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2051 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2052
2053 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2054 unsigned TagSpec, SourceLocation TagLoc,
2055 CXXScopeSpec &SS,
2056 IdentifierInfo *Name, SourceLocation NameLoc,
2057 AttributeList *Attr,
2058 MultiTemplateParamsArg TempParamLists);
2059
2060 TypeResult ActOnDependentTag(Scope *S,
2061 unsigned TagSpec,
2062 TagUseKind TUK,
2063 const CXXScopeSpec &SS,
2064 IdentifierInfo *Name,
2065 SourceLocation TagLoc,
2066 SourceLocation NameLoc);
2067
2068 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2069 IdentifierInfo *ClassName,
2070 SmallVectorImpl<Decl *> &Decls);
2071 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2072 Declarator &D, Expr *BitfieldWidth);
2073
2074 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2075 Declarator &D, Expr *BitfieldWidth,
2076 InClassInitStyle InitStyle,
2077 AccessSpecifier AS);
2078 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2079 SourceLocation DeclStart,
2080 Declarator &D, Expr *BitfieldWidth,
2081 InClassInitStyle InitStyle,
2082 AccessSpecifier AS,
2083 AttributeList *MSPropertyAttr);
2084
2085 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2086 TypeSourceInfo *TInfo,
2087 RecordDecl *Record, SourceLocation Loc,
2088 bool Mutable, Expr *BitfieldWidth,
2089 InClassInitStyle InitStyle,
2090 SourceLocation TSSL,
2091 AccessSpecifier AS, NamedDecl *PrevDecl,
2092 Declarator *D = nullptr);
2093
2094 bool CheckNontrivialField(FieldDecl *FD);
2095 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2096 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2097 bool Diagnose = false);
2098 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2099 void ActOnLastBitfield(SourceLocation DeclStart,
2100 SmallVectorImpl<Decl *> &AllIvarDecls);
2101 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2102 Declarator &D, Expr *BitfieldWidth,
2103 tok::ObjCKeywordKind visibility);
2104
2105 // This is used for both record definitions and ObjC interface declarations.
2106 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2107 ArrayRef<Decl *> Fields,
2108 SourceLocation LBrac, SourceLocation RBrac,
2109 AttributeList *AttrList);
2110
2111 /// ActOnTagStartDefinition - Invoked when we have entered the
2112 /// scope of a tag's definition (e.g., for an enumeration, class,
2113 /// struct, or union).
2114 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2115
2116 typedef void *SkippedDefinitionContext;
2117
2118 /// \brief Invoked when we enter a tag definition that we're skipping.
2119 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2120
2121 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2122
2123 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2124 /// C++ record definition's base-specifiers clause and are starting its
2125 /// member declarations.
2126 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2127 SourceLocation FinalLoc,
2128 bool IsFinalSpelledSealed,
2129 SourceLocation LBraceLoc);
2130
2131 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2132 /// the definition of a tag (enumeration, class, struct, or union).
2133 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2134 SourceRange BraceRange);
2135
2136 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2137
2138 void ActOnObjCContainerFinishDefinition();
2139
2140 /// \brief Invoked when we must temporarily exit the objective-c container
2141 /// scope for parsing/looking-up C constructs.
2142 ///
2143 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2144 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2145 void ActOnObjCReenterContainerContext(DeclContext *DC);
2146
2147 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2148 /// error parsing the definition of a tag.
2149 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2150
2151 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2152 EnumConstantDecl *LastEnumConst,
2153 SourceLocation IdLoc,
2154 IdentifierInfo *Id,
2155 Expr *val);
2156 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2157 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2158 QualType EnumUnderlyingTy,
2159 bool EnumUnderlyingIsImplicit,
2160 const EnumDecl *Prev);
2161
2162 /// Determine whether the body of an anonymous enumeration should be skipped.
2163 /// \param II The name of the first enumerator.
2164 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2165 SourceLocation IILoc);
2166
2167 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2168 SourceLocation IdLoc, IdentifierInfo *Id,
2169 AttributeList *Attrs,
2170 SourceLocation EqualLoc, Expr *Val);
2171 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2172 Decl *EnumDecl,
2173 ArrayRef<Decl *> Elements,
2174 Scope *S, AttributeList *Attr);
2175
2176 DeclContext *getContainingDC(DeclContext *DC);
2177
2178 /// Set the current declaration context until it gets popped.
2179 void PushDeclContext(Scope *S, DeclContext *DC);
2180 void PopDeclContext();
2181
2182 /// EnterDeclaratorContext - Used when we must lookup names in the context
2183 /// of a declarator's nested name specifier.
2184 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2185 void ExitDeclaratorContext(Scope *S);
2186
2187 /// Push the parameters of D, which must be a function, into scope.
2188 void ActOnReenterFunctionContext(Scope* S, Decl* D);
2189 void ActOnExitFunctionContext();
2190
2191 DeclContext *getFunctionLevelDeclContext();
2192
2193 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2194 /// to the function decl for the function being parsed. If we're currently
2195 /// in a 'block', this returns the containing context.
2196 FunctionDecl *getCurFunctionDecl();
2197
2198 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2199 /// the method decl for the method being parsed. If we're currently
2200 /// in a 'block', this returns the containing context.
2201 ObjCMethodDecl *getCurMethodDecl();
2202
2203 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2204 /// or C function we're in, otherwise return null. If we're currently
2205 /// in a 'block', this returns the containing context.
2206 NamedDecl *getCurFunctionOrMethodDecl();
2207
2208 /// Add this decl to the scope shadowed decl chains.
2209 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2210
2211 /// \brief Make the given externally-produced declaration visible at the
2212 /// top level scope.
2213 ///
2214 /// \param D The externally-produced declaration to push.
2215 ///
2216 /// \param Name The name of the externally-produced declaration.
2217 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2218
2219 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2220 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2221 /// true if 'D' belongs to the given declaration context.
2222 ///
2223 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2224 /// enclosing namespace set of the context, rather than contained
2225 /// directly within it.
2226 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2227 bool AllowInlineNamespace = false);
2228
2229 /// Finds the scope corresponding to the given decl context, if it
2230 /// happens to be an enclosing scope. Otherwise return NULL.
2231 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2232
2233 /// Subroutines of ActOnDeclarator().
2234 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2235 TypeSourceInfo *TInfo);
2236 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2237
2238 /// \brief Describes the kind of merge to perform for availability
2239 /// attributes (including "deprecated", "unavailable", and "availability").
2240 enum AvailabilityMergeKind {
2241 /// \brief Don't merge availability attributes at all.
2242 AMK_None,
2243 /// \brief Merge availability attributes for a redeclaration, which requires
2244 /// an exact match.
2245 AMK_Redeclaration,
2246 /// \brief Merge availability attributes for an override, which requires
2247 /// an exact match or a weakening of constraints.
2248 AMK_Override,
2249 /// \brief Merge availability attributes for an implementation of
2250 /// a protocol requirement.
2251 AMK_ProtocolImplementation,
2252 };
2253
2254 /// Attribute merging methods. Return true if a new attribute was added.
2255 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2256 IdentifierInfo *Platform,
2257 bool Implicit,
2258 VersionTuple Introduced,
2259 VersionTuple Deprecated,
2260 VersionTuple Obsoleted,
2261 bool IsUnavailable,
2262 StringRef Message,
2263 bool IsStrict, StringRef Replacement,
2264 AvailabilityMergeKind AMK,
2265 unsigned AttrSpellingListIndex);
2266 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2267 TypeVisibilityAttr::VisibilityType Vis,
2268 unsigned AttrSpellingListIndex);
2269 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2270 VisibilityAttr::VisibilityType Vis,
2271 unsigned AttrSpellingListIndex);
2272 UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2273 unsigned AttrSpellingListIndex, StringRef Uuid);
2274 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2275 unsigned AttrSpellingListIndex);
2276 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2277 unsigned AttrSpellingListIndex);
2278 MSInheritanceAttr *
2279 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2280 unsigned AttrSpellingListIndex,
2281 MSInheritanceAttr::Spelling SemanticSpelling);
2282 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2283 IdentifierInfo *Format, int FormatIdx,
2284 int FirstArg, unsigned AttrSpellingListIndex);
2285 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2286 unsigned AttrSpellingListIndex);
2287 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2288 IdentifierInfo *Ident,
2289 unsigned AttrSpellingListIndex);
2290 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2291 unsigned AttrSpellingListIndex);
2292 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2293 unsigned AttrSpellingListIndex);
2294 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2295 IdentifierInfo *Ident,
2296 unsigned AttrSpellingListIndex);
2297 CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2298 unsigned AttrSpellingListIndex);
2299
2300 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2301 AvailabilityMergeKind AMK = AMK_Redeclaration);
2302 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2303 LookupResult &OldDecls);
2304 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2305 bool MergeTypeWithOld);
2306 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2307 Scope *S, bool MergeTypeWithOld);
2308 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2309 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2310 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2311 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2312 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2313 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2314
2315 // AssignmentAction - This is used by all the assignment diagnostic functions
2316 // to represent what is actually causing the operation
2317 enum AssignmentAction {
2318 AA_Assigning,
2319 AA_Passing,
2320 AA_Returning,
2321 AA_Converting,
2322 AA_Initializing,
2323 AA_Sending,
2324 AA_Casting,
2325 AA_Passing_CFAudited
2326 };
2327
2328 /// C++ Overloading.
2329 enum OverloadKind {
2330 /// This is a legitimate overload: the existing declarations are
2331 /// functions or function templates with different signatures.
2332 Ovl_Overload,
2333
2334 /// This is not an overload because the signature exactly matches
2335 /// an existing declaration.
2336 Ovl_Match,
2337
2338 /// This is not an overload because the lookup results contain a
2339 /// non-function.
2340 Ovl_NonFunction
2341 };
2342 OverloadKind CheckOverload(Scope *S,
2343 FunctionDecl *New,
2344 const LookupResult &OldDecls,
2345 NamedDecl *&OldDecl,
2346 bool IsForUsingDecl);
2347 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2348 bool ConsiderCudaAttrs = true);
2349
2350 /// \brief Checks availability of the function depending on the current
2351 /// function context.Inside an unavailable function,unavailability is ignored.
2352 ///
2353 /// \returns true if \p FD is unavailable and current context is inside
2354 /// an available function, false otherwise.
2355 bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2356
2357 ImplicitConversionSequence
2358 TryImplicitConversion(Expr *From, QualType ToType,
2359 bool SuppressUserConversions,
2360 bool AllowExplicit,
2361 bool InOverloadResolution,
2362 bool CStyle,
2363 bool AllowObjCWritebackConversion);
2364
2365 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2366 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2367 bool IsComplexPromotion(QualType FromType, QualType ToType);
2368 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2369 bool InOverloadResolution,
2370 QualType& ConvertedType, bool &IncompatibleObjC);
2371 bool isObjCPointerConversion(QualType FromType, QualType ToType,
2372 QualType& ConvertedType, bool &IncompatibleObjC);
2373 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2374 QualType &ConvertedType);
2375 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2376 QualType& ConvertedType);
2377 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2378 const FunctionProtoType *NewType,
2379 unsigned *ArgPos = nullptr);
2380 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2381 QualType FromType, QualType ToType);
2382
2383 void maybeExtendBlockObject(ExprResult &E);
2384 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2385 bool CheckPointerConversion(Expr *From, QualType ToType,
2386 CastKind &Kind,
2387 CXXCastPath& BasePath,
2388 bool IgnoreBaseAccess,
2389 bool Diagnose = true);
2390 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2391 bool InOverloadResolution,
2392 QualType &ConvertedType);
2393 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2394 CastKind &Kind,
2395 CXXCastPath &BasePath,
2396 bool IgnoreBaseAccess);
2397 bool IsQualificationConversion(QualType FromType, QualType ToType,
2398 bool CStyle, bool &ObjCLifetimeConversion);
2399 bool IsFunctionConversion(QualType FromType, QualType ToType,
2400 QualType &ResultTy);
2401 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2402 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2403
2404 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2405 const VarDecl *NRVOCandidate,
2406 QualType ResultType,
2407 Expr *Value,
2408 bool AllowNRVO = true);
2409
2410 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2411 ExprResult Init);
2412 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2413 SourceLocation EqualLoc,
2414 ExprResult Init,
2415 bool TopLevelOfInitList = false,
2416 bool AllowExplicit = false);
2417 ExprResult PerformObjectArgumentInitialization(Expr *From,
2418 NestedNameSpecifier *Qualifier,
2419 NamedDecl *FoundDecl,
2420 CXXMethodDecl *Method);
2421
2422 ExprResult PerformContextuallyConvertToBool(Expr *From);
2423 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2424
2425 /// Contexts in which a converted constant expression is required.
2426 enum CCEKind {
2427 CCEK_CaseValue, ///< Expression in a case label.
2428 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
2429 CCEK_TemplateArg, ///< Value of a non-type template parameter.
2430 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
2431 CCEK_ConstexprIf ///< Condition in a constexpr if statement.
2432 };
2433 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2434 llvm::APSInt &Value, CCEKind CCE);
2435 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2436 APValue &Value, CCEKind CCE);
2437
2438 /// \brief Abstract base class used to perform a contextual implicit
2439 /// conversion from an expression to any type passing a filter.
2440 class ContextualImplicitConverter {
2441 public:
2442 bool Suppress;
2443 bool SuppressConversion;
2444
2445 ContextualImplicitConverter(bool Suppress = false,
2446 bool SuppressConversion = false)
2447 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2448
2449 /// \brief Determine whether the specified type is a valid destination type
2450 /// for this conversion.
2451 virtual bool match(QualType T) = 0;
2452
2453 /// \brief Emits a diagnostic complaining that the expression does not have
2454 /// integral or enumeration type.
2455 virtual SemaDiagnosticBuilder
2456 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2457
2458 /// \brief Emits a diagnostic when the expression has incomplete class type.
2459 virtual SemaDiagnosticBuilder
2460 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2461
2462 /// \brief Emits a diagnostic when the only matching conversion function
2463 /// is explicit.
2464 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2465 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2466
2467 /// \brief Emits a note for the explicit conversion function.
2468 virtual SemaDiagnosticBuilder
2469 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2470
2471 /// \brief Emits a diagnostic when there are multiple possible conversion
2472 /// functions.
2473 virtual SemaDiagnosticBuilder
2474 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2475
2476 /// \brief Emits a note for one of the candidate conversions.
2477 virtual SemaDiagnosticBuilder
2478 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2479
2480 /// \brief Emits a diagnostic when we picked a conversion function
2481 /// (for cases when we are not allowed to pick a conversion function).
2482 virtual SemaDiagnosticBuilder diagnoseConversion(
2483 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2484
2485 virtual ~ContextualImplicitConverter() {}
2486 };
2487
2488 class ICEConvertDiagnoser : public ContextualImplicitConverter {
2489 bool AllowScopedEnumerations;
2490
2491 public:
2492 ICEConvertDiagnoser(bool AllowScopedEnumerations,
2493 bool Suppress, bool SuppressConversion)
2494 : ContextualImplicitConverter(Suppress, SuppressConversion),
2495 AllowScopedEnumerations(AllowScopedEnumerations) {}
2496
2497 /// Match an integral or (possibly scoped) enumeration type.
2498 bool match(QualType T) override;
2499
2500 SemaDiagnosticBuilder
2501 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2502 return diagnoseNotInt(S, Loc, T);
2503 }
2504
2505 /// \brief Emits a diagnostic complaining that the expression does not have
2506 /// integral or enumeration type.
2507 virtual SemaDiagnosticBuilder
2508 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2509 };
2510
2511 /// Perform a contextual implicit conversion.
2512 ExprResult PerformContextualImplicitConversion(
2513 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2514
2515
2516 enum ObjCSubscriptKind {
2517 OS_Array,
2518 OS_Dictionary,
2519 OS_Error
2520 };
2521 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2522
2523 // Note that LK_String is intentionally after the other literals, as
2524 // this is used for diagnostics logic.
2525 enum ObjCLiteralKind {
2526 LK_Array,
2527 LK_Dictionary,
2528 LK_Numeric,
2529 LK_Boxed,
2530 LK_String,
2531 LK_Block,
2532 LK_None
2533 };
2534 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2535
2536 ExprResult PerformObjectMemberConversion(Expr *From,
2537 NestedNameSpecifier *Qualifier,
2538 NamedDecl *FoundDecl,
2539 NamedDecl *Member);
2540
2541 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2542 // TODO: make this is a typesafe union.
2543 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
2544 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2545
2546 void AddOverloadCandidate(FunctionDecl *Function,
2547 DeclAccessPair FoundDecl,
2548 ArrayRef<Expr *> Args,
2549 OverloadCandidateSet &CandidateSet,
2550 bool SuppressUserConversions = false,
2551 bool PartialOverloading = false,
2552 bool AllowExplicit = false,
2553 ConversionSequenceList EarlyConversions = None);
2554 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2555 ArrayRef<Expr *> Args,
2556 OverloadCandidateSet &CandidateSet,
2557 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2558 bool SuppressUserConversions = false,
2559 bool PartialOverloading = false);
2560 void AddMethodCandidate(DeclAccessPair FoundDecl,
2561 QualType ObjectType,
2562 Expr::Classification ObjectClassification,
2563 ArrayRef<Expr *> Args,
2564 OverloadCandidateSet& CandidateSet,
2565 bool SuppressUserConversion = false);
2566 void AddMethodCandidate(CXXMethodDecl *Method,
2567 DeclAccessPair FoundDecl,
2568 CXXRecordDecl *ActingContext, QualType ObjectType,
2569 Expr::Classification ObjectClassification,
2570 ArrayRef<Expr *> Args,
2571 OverloadCandidateSet& CandidateSet,
2572 bool SuppressUserConversions = false,
2573 bool PartialOverloading = false,
2574 ConversionSequenceList EarlyConversions = None);
2575 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2576 DeclAccessPair FoundDecl,
2577 CXXRecordDecl *ActingContext,
2578 TemplateArgumentListInfo *ExplicitTemplateArgs,
2579 QualType ObjectType,
2580 Expr::Classification ObjectClassification,
2581 ArrayRef<Expr *> Args,
2582 OverloadCandidateSet& CandidateSet,
2583 bool SuppressUserConversions = false,
2584 bool PartialOverloading = false);
2585 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2586 DeclAccessPair FoundDecl,
2587 TemplateArgumentListInfo *ExplicitTemplateArgs,
2588 ArrayRef<Expr *> Args,
2589 OverloadCandidateSet& CandidateSet,
2590 bool SuppressUserConversions = false,
2591 bool PartialOverloading = false);
2592 bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2593 ArrayRef<QualType> ParamTypes,
2594 ArrayRef<Expr *> Args,
2595 OverloadCandidateSet &CandidateSet,
2596 ConversionSequenceList &Conversions,
2597 bool SuppressUserConversions,
2598 CXXRecordDecl *ActingContext = nullptr,
2599 QualType ObjectType = QualType(),
2600 Expr::Classification
2601 ObjectClassification = {});
2602 void AddConversionCandidate(CXXConversionDecl *Conversion,
2603 DeclAccessPair FoundDecl,
2604 CXXRecordDecl *ActingContext,
2605 Expr *From, QualType ToType,
2606 OverloadCandidateSet& CandidateSet,
2607 bool AllowObjCConversionOnExplicit);
2608 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2609 DeclAccessPair FoundDecl,
2610 CXXRecordDecl *ActingContext,
2611 Expr *From, QualType ToType,
2612 OverloadCandidateSet &CandidateSet,
2613 bool AllowObjCConversionOnExplicit);
2614 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2615 DeclAccessPair FoundDecl,
2616 CXXRecordDecl *ActingContext,
2617 const FunctionProtoType *Proto,
2618 Expr *Object, ArrayRef<Expr *> Args,
2619 OverloadCandidateSet& CandidateSet);
2620 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2621 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2622 OverloadCandidateSet& CandidateSet,
2623 SourceRange OpRange = SourceRange());
2624 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2625 ArrayRef<Expr *> Args,
2626 OverloadCandidateSet& CandidateSet,
2627 bool IsAssignmentOperator = false,
2628 unsigned NumContextualBoolArguments = 0);
2629 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2630 SourceLocation OpLoc, ArrayRef<Expr *> Args,
2631 OverloadCandidateSet& CandidateSet);
2632 void AddArgumentDependentLookupCandidates(DeclarationName Name,
2633 SourceLocation Loc,
2634 ArrayRef<Expr *> Args,
2635 TemplateArgumentListInfo *ExplicitTemplateArgs,
2636 OverloadCandidateSet& CandidateSet,
2637 bool PartialOverloading = false);
2638
2639 // Emit as a 'note' the specific overload candidate
2640 void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2641 QualType DestType = QualType(),
2642 bool TakingAddress = false);
2643
2644 // Emit as a series of 'note's all template and non-templates identified by
2645 // the expression Expr
2646 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2647 bool TakingAddress = false);
2648
2649 /// Check the enable_if expressions on the given function. Returns the first
2650 /// failing attribute, or NULL if they were all successful.
2651 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2652 bool MissingImplicitThis = false);
2653
2654 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2655 /// non-ArgDependent DiagnoseIfAttrs.
2656 ///
2657 /// Argument-dependent diagnose_if attributes should be checked each time a
2658 /// function is used as a direct callee of a function call.
2659 ///
2660 /// Returns true if any errors were emitted.
2661 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2662 const Expr *ThisArg,
2663 ArrayRef<const Expr *> Args,
2664 SourceLocation Loc);
2665
2666 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2667 /// ArgDependent DiagnoseIfAttrs.
2668 ///
2669 /// Argument-independent diagnose_if attributes should be checked on every use
2670 /// of a function.
2671 ///
2672 /// Returns true if any errors were emitted.
2673 bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2674 SourceLocation Loc);
2675
2676 /// Returns whether the given function's address can be taken or not,
2677 /// optionally emitting a diagnostic if the address can't be taken.
2678 ///
2679 /// Returns false if taking the address of the function is illegal.
2680 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2681 bool Complain = false,
2682 SourceLocation Loc = SourceLocation());
2683
2684 // [PossiblyAFunctionType] --> [Return]
2685 // NonFunctionType --> NonFunctionType
2686 // R (A) --> R(A)
2687 // R (*)(A) --> R (A)
2688 // R (&)(A) --> R (A)
2689 // R (S::*)(A) --> R (A)
2690 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2691
2692 FunctionDecl *
2693 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2694 QualType TargetType,
2695 bool Complain,
2696 DeclAccessPair &Found,
2697 bool *pHadMultipleCandidates = nullptr);
2698
2699 FunctionDecl *
2700 resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2701 DeclAccessPair &FoundResult);
2702
2703 bool resolveAndFixAddressOfOnlyViableOverloadCandidate(ExprResult &SrcExpr);
2704
2705 FunctionDecl *
2706 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2707 bool Complain = false,
2708 DeclAccessPair *Found = nullptr);
2709
2710 bool ResolveAndFixSingleFunctionTemplateSpecialization(
2711 ExprResult &SrcExpr,
2712 bool DoFunctionPointerConverion = false,
2713 bool Complain = false,
2714 SourceRange OpRangeForComplaining = SourceRange(),
2715 QualType DestTypeForComplaining = QualType(),
2716 unsigned DiagIDForComplaining = 0);
2717
2718
2719 Expr *FixOverloadedFunctionReference(Expr *E,
2720 DeclAccessPair FoundDecl,
2721 FunctionDecl *Fn);
2722 ExprResult FixOverloadedFunctionReference(ExprResult,
2723 DeclAccessPair FoundDecl,
2724 FunctionDecl *Fn);
2725
2726 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2727 ArrayRef<Expr *> Args,
2728 OverloadCandidateSet &CandidateSet,
2729 bool PartialOverloading = false);
2730
2731 // An enum used to represent the different possible results of building a
2732 // range-based for loop.
2733 enum ForRangeStatus {
2734 FRS_Success,
2735 FRS_NoViableFunction,
2736 FRS_DiagnosticIssued
2737 };
2738
2739 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2740 SourceLocation RangeLoc,
2741 const DeclarationNameInfo &NameInfo,
2742 LookupResult &MemberLookup,
2743 OverloadCandidateSet *CandidateSet,
2744 Expr *Range, ExprResult *CallExpr);
2745
2746 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2747 UnresolvedLookupExpr *ULE,
2748 SourceLocation LParenLoc,
2749 MultiExprArg Args,
2750 SourceLocation RParenLoc,
2751 Expr *ExecConfig,
2752 bool AllowTypoCorrection=true,
2753 bool CalleesAddressIsTaken=false);
2754
2755 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2756 MultiExprArg Args, SourceLocation RParenLoc,
2757 OverloadCandidateSet *CandidateSet,
2758 ExprResult *Result);
2759
2760 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2761 UnaryOperatorKind Opc,
2762 const UnresolvedSetImpl &Fns,
2763 Expr *input);
2764
2765 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2766 BinaryOperatorKind Opc,
2767 const UnresolvedSetImpl &Fns,
2768 Expr *LHS, Expr *RHS);
2769
2770 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2771 SourceLocation RLoc,
2772 Expr *Base,Expr *Idx);
2773
2774 ExprResult
2775 BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2776 SourceLocation LParenLoc,
2777 MultiExprArg Args,
2778 SourceLocation RParenLoc);
2779 ExprResult
2780 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2781 MultiExprArg Args,
2782 SourceLocation RParenLoc);
2783
2784 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2785 SourceLocation OpLoc,
2786 bool *NoArrowOperatorFound = nullptr);
2787
2788 /// CheckCallReturnType - Checks that a call expression's return type is
2789 /// complete. Returns true on failure. The location passed in is the location
2790 /// that best represents the call.
2791 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2792 CallExpr *CE, FunctionDecl *FD);
2793
2794 /// Helpers for dealing with blocks and functions.
2795 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2796 bool CheckParameterNames);
2797 void CheckCXXDefaultArguments(FunctionDecl *FD);
2798 void CheckExtraCXXDefaultArguments(Declarator &D);
2799 Scope *getNonFieldDeclScope(Scope *S);
2800
2801 /// \name Name lookup
2802 ///
2803 /// These routines provide name lookup that is used during semantic
2804 /// analysis to resolve the various kinds of names (identifiers,
2805 /// overloaded operator names, constructor names, etc.) into zero or
2806 /// more declarations within a particular scope. The major entry
2807 /// points are LookupName, which performs unqualified name lookup,
2808 /// and LookupQualifiedName, which performs qualified name lookup.
2809 ///
2810 /// All name lookup is performed based on some specific criteria,
2811 /// which specify what names will be visible to name lookup and how
2812 /// far name lookup should work. These criteria are important both
2813 /// for capturing language semantics (certain lookups will ignore
2814 /// certain names, for example) and for performance, since name
2815 /// lookup is often a bottleneck in the compilation of C++. Name
2816 /// lookup criteria is specified via the LookupCriteria enumeration.
2817 ///
2818 /// The results of name lookup can vary based on the kind of name
2819 /// lookup performed, the current language, and the translation
2820 /// unit. In C, for example, name lookup will either return nothing
2821 /// (no entity found) or a single declaration. In C++, name lookup
2822 /// can additionally refer to a set of overloaded functions or
2823 /// result in an ambiguity. All of the possible results of name
2824 /// lookup are captured by the LookupResult class, which provides
2825 /// the ability to distinguish among them.
2826 //@{
2827
2828 /// @brief Describes the kind of name lookup to perform.
2829 enum LookupNameKind {
2830 /// Ordinary name lookup, which finds ordinary names (functions,
2831 /// variables, typedefs, etc.) in C and most kinds of names
2832 /// (functions, variables, members, types, etc.) in C++.
2833 LookupOrdinaryName = 0,
2834 /// Tag name lookup, which finds the names of enums, classes,
2835 /// structs, and unions.
2836 LookupTagName,
2837 /// Label name lookup.
2838 LookupLabel,
2839 /// Member name lookup, which finds the names of
2840 /// class/struct/union members.
2841 LookupMemberName,
2842 /// Look up of an operator name (e.g., operator+) for use with
2843 /// operator overloading. This lookup is similar to ordinary name
2844 /// lookup, but will ignore any declarations that are class members.
2845 LookupOperatorName,
2846 /// Look up of a name that precedes the '::' scope resolution
2847 /// operator in C++. This lookup completely ignores operator, object,
2848 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2849 LookupNestedNameSpecifierName,
2850 /// Look up a namespace name within a C++ using directive or
2851 /// namespace alias definition, ignoring non-namespace names (C++
2852 /// [basic.lookup.udir]p1).
2853 LookupNamespaceName,
2854 /// Look up all declarations in a scope with the given name,
2855 /// including resolved using declarations. This is appropriate
2856 /// for checking redeclarations for a using declaration.
2857 LookupUsingDeclName,
2858 /// Look up an ordinary name that is going to be redeclared as a
2859 /// name with linkage. This lookup ignores any declarations that
2860 /// are outside of the current scope unless they have linkage. See
2861 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2862 LookupRedeclarationWithLinkage,
2863 /// Look up a friend of a local class. This lookup does not look
2864 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2865 LookupLocalFriendName,
2866 /// Look up the name of an Objective-C protocol.
2867 LookupObjCProtocolName,
2868 /// Look up implicit 'self' parameter of an objective-c method.
2869 LookupObjCImplicitSelfParam,
2870 /// \brief Look up the name of an OpenMP user-defined reduction operation.
2871 LookupOMPReductionName,
2872 /// \brief Look up any declaration with any name.
2873 LookupAnyName
2874 };
2875
2876 /// \brief Specifies whether (or how) name lookup is being performed for a
2877 /// redeclaration (vs. a reference).
2878 enum RedeclarationKind {
2879 /// \brief The lookup is a reference to this name that is not for the
2880 /// purpose of redeclaring the name.
2881 NotForRedeclaration = 0,
2882 /// \brief The lookup results will be used for redeclaration of a name,
2883 /// if an entity by that name already exists.
2884 ForRedeclaration
2885 };
2886
2887 /// \brief The possible outcomes of name lookup for a literal operator.
2888 enum LiteralOperatorLookupResult {
2889 /// \brief The lookup resulted in an error.
2890 LOLR_Error,
2891 /// \brief The lookup found a single 'cooked' literal operator, which
2892 /// expects a normal literal to be built and passed to it.
2893 LOLR_Cooked,
2894 /// \brief The lookup found a single 'raw' literal operator, which expects
2895 /// a string literal containing the spelling of the literal token.
2896 LOLR_Raw,
2897 /// \brief The lookup found an overload set of literal operator templates,
2898 /// which expect the characters of the spelling of the literal token to be
2899 /// passed as a non-type template argument pack.
2900 LOLR_Template,
2901 /// \brief The lookup found an overload set of literal operator templates,
2902 /// which expect the character type and characters of the spelling of the
2903 /// string literal token to be passed as template arguments.
2904 LOLR_StringTemplate
2905 };
2906
2907 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2908 CXXSpecialMember SM,
2909 bool ConstArg,
2910 bool VolatileArg,
2911 bool RValueThis,
2912 bool ConstThis,
2913 bool VolatileThis);
2914
2915 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2916 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2917 TypoRecoveryCallback;
2918
2919private:
2920 bool CppLookupName(LookupResult &R, Scope *S);
2921
2922 struct TypoExprState {
2923 std::unique_ptr<TypoCorrectionConsumer> Consumer;
2924 TypoDiagnosticGenerator DiagHandler;
2925 TypoRecoveryCallback RecoveryHandler;
2926 TypoExprState();
2927 TypoExprState(TypoExprState &&other) noexcept;
2928 TypoExprState &operator=(TypoExprState &&other) noexcept;
2929 };
2930
2931 /// \brief The set of unhandled TypoExprs and their associated state.
2932 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2933
2934 /// \brief Creates a new TypoExpr AST node.
2935 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2936 TypoDiagnosticGenerator TDG,
2937 TypoRecoveryCallback TRC);
2938
2939 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2940 //
2941 // The boolean value will be true to indicate that the namespace was loaded
2942 // from an AST/PCH file, or false otherwise.
2943 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2944
2945 /// \brief Whether we have already loaded known namespaces from an extenal
2946 /// source.
2947 bool LoadedExternalKnownNamespaces;
2948
2949 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2950 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2951 /// should be skipped entirely.
2952 std::unique_ptr<TypoCorrectionConsumer>
2953 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2954 Sema::LookupNameKind LookupKind, Scope *S,
2955 CXXScopeSpec *SS,
2956 std::unique_ptr<CorrectionCandidateCallback> CCC,
2957 DeclContext *MemberContext, bool EnteringContext,
2958 const ObjCObjectPointerType *OPT,
2959 bool ErrorRecovery);
2960
2961public:
2962 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2963
2964 /// \brief Clears the state of the given TypoExpr.
2965 void clearDelayedTypo(TypoExpr *TE);
2966
2967 /// \brief Look up a name, looking for a single declaration. Return
2968 /// null if the results were absent, ambiguous, or overloaded.
2969 ///
2970 /// It is preferable to use the elaborated form and explicitly handle
2971 /// ambiguity and overloaded.
2972 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2973 SourceLocation Loc,
2974 LookupNameKind NameKind,
2975 RedeclarationKind Redecl
2976 = NotForRedeclaration);
2977 bool LookupName(LookupResult &R, Scope *S,
2978 bool AllowBuiltinCreation = false);
2979 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2980 bool InUnqualifiedLookup = false);
2981 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2982 CXXScopeSpec &SS);
2983 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2984 bool AllowBuiltinCreation = false,
2985 bool EnteringContext = false);
2986 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2987 RedeclarationKind Redecl
2988 = NotForRedeclaration);
2989 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2990
2991 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2992 QualType T1, QualType T2,
2993 UnresolvedSetImpl &Functions);
2994 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
2995 DeclAccessPair Operator,
2996 QualType T1, QualType T2);
2997
2998 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
2999 SourceLocation GnuLabelLoc = SourceLocation());
3000
3001 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3002 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3003 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3004 unsigned Quals);
3005 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3006 bool RValueThis, unsigned ThisQuals);
3007 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3008 unsigned Quals);
3009 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3010 bool RValueThis, unsigned ThisQuals);
3011 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3012
3013 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3014 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3015 ArrayRef<QualType> ArgTys,
3016 bool AllowRaw,
3017 bool AllowTemplate,
3018 bool AllowStringTemplate);
3019 bool isKnownName(StringRef name);
3020
3021 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3022 ArrayRef<Expr *> Args, ADLResult &Functions);
3023
3024 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3025 VisibleDeclConsumer &Consumer,
3026 bool IncludeGlobalScope = true);
3027 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3028 VisibleDeclConsumer &Consumer,
3029 bool IncludeGlobalScope = true);
3030
3031 enum CorrectTypoKind {
3032 CTK_NonError, // CorrectTypo used in a non error recovery situation.
3033 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3034 };
3035
3036 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3037 Sema::LookupNameKind LookupKind,
3038 Scope *S, CXXScopeSpec *SS,
3039 std::unique_ptr<CorrectionCandidateCallback> CCC,
3040 CorrectTypoKind Mode,
3041 DeclContext *MemberContext = nullptr,
3042 bool EnteringContext = false,
3043 const ObjCObjectPointerType *OPT = nullptr,
3044 bool RecordFailure = true);
3045
3046 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3047 Sema::LookupNameKind LookupKind, Scope *S,
3048 CXXScopeSpec *SS,
3049 std::unique_ptr<CorrectionCandidateCallback> CCC,
3050 TypoDiagnosticGenerator TDG,
3051 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3052 DeclContext *MemberContext = nullptr,
3053 bool EnteringContext = false,
3054 const ObjCObjectPointerType *OPT = nullptr);
3055
3056 /// \brief Process any TypoExprs in the given Expr and its children,
3057 /// generating diagnostics as appropriate and returning a new Expr if there
3058 /// were typos that were all successfully corrected and ExprError if one or
3059 /// more typos could not be corrected.
3060 ///
3061 /// \param E The Expr to check for TypoExprs.
3062 ///
3063 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3064 /// initializer.
3065 ///
3066 /// \param Filter A function applied to a newly rebuilt Expr to determine if
3067 /// it is an acceptable/usable result from a single combination of typo
3068 /// corrections. As long as the filter returns ExprError, different
3069 /// combinations of corrections will be tried until all are exhausted.
3070 ExprResult
3071 CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3072 llvm::function_ref<ExprResult(Expr *)> Filter =
3073 [](Expr *E) -> ExprResult { return E; });
3074
3075 ExprResult
3076 CorrectDelayedTyposInExpr(Expr *E,
3077 llvm::function_ref<ExprResult(Expr *)> Filter) {
3078 return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3079 }
3080
3081 ExprResult
3082 CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3083 llvm::function_ref<ExprResult(Expr *)> Filter =
3084 [](Expr *E) -> ExprResult { return E; }) {
3085 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3086 }
3087
3088 ExprResult
3089 CorrectDelayedTyposInExpr(ExprResult ER,
3090 llvm::function_ref<ExprResult(Expr *)> Filter) {
3091 return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3092 }
3093
3094 void diagnoseTypo(const TypoCorrection &Correction,
3095 const PartialDiagnostic &TypoDiag,
3096 bool ErrorRecovery = true);
3097
3098 void diagnoseTypo(const TypoCorrection &Correction,
3099 const PartialDiagnostic &TypoDiag,
3100 const PartialDiagnostic &PrevNote,
3101 bool ErrorRecovery = true);
3102
3103 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3104 ArrayRef<Expr *> Args,
3105 AssociatedNamespaceSet &AssociatedNamespaces,
3106 AssociatedClassSet &AssociatedClasses);
3107
3108 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3109 bool ConsiderLinkage, bool AllowInlineNamespace);
3110
3111 void DiagnoseAmbiguousLookup(LookupResult &Result);
3112 //@}
3113
3114 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3115 SourceLocation IdLoc,
3116 bool TypoCorrection = false);
3117 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3118 Scope *S, bool ForRedeclaration,
3119 SourceLocation Loc);
3120 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3121 Scope *S);
3122 void AddKnownFunctionAttributes(FunctionDecl *FD);
3123
3124 // More parsing and symbol table subroutines.
3125
3126 void ProcessPragmaWeak(Scope *S, Decl *D);
3127 // Decl attributes - this routine is the top level dispatcher.
3128 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3129 // Helper for delayed proccessing of attributes.
3130 void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3131 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3132 bool IncludeCXX11Attributes = true);
3133 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3134 const AttributeList *AttrList);
3135
3136 void checkUnusedDeclAttributes(Declarator &D);
3137
3138 /// Determine if type T is a valid subject for a nonnull and similar
3139 /// attributes. By default, we look through references (the behavior used by
3140 /// nonnull), but if the second parameter is true, then we treat a reference
3141 /// type as valid.
3142 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3143
3144 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3145 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3146 const FunctionDecl *FD = nullptr);
3147 bool CheckNoReturnAttr(const AttributeList &attr);
3148 bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3149 unsigned ArgNum, StringRef &Str,
3150 SourceLocation *ArgLocation = nullptr);
3151 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3152 void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3153 bool checkMSInheritanceAttrOnDefinition(
3154 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3155 MSInheritanceAttr::Spelling SemanticSpelling);
3156
3157 void CheckAlignasUnderalignment(Decl *D);
3158
3159 /// Adjust the calling convention of a method to be the ABI default if it
3160 /// wasn't specified explicitly. This handles method types formed from
3161 /// function type typedefs and typename template arguments.
3162 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3163 SourceLocation Loc);
3164
3165 // Check if there is an explicit attribute, but only look through parens.
3166 // The intent is to look for an attribute on the current declarator, but not
3167 // one that came from a typedef.
3168 bool hasExplicitCallingConv(QualType &T);
3169
3170 /// Get the outermost AttributedType node that sets a calling convention.
3171 /// Valid types should not have multiple attributes with different CCs.
3172 const AttributedType *getCallingConvAttributedType(QualType T) const;
3173
3174 /// Check whether a nullability type specifier can be added to the given
3175 /// type.
3176 ///
3177 /// \param type The type to which the nullability specifier will be
3178 /// added. On success, this type will be updated appropriately.
3179 ///
3180 /// \param nullability The nullability specifier to add.
3181 ///
3182 /// \param nullabilityLoc The location of the nullability specifier.
3183 ///
3184 /// \param isContextSensitive Whether this nullability specifier was
3185 /// written as a context-sensitive keyword (in an Objective-C
3186 /// method) or an Objective-C property attribute, rather than as an
3187 /// underscored type specifier.
3188 ///
3189 /// \param allowArrayTypes Whether to accept nullability specifiers on an
3190 /// array type (e.g., because it will decay to a pointer).
3191 ///
3192 /// \returns true if nullability cannot be applied, false otherwise.
3193 bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3194 SourceLocation nullabilityLoc,
3195 bool isContextSensitive,
3196 bool allowArrayTypes);
3197
3198 /// \brief Stmt attributes - this routine is the top level dispatcher.
3199 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3200 SourceRange Range);
3201
3202 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3203 ObjCMethodDecl *MethodDecl,
3204 bool IsProtocolMethodDecl);
3205
3206 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3207 ObjCMethodDecl *Overridden,
3208 bool IsProtocolMethodDecl);
3209
3210 /// WarnExactTypedMethods - This routine issues a warning if method
3211 /// implementation declaration matches exactly that of its declaration.
3212 void WarnExactTypedMethods(ObjCMethodDecl *Method,
3213 ObjCMethodDecl *MethodDecl,
3214 bool IsProtocolMethodDecl);
3215
3216 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3217
3218 /// CheckImplementationIvars - This routine checks if the instance variables
3219 /// listed in the implelementation match those listed in the interface.
3220 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3221 ObjCIvarDecl **Fields, unsigned nIvars,
3222 SourceLocation Loc);
3223
3224 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3225 /// remains unimplemented in the class or category \@implementation.
3226 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3227 ObjCContainerDecl* IDecl,
3228 bool IncompleteImpl = false);
3229
3230 /// DiagnoseUnimplementedProperties - This routine warns on those properties
3231 /// which must be implemented by this implementation.
3232 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3233 ObjCContainerDecl *CDecl,
3234 bool SynthesizeProperties);
3235
3236 /// Diagnose any null-resettable synthesized setters.
3237 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3238
3239 /// DefaultSynthesizeProperties - This routine default synthesizes all
3240 /// properties which must be synthesized in the class's \@implementation.
3241 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3242 ObjCInterfaceDecl *IDecl);
3243 void DefaultSynthesizeProperties(Scope *S, Decl *D);
3244
3245 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3246 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3247 /// declared in class 'IFace'.
3248 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3249 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3250
3251 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3252 /// backs the property is not used in the property's accessor.
3253 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3254 const ObjCImplementationDecl *ImplD);
3255
3256 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3257 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3258 /// It also returns ivar's property on success.
3259 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3260 const ObjCPropertyDecl *&PDecl) const;
3261
3262 /// Called by ActOnProperty to handle \@property declarations in
3263 /// class extensions.
3264 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3265 SourceLocation AtLoc,
3266 SourceLocation LParenLoc,
3267 FieldDeclarator &FD,
3268 Selector GetterSel,
3269 SourceLocation GetterNameLoc,
3270 Selector SetterSel,
3271 SourceLocation SetterNameLoc,
3272 const bool isReadWrite,
3273 unsigned &Attributes,
3274 const unsigned AttributesAsWritten,
3275 QualType T,
3276 TypeSourceInfo *TSI,
3277 tok::ObjCKeywordKind MethodImplKind);
3278
3279 /// Called by ActOnProperty and HandlePropertyInClassExtension to
3280 /// handle creating the ObjcPropertyDecl for a category or \@interface.
3281 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3282 ObjCContainerDecl *CDecl,
3283 SourceLocation AtLoc,
3284 SourceLocation LParenLoc,
3285 FieldDeclarator &FD,
3286 Selector GetterSel,
3287 SourceLocation GetterNameLoc,
3288 Selector SetterSel,
3289 SourceLocation SetterNameLoc,
3290 const bool isReadWrite,
3291 const unsigned Attributes,
3292 const unsigned AttributesAsWritten,
3293 QualType T,
3294 TypeSourceInfo *TSI,
3295 tok::ObjCKeywordKind MethodImplKind,
3296 DeclContext *lexicalDC = nullptr);
3297
3298 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3299 /// warning) when atomic property has one but not the other user-declared
3300 /// setter or getter.
3301 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3302 ObjCInterfaceDecl* IDecl);
3303
3304 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3305
3306 void DiagnoseMissingDesignatedInitOverrides(
3307 const ObjCImplementationDecl *ImplD,
3308 const ObjCInterfaceDecl *IFD);
3309
3310 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3311
3312 enum MethodMatchStrategy {
3313 MMS_loose,
3314 MMS_strict
3315 };
3316
3317 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3318 /// true, or false, accordingly.
3319 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3320 const ObjCMethodDecl *PrevMethod,
3321 MethodMatchStrategy strategy = MMS_strict);
3322
3323 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3324 /// or protocol against those declared in their implementations.
3325 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3326 const SelectorSet &ClsMap,
3327 SelectorSet &InsMapSeen,
3328 SelectorSet &ClsMapSeen,
3329 ObjCImplDecl* IMPDecl,
3330 ObjCContainerDecl* IDecl,
3331 bool &IncompleteImpl,
3332 bool ImmediateClass,
3333 bool WarnCategoryMethodImpl=false);
3334
3335 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3336 /// category matches with those implemented in its primary class and
3337 /// warns each time an exact match is found.
3338 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3339
3340 /// \brief Add the given method to the list of globally-known methods.
3341 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3342
3343private:
3344 /// AddMethodToGlobalPool - Add an instance or factory method to the global
3345 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3346 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3347
3348 /// LookupMethodInGlobalPool - Returns the instance or factory method and
3349 /// optionally warns if there are multiple signatures.
3350 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3351 bool receiverIdOrClass,
3352 bool instance);
3353
3354public:
3355 /// \brief - Returns instance or factory methods in global method pool for
3356 /// given selector. It checks the desired kind first, if none is found, and
3357 /// parameter checkTheOther is set, it then checks the other kind. If no such
3358 /// method or only one method is found, function returns false; otherwise, it
3359 /// returns true.
3360 bool
3361 CollectMultipleMethodsInGlobalPool(Selector Sel,
3362 SmallVectorImpl<ObjCMethodDecl*>& Methods,
3363 bool InstanceFirst, bool CheckTheOther,
3364 const ObjCObjectType *TypeBound = nullptr);
3365
3366 bool
3367 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3368 SourceRange R, bool receiverIdOrClass,
3369 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3370
3371 void
3372 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3373 Selector Sel, SourceRange R,
3374 bool receiverIdOrClass);
3375
3376private:
3377 /// \brief - Returns a selector which best matches given argument list or
3378 /// nullptr if none could be found
3379 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3380 bool IsInstance,
3381 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3382
3383
3384 /// \brief Record the typo correction failure and return an empty correction.
3385 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3386 bool RecordFailure = true) {
3387 if (RecordFailure)
3388 TypoCorrectionFailures[Typo].insert(TypoLoc);
3389 return TypoCorrection();
3390 }
3391
3392public:
3393 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3394 /// unit are added to a global pool. This allows us to efficiently associate
3395 /// a selector with a method declaraation for purposes of typechecking
3396 /// messages sent to "id" (where the class of the object is unknown).
3397 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3398 AddMethodToGlobalPool(Method, impl, /*instance*/true);
3399 }
3400
3401 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3402 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3403 AddMethodToGlobalPool(Method, impl, /*instance*/false);
3404 }
3405
3406 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3407 /// pool.
3408 void AddAnyMethodToGlobalPool(Decl *D);
3409
3410 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3411 /// there are multiple signatures.
3412 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3413 bool receiverIdOrClass=false) {
3414 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3415 /*instance*/true);
3416 }
3417
3418 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3419 /// there are multiple signatures.
3420 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3421 bool receiverIdOrClass=false) {
3422 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3423 /*instance*/false);
3424 }
3425
3426 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3427 QualType ObjectType=QualType());
3428 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3429 /// implementation.
3430 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3431
3432 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3433 /// initialization.
3434 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3435 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3436
3437 //===--------------------------------------------------------------------===//
3438 // Statement Parsing Callbacks: SemaStmt.cpp.
3439public:
3440 class FullExprArg {
3441 public:
3442 FullExprArg() : E(nullptr) { }
3443 FullExprArg(Sema &actions) : E(nullptr) { }
3444
3445 ExprResult release() {
3446 return E;
3447 }
3448
3449 Expr *get() const { return E; }
3450
3451 Expr *operator->() {
3452 return E;
3453 }
3454
3455 private:
3456 // FIXME: No need to make the entire Sema class a friend when it's just
3457 // Sema::MakeFullExpr that needs access to the constructor below.
3458 friend class Sema;
3459
3460 explicit FullExprArg(Expr *expr) : E(expr) {}
3461
3462 Expr *E;
3463 };
3464
3465 FullExprArg MakeFullExpr(Expr *Arg) {
3466 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3467 }
3468 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3469 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3470 }
3471 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3472 ExprResult FE =
3473 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3474 /*DiscardedValue*/ true);
3475 return FullExprArg(FE.get());
3476 }
3477
3478 StmtResult ActOnExprStmt(ExprResult Arg);
3479 StmtResult ActOnExprStmtError();
3480
3481 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3482 bool HasLeadingEmptyMacro = false);
3483
3484 void ActOnStartOfCompoundStmt();
3485 void ActOnFinishOfCompoundStmt();
3486 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3487 ArrayRef<Stmt *> Elts, bool isStmtExpr);
3488
3489 /// \brief A RAII object to enter scope of a compound statement.
3490 class CompoundScopeRAII {
3491 public:
3492 CompoundScopeRAII(Sema &S): S(S) {
3493 S.ActOnStartOfCompoundStmt();
3494 }
3495
3496 ~CompoundScopeRAII() {
3497 S.ActOnFinishOfCompoundStmt();
3498 }
3499
3500 private:
3501 Sema &S;
3502 };
3503
3504 /// An RAII helper that pops function a function scope on exit.
3505 struct FunctionScopeRAII {
3506 Sema &S;
3507 bool Active;
3508 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3509 ~FunctionScopeRAII() {
3510 if (Active)
3511 S.PopFunctionScopeInfo();
3512 }
3513 void disable() { Active = false; }
3514 };
3515
3516 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3517 SourceLocation StartLoc,
3518 SourceLocation EndLoc);
3519 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3520 StmtResult ActOnForEachLValueExpr(Expr *E);
3521 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3522 SourceLocation DotDotDotLoc, Expr *RHSVal,
3523 SourceLocation ColonLoc);
3524 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3525
3526 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3527 SourceLocation ColonLoc,
3528 Stmt *SubStmt, Scope *CurScope);
3529 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3530 SourceLocation ColonLoc, Stmt *SubStmt);
3531
3532 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3533 ArrayRef<const Attr*> Attrs,
3534 Stmt *SubStmt);
3535
3536 class ConditionResult;
3537 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3538 Stmt *InitStmt,
3539 ConditionResult Cond, Stmt *ThenVal,
3540 SourceLocation ElseLoc, Stmt *ElseVal);
3541 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3542 Stmt *InitStmt,
3543 ConditionResult Cond, Stmt *ThenVal,
3544 SourceLocation ElseLoc, Stmt *ElseVal);
3545 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3546 Stmt *InitStmt,
3547 ConditionResult Cond);
3548 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3549 Stmt *Switch, Stmt *Body);
3550 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3551 Stmt *Body);
3552 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3553 SourceLocation WhileLoc, SourceLocation CondLParen,
3554 Expr *Cond, SourceLocation CondRParen);
3555
3556 StmtResult ActOnForStmt(SourceLocation ForLoc,
3557 SourceLocation LParenLoc,
3558 Stmt *First,
3559 ConditionResult Second,
3560 FullExprArg Third,
3561 SourceLocation RParenLoc,
3562 Stmt *Body);
3563 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3564 Expr *collection);
3565 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3566 Stmt *First, Expr *collection,
3567 SourceLocation RParenLoc);
3568 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3569
3570 enum BuildForRangeKind {
3571 /// Initial building of a for-range statement.
3572 BFRK_Build,
3573 /// Instantiation or recovery rebuild of a for-range statement. Don't
3574 /// attempt any typo-correction.
3575 BFRK_Rebuild,
3576 /// Determining whether a for-range statement could be built. Avoid any
3577 /// unnecessary or irreversible actions.
3578 BFRK_Check
3579 };
3580
3581 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3582 SourceLocation CoawaitLoc,
3583 Stmt *LoopVar,
3584 SourceLocation ColonLoc, Expr *Collection,
3585 SourceLocation RParenLoc,
3586 BuildForRangeKind Kind);
3587 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3588 SourceLocation CoawaitLoc,
3589 SourceLocation ColonLoc,
3590 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3591 Expr *Cond, Expr *Inc,
3592 Stmt *LoopVarDecl,
3593 SourceLocation RParenLoc,
3594 BuildForRangeKind Kind);
3595 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3596
3597 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3598 SourceLocation LabelLoc,
3599 LabelDecl *TheDecl);
3600 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3601 SourceLocation StarLoc,
3602 Expr *DestExp);
3603 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3604 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3605
3606 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3607 CapturedRegionKind Kind, unsigned NumParams);
3608 typedef std::pair<StringRef, QualType> CapturedParamNameType;
3609 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3610 CapturedRegionKind Kind,
3611 ArrayRef<CapturedParamNameType> Params);
3612 StmtResult ActOnCapturedRegionEnd(Stmt *S);
3613 void ActOnCapturedRegionError();
3614 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3615 SourceLocation Loc,
3616 unsigned NumParams);
3617 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3618 bool AllowParamOrMoveConstructible);
3619 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3620 bool AllowParamOrMoveConstructible);
3621
3622 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3623 Scope *CurScope);
3624 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3625 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3626
3627 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3628 bool IsVolatile, unsigned NumOutputs,
3629 unsigned NumInputs, IdentifierInfo **Names,
3630 MultiExprArg Constraints, MultiExprArg Exprs,
3631 Expr *AsmString, MultiExprArg Clobbers,
3632 SourceLocation RParenLoc);
3633
3634 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3635 SourceLocation TemplateKWLoc,
3636 UnqualifiedId &Id,
3637 llvm::InlineAsmIdentifierInfo &Info,
3638 bool IsUnevaluatedContext);
3639 bool LookupInlineAsmField(StringRef Base, StringRef Member,
3640 unsigned &Offset, SourceLocation AsmLoc);
3641 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3642 llvm::InlineAsmIdentifierInfo &Info,
3643 SourceLocation AsmLoc);
3644 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3645 ArrayRef<Token> AsmToks,
3646 StringRef AsmString,
3647 unsigned NumOutputs, unsigned NumInputs,
3648 ArrayRef<StringRef> Constraints,
3649 ArrayRef<StringRef> Clobbers,
3650 ArrayRef<Expr*> Exprs,
3651 SourceLocation EndLoc);
3652 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3653 SourceLocation Location,
3654 bool AlwaysCreate);
3655
3656 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3657 SourceLocation StartLoc,
3658 SourceLocation IdLoc, IdentifierInfo *Id,
3659 bool Invalid = false);
3660
3661 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3662
3663 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3664 Decl *Parm, Stmt *Body);
3665
3666 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3667
3668 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3669 MultiStmtArg Catch, Stmt *Finally);
3670
3671 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3672 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3673 Scope *CurScope);
3674 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3675 Expr *operand);
3676 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3677 Expr *SynchExpr,
3678 Stmt *SynchBody);
3679
3680 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3681
3682 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3683 SourceLocation StartLoc,
3684 SourceLocation IdLoc,
3685 IdentifierInfo *Id);
3686
3687 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3688
3689 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3690 Decl *ExDecl, Stmt *HandlerBlock);
3691 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3692 ArrayRef<Stmt *> Handlers);
3693
3694 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3695 SourceLocation TryLoc, Stmt *TryBlock,
3696 Stmt *Handler);
3697 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3698 Expr *FilterExpr,
3699 Stmt *Block);
3700 void ActOnStartSEHFinallyBlock();
3701 void ActOnAbortSEHFinallyBlock();
3702 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3703 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3704
3705 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3706
3707 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3708
3709 /// \brief If it's a file scoped decl that must warn if not used, keep track
3710 /// of it.
3711 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3712
3713 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3714 /// whose result is unused, warn.
3715 void DiagnoseUnusedExprResult(const Stmt *S);
3716 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3717 void DiagnoseUnusedDecl(const NamedDecl *ND);
3718
3719 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3720 /// statement as a \p Body, and it is located on the same line.
3721 ///
3722 /// This helps prevent bugs due to typos, such as:
3723 /// if (condition);
3724 /// do_stuff();
3725 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3726 const Stmt *Body,
3727 unsigned DiagID);
3728
3729 /// Warn if a for/while loop statement \p S, which is followed by
3730 /// \p PossibleBody, has a suspicious null statement as a body.
3731 void DiagnoseEmptyLoopBody(const Stmt *S,
3732 const Stmt *PossibleBody);
3733
3734 /// Warn if a value is moved to itself.
3735 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3736 SourceLocation OpLoc);
3737
3738 /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3739 /// _Nonnull one.
3740 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3741 SourceLocation Loc);
3742
3743 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3744 return DelayedDiagnostics.push(pool);
3745 }
3746 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3747
3748 typedef ProcessingContextState ParsingClassState;
3749 ParsingClassState PushParsingClass() {
3750 return DelayedDiagnostics.pushUndelayed();
3751 }
3752 void PopParsingClass(ParsingClassState state) {
3753 DelayedDiagnostics.popUndelayed(state);
3754 }
3755
3756 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3757
3758 void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3759 StringRef Message, SourceLocation Loc,
3760 const ObjCInterfaceDecl *UnknownObjCClass,
3761 const ObjCPropertyDecl *ObjCProperty,
3762 bool ObjCPropertyAccess);
3763
3764 bool makeUnavailableInSystemHeader(SourceLocation loc,
3765 UnavailableAttr::ImplicitReason reason);
3766
3767 /// \brief Issue any -Wunguarded-availability warnings in \c FD
3768 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3769
3770 //===--------------------------------------------------------------------===//
3771 // Expression Parsing Callbacks: SemaExpr.cpp.
3772
3773 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3774 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3775 const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3776 bool ObjCPropertyAccess=false);
3777 void NoteDeletedFunction(FunctionDecl *FD);
3778 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3779 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3780 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3781 ObjCMethodDecl *Getter,
3782 SourceLocation Loc);
3783 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3784 ArrayRef<Expr *> Args);
3785
3786 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3787 Decl *LambdaContextDecl = nullptr,
3788 bool IsDecltype = false);
3789 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3790 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3791 ReuseLambdaContextDecl_t,
3792 bool IsDecltype = false);
3793 void PopExpressionEvaluationContext();
3794
3795 void DiscardCleanupsInEvaluationContext();
3796
3797 ExprResult TransformToPotentiallyEvaluated(Expr *E);
3798 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3799
3800 ExprResult ActOnConstantExpression(ExprResult Res);
3801
3802 // Functions for marking a declaration referenced. These functions also
3803 // contain the relevant logic for marking if a reference to a function or
3804 // variable is an odr-use (in the C++11 sense). There are separate variants
3805 // for expressions referring to a decl; these exist because odr-use marking
3806 // needs to be delayed for some constant variables when we build one of the
3807 // named expressions.
3808 //
3809 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3810 // should usually be true. This only needs to be set to false if the lack of
3811 // odr-use cannot be determined from the current context (for instance,
3812 // because the name denotes a virtual function and was written without an
3813 // explicit nested-name-specifier).
3814 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3815 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3816 bool MightBeOdrUse = true);
3817 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3818 void MarkDeclRefReferenced(DeclRefExpr *E);
3819 void MarkMemberReferenced(MemberExpr *E);
3820
3821 void UpdateMarkingForLValueToRValue(Expr *E);
3822 void CleanupVarDeclMarking();
3823
3824 enum TryCaptureKind {
3825 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3826 };
3827
3828 /// \brief Try to capture the given variable.
3829 ///
3830 /// \param Var The variable to capture.
3831 ///
3832 /// \param Loc The location at which the capture occurs.
3833 ///
3834 /// \param Kind The kind of capture, which may be implicit (for either a
3835 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3836 ///
3837 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3838 /// an explicit lambda capture.
3839 ///
3840 /// \param BuildAndDiagnose Whether we are actually supposed to add the
3841 /// captures or diagnose errors. If false, this routine merely check whether
3842 /// the capture can occur without performing the capture itself or complaining
3843 /// if the variable cannot be captured.
3844 ///
3845 /// \param CaptureType Will be set to the type of the field used to capture
3846 /// this variable in the innermost block or lambda. Only valid when the
3847 /// variable can be captured.
3848 ///
3849 /// \param DeclRefType Will be set to the type of a reference to the capture
3850 /// from within the current scope. Only valid when the variable can be
3851 /// captured.
3852 ///
3853 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3854 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3855 /// This is useful when enclosing lambdas must speculatively capture
3856 /// variables that may or may not be used in certain specializations of
3857 /// a nested generic lambda.
3858 ///
3859 /// \returns true if an error occurred (i.e., the variable cannot be
3860 /// captured) and false if the capture succeeded.
3861 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3862 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3863 QualType &CaptureType,
3864 QualType &DeclRefType,
3865 const unsigned *const FunctionScopeIndexToStopAt);
3866
3867 /// \brief Try to capture the given variable.
3868 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3869 TryCaptureKind Kind = TryCapture_Implicit,
3870 SourceLocation EllipsisLoc = SourceLocation());
3871
3872 /// \brief Checks if the variable must be captured.
3873 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3874
3875 /// \brief Given a variable, determine the type that a reference to that
3876 /// variable will have in the given scope.
3877 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3878
3879 /// Mark all of the declarations referenced within a particular AST node as
3880 /// referenced. Used when template instantiation instantiates a non-dependent
3881 /// type -- entities referenced by the type are now referenced.
3882 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3883 void MarkDeclarationsReferencedInExpr(Expr *E,
3884 bool SkipLocalVariables = false);
3885
3886 /// \brief Try to recover by turning the given expression into a
3887 /// call. Returns true if recovery was attempted or an error was
3888 /// emitted; this may also leave the ExprResult invalid.
3889 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3890 bool ForceComplain = false,
3891 bool (*IsPlausibleResult)(QualType) = nullptr);
3892
3893 /// \brief Figure out if an expression could be turned into a call.
3894 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3895 UnresolvedSetImpl &NonTemplateOverloads);
3896
3897 /// \brief Conditionally issue a diagnostic based on the current
3898 /// evaluation context.
3899 ///
3900 /// \param Statement If Statement is non-null, delay reporting the
3901 /// diagnostic until the function body is parsed, and then do a basic
3902 /// reachability analysis to determine if the statement is reachable.
3903 /// If it is unreachable, the diagnostic will not be emitted.
3904 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3905 const PartialDiagnostic &PD);
3906
3907 // Primary Expressions.
3908 SourceRange getExprRange(Expr *E) const;
3909
3910 ExprResult ActOnIdExpression(
3911 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3912 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3913 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3914 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3915
3916 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3917 TemplateArgumentListInfo &Buffer,
3918 DeclarationNameInfo &NameInfo,
3919 const TemplateArgumentListInfo *&TemplateArgs);
3920
3921 bool
3922 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3923 std::unique_ptr<CorrectionCandidateCallback> CCC,
3924 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3925 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3926
3927 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3928 IdentifierInfo *II,
3929 bool AllowBuiltinCreation=false);
3930
3931 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3932 SourceLocation TemplateKWLoc,
3933 const DeclarationNameInfo &NameInfo,
3934 bool isAddressOfOperand,
3935 const TemplateArgumentListInfo *TemplateArgs);
3936
3937 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3938 ExprValueKind VK,
3939 SourceLocation Loc,
3940 const CXXScopeSpec *SS = nullptr);
3941 ExprResult
3942 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3943 const DeclarationNameInfo &NameInfo,
3944 const CXXScopeSpec *SS = nullptr,
3945 NamedDecl *FoundD = nullptr,
3946 const TemplateArgumentListInfo *TemplateArgs = nullptr);
3947 ExprResult
3948 BuildAnonymousStructUnionMemberReference(
3949 const CXXScopeSpec &SS,
3950 SourceLocation nameLoc,
3951 IndirectFieldDecl *indirectField,
3952 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3953 Expr *baseObjectExpr = nullptr,
3954 SourceLocation opLoc = SourceLocation());
3955
3956 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3957 SourceLocation TemplateKWLoc,
3958 LookupResult &R,
3959 const TemplateArgumentListInfo *TemplateArgs,
3960 const Scope *S);
3961 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3962 SourceLocation TemplateKWLoc,
3963 LookupResult &R,
3964 const TemplateArgumentListInfo *TemplateArgs,
3965 bool IsDefiniteInstance,
3966 const Scope *S);
3967 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3968 const LookupResult &R,
3969 bool HasTrailingLParen);
3970
3971 ExprResult
3972 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3973 const DeclarationNameInfo &NameInfo,
3974 bool IsAddressOfOperand, const Scope *S,
3975 TypeSourceInfo **RecoveryTSI = nullptr);
3976
3977 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3978 SourceLocation TemplateKWLoc,
3979 const DeclarationNameInfo &NameInfo,
3980 const TemplateArgumentListInfo *TemplateArgs);
3981
3982 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3983 LookupResult &R,
3984 bool NeedsADL,
3985 bool AcceptInvalidDecl = false);
3986 ExprResult BuildDeclarationNameExpr(
3987 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3988 NamedDecl *FoundD = nullptr,
3989 const TemplateArgumentListInfo *TemplateArgs = nullptr,
3990 bool AcceptInvalidDecl = false);
3991
3992 ExprResult BuildLiteralOperatorCall(LookupResult &R,
3993 DeclarationNameInfo &SuffixInfo,
3994 ArrayRef<Expr *> Args,
3995 SourceLocation LitEndLoc,
3996 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3997
3998 ExprResult BuildPredefinedExpr(SourceLocation Loc,
3999 PredefinedExpr::IdentType IT);
4000 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4001 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4002
4003 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4004
4005 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4006 ExprResult ActOnCharacterConstant(const Token &Tok,
4007 Scope *UDLScope = nullptr);
4008 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4009 ExprResult ActOnParenListExpr(SourceLocation L,
4010 SourceLocation R,
4011 MultiExprArg Val);
4012
4013 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4014 /// fragments (e.g. "foo" "bar" L"baz").
4015 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4016 Scope *UDLScope = nullptr);
4017
4018 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4019 SourceLocation DefaultLoc,
4020 SourceLocation RParenLoc,
4021 Expr *ControllingExpr,
4022 ArrayRef<ParsedType> ArgTypes,
4023 ArrayRef<Expr *> ArgExprs);
4024 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4025 SourceLocation DefaultLoc,
4026 SourceLocation RParenLoc,
4027 Expr *ControllingExpr,
4028 ArrayRef<TypeSourceInfo *> Types,
4029 ArrayRef<Expr *> Exprs);
4030
4031 // Binary/Unary Operators. 'Tok' is the token for the operator.
4032 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4033 Expr *InputExpr);
4034 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4035 UnaryOperatorKind Opc, Expr *Input);
4036 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4037 tok::TokenKind Op, Expr *Input);
4038
4039 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4040
4041 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4042 SourceLocation OpLoc,
4043 UnaryExprOrTypeTrait ExprKind,
4044 SourceRange R);
4045 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4046 UnaryExprOrTypeTrait ExprKind);
4047 ExprResult
4048 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4049 UnaryExprOrTypeTrait ExprKind,
4050 bool IsType, void *TyOrEx,
4051 SourceRange ArgRange);
4052
4053 ExprResult CheckPlaceholderExpr(Expr *E);
4054 bool CheckVecStepExpr(Expr *E);
4055
4056 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4057 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4058 SourceRange ExprRange,
4059 UnaryExprOrTypeTrait ExprKind);
4060 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4061 SourceLocation OpLoc,
4062 IdentifierInfo &Name,
4063 SourceLocation NameLoc,
4064 SourceLocation RParenLoc);
4065 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4066 tok::TokenKind Kind, Expr *Input);
4067
4068 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4069 Expr *Idx, SourceLocation RLoc);
4070 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4071 Expr *Idx, SourceLocation RLoc);
4072 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4073 Expr *LowerBound, SourceLocation ColonLoc,
4074 Expr *Length, SourceLocation RBLoc);
4075
4076 // This struct is for use by ActOnMemberAccess to allow
4077 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4078 // changing the access operator from a '.' to a '->' (to see if that is the
4079 // change needed to fix an error about an unknown member, e.g. when the class
4080 // defines a custom operator->).
4081 struct ActOnMemberAccessExtraArgs {
4082 Scope *S;
4083 UnqualifiedId &Id;
4084 Decl *ObjCImpDecl;
4085 };
4086
4087 ExprResult BuildMemberReferenceExpr(
4088 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4089 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4090 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4091 const TemplateArgumentListInfo *TemplateArgs,
4092 const Scope *S,
4093 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4094
4095 ExprResult
4096 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4097 bool IsArrow, const CXXScopeSpec &SS,
4098 SourceLocation TemplateKWLoc,
4099 NamedDecl *FirstQualifierInScope, LookupResult &R,
4100 const TemplateArgumentListInfo *TemplateArgs,
4101 const Scope *S,
4102 bool SuppressQualifierCheck = false,
4103 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4104
4105 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4106 SourceLocation OpLoc,
4107 const CXXScopeSpec &SS, FieldDecl *Field,
4108 DeclAccessPair FoundDecl,
4109 const DeclarationNameInfo &MemberNameInfo);
4110
4111 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4112
4113 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4114 const CXXScopeSpec &SS,
4115 const LookupResult &R);
4116
4117 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4118 bool IsArrow, SourceLocation OpLoc,
4119 const CXXScopeSpec &SS,
4120 SourceLocation TemplateKWLoc,
4121 NamedDecl *FirstQualifierInScope,
4122 const DeclarationNameInfo &NameInfo,
4123 const TemplateArgumentListInfo *TemplateArgs);
4124
4125 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4126 SourceLocation OpLoc,
4127 tok::TokenKind OpKind,
4128 CXXScopeSpec &SS,
4129 SourceLocation TemplateKWLoc,
4130 UnqualifiedId &Member,
4131 Decl *ObjCImpDecl);
4132
4133 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4134 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4135 FunctionDecl *FDecl,
4136 const FunctionProtoType *Proto,
4137 ArrayRef<Expr *> Args,
4138 SourceLocation RParenLoc,
4139 bool ExecConfig = false);
4140 void CheckStaticArrayArgument(SourceLocation CallLoc,
4141 ParmVarDecl *Param,
4142 const Expr *ArgExpr);
4143
4144 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4145 /// This provides the location of the left/right parens and a list of comma
4146 /// locations.
4147 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4148 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4149 Expr *ExecConfig = nullptr,
4150 bool IsExecConfig = false);
4151 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4152 SourceLocation LParenLoc,
4153 ArrayRef<Expr *> Arg,
4154 SourceLocation RParenLoc,
4155 Expr *Config = nullptr,
4156 bool IsExecConfig = false);
4157
4158 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4159 MultiExprArg ExecConfig,
4160 SourceLocation GGGLoc);
4161
4162 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4163 Declarator &D, ParsedType &Ty,
4164 SourceLocation RParenLoc, Expr *CastExpr);
4165 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4166 TypeSourceInfo *Ty,
4167 SourceLocation RParenLoc,
4168 Expr *Op);
4169 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4170
4171 /// \brief Build an altivec or OpenCL literal.
4172 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4173 SourceLocation RParenLoc, Expr *E,
4174 TypeSourceInfo *TInfo);
4175
4176 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4177
4178 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4179 ParsedType Ty,
4180 SourceLocation RParenLoc,
4181 Expr *InitExpr);
4182
4183 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4184 TypeSourceInfo *TInfo,
4185 SourceLocation RParenLoc,
4186 Expr *LiteralExpr);
4187
4188 ExprResult ActOnInitList(SourceLocation LBraceLoc,
4189 MultiExprArg InitArgList,
4190 SourceLocation RBraceLoc);
4191
4192 ExprResult ActOnDesignatedInitializer(Designation &Desig,
4193 SourceLocation Loc,
4194 bool GNUSyntax,
4195 ExprResult Init);
4196
4197private:
4198 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4199
4200public:
4201 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4202 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4203 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4204 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4205 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4206 Expr *LHSExpr, Expr *RHSExpr);
4207
4208 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4209
4210 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4211 /// in the case of a the GNU conditional expr extension.
4212 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4213 SourceLocation ColonLoc,
4214 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4215
4216 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4217 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4218 LabelDecl *TheDecl);
4219
4220 void ActOnStartStmtExpr();
4221 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4222 SourceLocation RPLoc); // "({..})"
4223 void ActOnStmtExprError();
4224
4225 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4226 struct OffsetOfComponent {
4227 SourceLocation LocStart, LocEnd;
4228 bool isBrackets; // true if [expr], false if .ident
4229 union {
4230 IdentifierInfo *IdentInfo;
4231 Expr *E;
4232 } U;
4233 };
4234
4235 /// __builtin_offsetof(type, a.b[123][456].c)
4236 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4237 TypeSourceInfo *TInfo,
4238 ArrayRef<OffsetOfComponent> Components,
4239 SourceLocation RParenLoc);
4240 ExprResult ActOnBuiltinOffsetOf(Scope *S,
4241 SourceLocation BuiltinLoc,
4242 SourceLocation TypeLoc,
4243 ParsedType ParsedArgTy,
4244 ArrayRef<OffsetOfComponent> Components,
4245 SourceLocation RParenLoc);
4246
4247 // __builtin_choose_expr(constExpr, expr1, expr2)
4248 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4249 Expr *CondExpr, Expr *LHSExpr,
4250 Expr *RHSExpr, SourceLocation RPLoc);
4251
4252 // __builtin_va_arg(expr, type)
4253 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4254 SourceLocation RPLoc);
4255 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4256 TypeSourceInfo *TInfo, SourceLocation RPLoc);
4257
4258 // __null
4259 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4260
4261 bool CheckCaseExpression(Expr *E);
4262
4263 /// \brief Describes the result of an "if-exists" condition check.
4264 enum IfExistsResult {
4265 /// \brief The symbol exists.
4266 IER_Exists,
4267
4268 /// \brief The symbol does not exist.
4269 IER_DoesNotExist,
4270
4271 /// \brief The name is a dependent name, so the results will differ
4272 /// from one instantiation to the next.
4273 IER_Dependent,
4274
4275 /// \brief An error occurred.
4276 IER_Error
4277 };
4278
4279 IfExistsResult
4280 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4281 const DeclarationNameInfo &TargetNameInfo);
4282
4283 IfExistsResult
4284 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4285 bool IsIfExists, CXXScopeSpec &SS,
4286 UnqualifiedId &Name);
4287
4288 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4289 bool IsIfExists,
4290 NestedNameSpecifierLoc QualifierLoc,
4291 DeclarationNameInfo NameInfo,
4292 Stmt *Nested);
4293 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4294 bool IsIfExists,
4295 CXXScopeSpec &SS, UnqualifiedId &Name,
4296 Stmt *Nested);
4297
4298 //===------------------------- "Block" Extension ------------------------===//
4299
4300 /// ActOnBlockStart - This callback is invoked when a block literal is
4301 /// started.
4302 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4303
4304 /// ActOnBlockArguments - This callback allows processing of block arguments.
4305 /// If there are no arguments, this is still invoked.
4306 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4307 Scope *CurScope);
4308
4309 /// ActOnBlockError - If there is an error parsing a block, this callback
4310 /// is invoked to pop the information about the block from the action impl.
4311 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4312
4313 /// ActOnBlockStmtExpr - This is called when the body of a block statement
4314 /// literal was successfully completed. ^(int x){...}
4315 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4316 Scope *CurScope);
4317
4318 //===---------------------------- Clang Extensions ----------------------===//
4319
4320 /// __builtin_convertvector(...)
4321 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4322 SourceLocation BuiltinLoc,
4323 SourceLocation RParenLoc);
4324
4325 //===---------------------------- OpenCL Features -----------------------===//
4326
4327 /// __builtin_astype(...)
4328 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4329 SourceLocation BuiltinLoc,
4330 SourceLocation RParenLoc);
4331
4332 //===---------------------------- C++ Features --------------------------===//
4333
4334 // Act on C++ namespaces
4335 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4336 SourceLocation NamespaceLoc,
4337 SourceLocation IdentLoc,
4338 IdentifierInfo *Ident,
4339 SourceLocation LBrace,
4340 AttributeList *AttrList,
4341 UsingDirectiveDecl * &UsingDecl);
4342 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4343
4344 NamespaceDecl *getStdNamespace() const;
4345 NamespaceDecl *getOrCreateStdNamespace();
4346
4347 NamespaceDecl *lookupStdExperimentalNamespace();
4348
4349 CXXRecordDecl *getStdBadAlloc() const;
4350 EnumDecl *getStdAlignValT() const;
4351
4352 /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4353 /// it is and Element is not NULL, assigns the element type to Element.
4354 bool isStdInitializerList(QualType Ty, QualType *Element);
4355
4356 /// \brief Looks for the std::initializer_list template and instantiates it
4357 /// with Element, or emits an error if it's not found.
4358 ///
4359 /// \returns The instantiated template, or null on error.
4360 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4361
4362 /// \brief Determine whether Ctor is an initializer-list constructor, as
4363 /// defined in [dcl.init.list]p2.
4364 bool isInitListConstructor(const FunctionDecl *Ctor);
4365
4366 Decl *ActOnUsingDirective(Scope *CurScope,
4367 SourceLocation UsingLoc,
4368 SourceLocation NamespcLoc,
4369 CXXScopeSpec &SS,
4370 SourceLocation IdentLoc,
4371 IdentifierInfo *NamespcName,
4372 AttributeList *AttrList);
4373
4374 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4375
4376 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4377 SourceLocation NamespaceLoc,
4378 SourceLocation AliasLoc,
4379 IdentifierInfo *Alias,
4380 CXXScopeSpec &SS,
4381 SourceLocation IdentLoc,
4382 IdentifierInfo *Ident);
4383
4384 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4385 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4386 const LookupResult &PreviousDecls,
4387 UsingShadowDecl *&PrevShadow);
4388 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4389 NamedDecl *Target,
4390 UsingShadowDecl *PrevDecl);
4391
4392 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4393 bool HasTypenameKeyword,
4394 const CXXScopeSpec &SS,
4395 SourceLocation NameLoc,
4396 const LookupResult &Previous);
4397 bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4398 bool HasTypename,
4399 const CXXScopeSpec &SS,
4400 const DeclarationNameInfo &NameInfo,
4401 SourceLocation NameLoc);
4402
4403 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4404 SourceLocation UsingLoc,
4405 bool HasTypenameKeyword,
4406 SourceLocation TypenameLoc,
4407 CXXScopeSpec &SS,
4408 DeclarationNameInfo NameInfo,
4409 SourceLocation EllipsisLoc,
4410 AttributeList *AttrList,
4411 bool IsInstantiation);
4412 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4413 ArrayRef<NamedDecl *> Expansions);
4414
4415 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4416
4417 /// Given a derived-class using shadow declaration for a constructor and the
4418 /// correspnding base class constructor, find or create the implicit
4419 /// synthesized derived class constructor to use for this initialization.
4420 CXXConstructorDecl *
4421 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4422 ConstructorUsingShadowDecl *DerivedShadow);
4423
4424 Decl *ActOnUsingDeclaration(Scope *CurScope,
4425 AccessSpecifier AS,
4426 SourceLocation UsingLoc,
4427 SourceLocation TypenameLoc,
4428 CXXScopeSpec &SS,
4429 UnqualifiedId &Name,
4430 SourceLocation EllipsisLoc,
4431 AttributeList *AttrList);
4432 Decl *ActOnAliasDeclaration(Scope *CurScope,
4433 AccessSpecifier AS,
4434 MultiTemplateParamsArg TemplateParams,
4435 SourceLocation UsingLoc,
4436 UnqualifiedId &Name,
4437 AttributeList *AttrList,
4438 TypeResult Type,
4439 Decl *DeclFromDeclSpec);
4440
4441 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4442 /// including handling of its default argument expressions.
4443 ///
4444 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4445 ExprResult
4446 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4447 NamedDecl *FoundDecl,
4448 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4449 bool HadMultipleCandidates, bool IsListInitialization,
4450 bool IsStdInitListInitialization,
4451 bool RequiresZeroInit, unsigned ConstructKind,
4452 SourceRange ParenRange);
4453
4454 /// Build a CXXConstructExpr whose constructor has already been resolved if
4455 /// it denotes an inherited constructor.
4456 ExprResult
4457 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4458 CXXConstructorDecl *Constructor, bool Elidable,
4459 MultiExprArg Exprs,
4460 bool HadMultipleCandidates, bool IsListInitialization,
4461 bool IsStdInitListInitialization,
4462 bool RequiresZeroInit, unsigned ConstructKind,
4463 SourceRange ParenRange);
4464
4465 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4466 // the constructor can be elidable?
4467 ExprResult
4468 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4469 NamedDecl *FoundDecl,
4470 CXXConstructorDecl *Constructor, bool Elidable,
4471 MultiExprArg Exprs, bool HadMultipleCandidates,
4472 bool IsListInitialization,
4473 bool IsStdInitListInitialization, bool RequiresZeroInit,
4474 unsigned ConstructKind, SourceRange ParenRange);
4475
4476 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4477
4478
4479 /// Instantiate or parse a C++ default argument expression as necessary.
4480 /// Return true on error.
4481 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4482 ParmVarDecl *Param);
4483
4484 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4485 /// the default expr if needed.
4486 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4487 FunctionDecl *FD,
4488 ParmVarDecl *Param);
4489
4490 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4491 /// constructed variable.
4492 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4493
4494 /// \brief Helper class that collects exception specifications for
4495 /// implicitly-declared special member functions.
4496 class ImplicitExceptionSpecification {
4497 // Pointer to allow copying
4498 Sema *Self;
4499 // We order exception specifications thus:
4500 // noexcept is the most restrictive, but is only used in C++11.
4501 // throw() comes next.
4502 // Then a throw(collected exceptions)
4503 // Finally no specification, which is expressed as noexcept(false).
4504 // throw(...) is used instead if any called function uses it.
4505 ExceptionSpecificationType ComputedEST;
4506 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4507 SmallVector<QualType, 4> Exceptions;
4508
4509 void ClearExceptions() {
4510 ExceptionsSeen.clear();
4511 Exceptions.clear();
4512 }
4513
4514 public:
4515 explicit ImplicitExceptionSpecification(Sema &Self)
4516 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4517 if (!Self.getLangOpts().CPlusPlus11)
4518 ComputedEST = EST_DynamicNone;
4519 }
4520
4521 /// \brief Get the computed exception specification type.
4522 ExceptionSpecificationType getExceptionSpecType() const {
4523 assert(ComputedEST != EST_ComputedNoexcept &&((ComputedEST != EST_ComputedNoexcept && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 4524, __PRETTY_FUNCTION__))
4524 "noexcept(expr) should not be a possible result")((ComputedEST != EST_ComputedNoexcept && "noexcept(expr) should not be a possible result"
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_ComputedNoexcept && \"noexcept(expr) should not be a possible result\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn298304/tools/clang/include/clang/Sema/Sema.h"
, 4524, __PRETTY_FUNCTION__))
;
4525 return ComputedEST;
4526 }
4527
4528 /// \brief The number of exceptions in the exception specification.
4529 unsigned size() const { return Exceptions.size(); }
4530
4531 /// \brief The set of exceptions in the exception specification.
4532 const QualType *data() const { return Exceptions.data(); }
4533
4534 /// \brief Integrate another called method into the collected data.
4535 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4536
4537 /// \brief Integrate an invoked expression into the collected data.
4538 void CalledExpr(Expr *E);
4539
4540 /// \brief Overwrite an EPI's exception specification with this
4541 /// computed exception specification.
4542 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4543 FunctionProtoType::ExceptionSpecInfo ESI;
4544 ESI.Type = getExceptionSpecType();
4545 if (ESI.Type == EST_Dynamic) {
4546 ESI.Exceptions = Exceptions;
4547 } else if (ESI.Type == EST_None) {
4548 /// C++11 [except.spec]p14:
4549 /// The exception-specification is noexcept(false) if the set of
4550 /// potential exceptions of the special member function contains "any"
4551 ESI.Type = EST_ComputedNoexcept;
4552 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4553 tok::kw_false).get();
4554 }
4555 return ESI;
4556 }
4557 };
4558
4559 /// \brief Determine what sort of exception specification a defaulted
4560 /// copy constructor of a class will have.
4561 ImplicitExceptionSpecification
4562 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4563 CXXMethodDecl *MD);
4564
4565 /// \brief Determine what sort of exception specification a defaulted
4566 /// default constructor of a class will have, and whether the parameter
4567 /// will be const.
4568 ImplicitExceptionSpecification
4569 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4570
4571 /// \brief Determine what sort of exception specification a defautled
4572 /// copy assignment operator of a class will have, and whether the
4573 /// parameter will be const.
4574 ImplicitExceptionSpecification
4575 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4576
4577 /// \brief Determine what sort of exception specification a defaulted move
4578 /// constructor of a class will have.
4579 ImplicitExceptionSpecification
4580 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4581
4582 /// \brief Determine what sort of exception specification a defaulted move
4583 /// assignment operator of a class will have.
4584 ImplicitExceptionSpecification
4585 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4586
4587 /// \brief Determine what sort of exception specification a defaulted
4588 /// destructor of a class will have.
4589 ImplicitExceptionSpecification
4590 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4591
4592 /// \brief Determine what sort of exception specification an inheriting
4593 /// constructor of a class will have.
4594 ImplicitExceptionSpecification
4595 ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4596 CXXConstructorDecl *CD);
4597
4598 /// \brief Evaluate the implicit exception specification for a defaulted
4599 /// special member function.
4600 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4601
4602 /// \brief Check the given exception-specification and update the
4603 /// exception specification information with the results.
4604 void checkExceptionSpecification(bool IsTopLevel,
4605 ExceptionSpecificationType EST,
4606 ArrayRef<ParsedType> DynamicExceptions,
4607 ArrayRef<SourceRange> DynamicExceptionRanges,
4608 Expr *NoexceptExpr,
4609 SmallVectorImpl<QualType> &Exceptions,
4610 FunctionProtoType::ExceptionSpecInfo &ESI);
4611
4612 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4613 /// parse an exception specification to work around a libstdc++ bug.
4614 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4615
4616 /// \brief Add an exception-specification to the given member function
4617 /// (or member function template). The exception-specification was parsed
4618 /// after the method itself was declared.
4619 void actOnDelayedExceptionSpecification(Decl *Method,
4620 ExceptionSpecificationType EST,
4621 SourceRange SpecificationRange,
4622 ArrayRef<ParsedType> DynamicExceptions,
4623 ArrayRef<SourceRange> DynamicExceptionRanges,
4624 Expr *NoexceptExpr);
4625
4626 class InheritedConstructorInfo;
4627
4628 /// \brief Determine if a special member function should have a deleted
4629 /// definition when it is defaulted.
4630 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4631 InheritedConstructorInfo *ICI = nullptr,
4632 bool Diagnose = false);
4633
4634 /// \brief Declare the implicit default constructor for the given class.
4635 ///
4636 /// \param ClassDecl The class declaration into which the implicit
4637 /// default constructor will be added.
4638 ///
4639 /// \returns The implicitly-declared default constructor.
4640 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4641 CXXRecordDecl *ClassDecl);
4642
4643 /// DefineImplicitDefaultConstructor - Checks for feasibility of
4644 /// defining this constructor as the default constructor.
4645 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4646 CXXConstructorDecl *Constructor);
4647
4648 /// \brief Declare the implicit destructor for the given class.
4649 ///
4650 /// \param ClassDecl The class declaration into which the implicit
4651 /// destructor will be added.
4652 ///
4653 /// \returns The implicitly-declared destructor.
4654 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4655
4656 /// DefineImplicitDestructor - Checks for feasibility of
4657 /// defining this destructor as the default destructor.
4658 void DefineImplicitDestructor(SourceLocation CurrentLocation,
4659 CXXDestructorDecl *Destructor);
4660
4661 /// \brief Build an exception spec for destructors that don't have one.
4662 ///
4663 /// C++11 says that user-defined destructors with no exception spec get one
4664 /// that looks as if the destructor was implicitly declared.
4665 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4666 CXXDestructorDecl *Destructor);
4667
4668 /// \brief Define the specified inheriting constructor.
4669 void DefineInheritingConstructor(SourceLocation UseLoc,
4670 CXXConstructorDecl *Constructor);
4671
4672 /// \brief Declare the implicit copy constructor for the given class.
4673 ///
4674 /// \param ClassDecl The class declaration into which the implicit
4675 /// copy constructor will be added.
4676 ///
4677 /// \returns The implicitly-declared copy constructor.
4678 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4679
4680 /// DefineImplicitCopyConstructor - Checks for feasibility of
4681 /// defining this constructor as the copy constructor.
4682 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4683 CXXConstructorDecl *Constructor);
4684
4685 /// \brief Declare the implicit move constructor for the given class.
4686 ///
4687 /// \param ClassDecl The Class declaration into which the implicit
4688 /// move constructor will be added.
4689 ///
4690 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4691 /// declared.
4692 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4693
4694 /// DefineImplicitMoveConstructor - Checks for feasibility of
4695 /// defining this constructor as the move constructor.
4696 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4697 CXXConstructorDecl *Constructor);
4698
4699 /// \brief Declare the implicit copy assignment operator for the given class.
4700 ///
4701 /// \param ClassDecl The class declaration into which the implicit
4702 /// copy assignment operator will be added.
4703 ///
4704 /// \returns The implicitly-declared copy assignment operator.
4705 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4706
4707 /// \brief Defines an implicitly-declared copy assignment operator.
4708 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4709 CXXMethodDecl *MethodDecl);
4710
4711 /// \brief Declare the implicit move assignment operator for the given class.
4712 ///
4713 /// \param ClassDecl The Class declaration into which the implicit
4714 /// move assignment operator will be added.
4715 ///
4716 /// \returns The implicitly-declared move assignment operator, or NULL if it
4717 /// wasn't declared.
4718 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4719
4720 /// \brief Defines an implicitly-declared move assignment operator.
4721 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4722 CXXMethodDecl *MethodDecl);
4723
4724 /// \brief Force the declaration of any implicitly-declared members of this
4725 /// class.
4726 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4727
4728 /// \brief Check a completed declaration of an implicit special member.
4729 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4730
4731 /// \brief Determine whether the given function is an implicitly-deleted
4732 /// special member function.
4733 bool isImplicitlyDeleted(FunctionDecl *FD);
4734
4735 /// \brief Check whether 'this' shows up in the type of a static member
4736 /// function after the (naturally empty) cv-qualifier-seq would be.
4737 ///
4738 /// \returns true if an error occurred.
4739 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4740
4741 /// \brief Whether this' shows up in the exception specification of a static
4742 /// member function.
4743 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4744
4745 /// \brief Check whether 'this' shows up in the attributes of the given
4746 /// static member function.
4747 ///
4748 /// \returns true if an error occurred.
4749 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4750
4751 /// MaybeBindToTemporary - If the passed in expression has a record type with
4752 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4753 /// it simply returns the passed in expression.
4754 ExprResult MaybeBindToTemporary(Expr *E);
4755
4756 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4757 MultiExprArg ArgsPtr,
4758 SourceLocation Loc,
4759 SmallVectorImpl<Expr*> &ConvertedArgs,
4760 bool AllowExplicit = false,
4761 bool IsListInitialization = false);
4762
4763 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4764 SourceLocation NameLoc,
4765 IdentifierInfo &Name);
4766
4767 ParsedType getDestructorName(SourceLocation TildeLoc,
4768 IdentifierInfo &II, SourceLocation NameLoc,
4769 Scope *S, CXXScopeSpec &SS,
4770 ParsedType ObjectType,
4771 bool EnteringContext);
4772
4773 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4774 ParsedType ObjectType);
4775
4776 // Checks that reinterpret casts don't have undefined behavior.
4777 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4778 bool IsDereference, SourceRange Range);
4779
4780 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4781 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4782 tok::TokenKind Kind,
4783 SourceLocation LAngleBracketLoc,
4784 Declarator &D,
4785 SourceLocation RAngleBracketLoc,
4786 SourceLocation LParenLoc,
4787 Expr *E,
4788 SourceLocation RParenLoc);
4789
4790 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4791 tok::TokenKind Kind,
4792 TypeSourceInfo *Ty,
4793 Expr *E,
4794 SourceRange AngleBrackets,
4795 SourceRange Parens);
4796
4797 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4798 SourceLocation TypeidLoc,
4799 TypeSourceInfo *Operand,
4800 SourceLocation RParenLoc);
4801 ExprResult BuildCXXTypeId(QualType TypeInfoType,
4802 SourceLocation TypeidLoc,
4803 Expr *Operand,
4804 SourceLocation RParenLoc);
4805
4806 /// ActOnCXXTypeid - Parse typeid( something ).
4807 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4808 SourceLocation LParenLoc, bool isType,
4809 void *TyOrExpr,
4810 SourceLocation RParenLoc);
4811
4812 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4813 SourceLocation TypeidLoc,
4814 TypeSourceInfo *Operand,
4815 SourceLocation RParenLoc);
4816 ExprResult BuildCXXUuidof(QualType TypeInfoType,
4817 SourceLocation TypeidLoc,
4818 Expr *Operand,
4819 SourceLocation RParenLoc);
4820
4821 /// ActOnCXXUuidof - Parse __uuidof( something ).
4822 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4823 SourceLocation LParenLoc, bool isType,
4824 void *TyOrExpr,
4825 SourceLocation RParenLoc);
4826
4827 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4828 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4829 tok::TokenKind Operator,
4830 SourceLocation EllipsisLoc, Expr *RHS,
4831 SourceLocation RParenLoc);
4832 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4833 BinaryOperatorKind Operator,
4834 SourceLocation EllipsisLoc, Expr *RHS,
4835 SourceLocation RParenLoc);
4836 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4837 BinaryOperatorKind Operator);
4838
4839 //// ActOnCXXThis - Parse 'this' pointer.
4840 ExprResult ActOnCXXThis(SourceLocation loc);
4841
4842 /// \brief Try to retrieve the type of the 'this' pointer.
4843 ///
4844 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4845 QualType getCurrentThisType();
4846
4847 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4848 /// current context not being a non-static member function. In such cases,
4849 /// this provides the type used for 'this'.
4850 QualType CXXThisTypeOverride;
4851
4852 /// \brief RAII object used to temporarily allow the C++ 'this' expression
4853 /// to be used, with the given qualifiers on the current class type.
4854 class CXXThisScopeRAII {
4855 Sema &S;
4856 QualType OldCXXThisTypeOverride;
4857 bool Enabled;
4858
4859 public:
4860 /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4861 /// using the given declaration (which is either a class template or a
4862 /// class) along with the given qualifiers.
4863 /// along with the qualifiers placed on '*this'.
4864 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4865 bool Enabled = true);
4866
4867 ~CXXThisScopeRAII();
4868 };
4869
4870 /// \brief Make sure the value of 'this' is actually available in the current
4871 /// context, if it is a potentially evaluated context.
4872 ///
4873 /// \param Loc The location at which the capture of 'this' occurs.
4874 ///
4875 /// \param Explicit Whether 'this' is explicitly captured in a lambda
4876 /// capture list.
4877 ///
4878 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4879 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4880 /// This is useful when enclosing lambdas must speculatively capture
4881 /// 'this' that may or may not be used in certain specializations of
4882 /// a nested generic lambda (depending on whether the name resolves to
4883 /// a non-static member function or a static function).
4884 /// \return returns 'true' if failed, 'false' if success.
4885 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4886 bool BuildAndDiagnose = true,
4887 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4888 bool ByCopy = false);
4889
4890 /// \brief Determine whether the given type is the type of *this that is used
4891 /// outside of the body of a member function for a type that is currently
4892 /// being defined.
4893 bool isThisOutsideMemberFunctionBody(QualType BaseType);
4894
4895 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4896 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4897
4898
4899 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4900 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4901
4902 ExprResult
4903 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4904 SourceLocation AtLoc, SourceLocation RParen);
4905
4906 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4907 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4908
4909 //// ActOnCXXThrow - Parse throw expressions.
4910 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4911 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4912 bool IsThrownVarInScope);
4913 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4914
4915 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4916 /// Can be interpreted either as function-style casting ("int(x)")
4917 /// or class type construction ("ClassType(x,y,z)")
4918 /// or creation of a value-initialized type ("int()").
4919 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4920 SourceLocation LParenLoc,
4921 MultiExprArg Exprs,
4922 SourceLocation RParenLoc);
4923
4924 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4925 SourceLocation LParenLoc,
4926 MultiExprArg Exprs,
4927 SourceLocation RParenLoc);
4928
4929 /// ActOnCXXNew - Parsed a C++ 'new' expression.
4930 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4931 SourceLocation PlacementLParen,
4932 MultiExprArg PlacementArgs,
4933 SourceLocation PlacementRParen,
4934 SourceRange TypeIdParens, Declarator &D,
4935 Expr *Initializer);
4936 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4937 SourceLocation PlacementLParen,
4938 MultiExprArg PlacementArgs,
4939 SourceLocation PlacementRParen,
4940 SourceRange TypeIdParens,
4941 QualType AllocType,
4942 TypeSourceInfo *AllocTypeInfo,
4943 Expr *ArraySize,
4944 SourceRange DirectInitRange,
4945 Expr *Initializer);
4946
4947 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4948 SourceRange R);
4949 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4950 bool UseGlobal, QualType AllocType, bool IsArray,
4951 bool &PassAlignment, MultiExprArg PlaceArgs,
4952 FunctionDecl *&OperatorNew,
4953 FunctionDecl *&OperatorDelete);
4954 void DeclareGlobalNewDelete();
4955 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4956 ArrayRef<QualType> Params);
4957
4958 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4959 DeclarationName Name, FunctionDecl* &Operator,
4960 bool Diagnose = true);
4961 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4962 bool CanProvideSize,
4963 bool Overaligned,
4964 DeclarationName Name);
4965 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
4966 CXXRecordDecl *RD);
4967
4968 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4969 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4970 bool UseGlobal, bool ArrayForm,
4971 Expr *Operand);
4972 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4973 bool IsDelete, bool CallCanBeVirtual,
4974 bool WarnOnNonAbstractTypes,
4975 SourceLocation DtorLoc);
4976
4977 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4978 Expr *Operand, SourceLocation RParen);
4979 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4980 SourceLocation RParen);
4981
4982 /// \brief Parsed one of the type trait support pseudo-functions.
4983 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4984 ArrayRef<ParsedType> Args,
4985 SourceLocation RParenLoc);
4986 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4987 ArrayRef<TypeSourceInfo *> Args,
4988 SourceLocation RParenLoc);
4989
4990 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
4991 /// pseudo-functions.
4992 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4993 SourceLocation KWLoc,
4994 ParsedType LhsTy,
4995 Expr *DimExpr,
4996 SourceLocation RParen);
4997
4998 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
4999 SourceLocation KWLoc,
5000 TypeSourceInfo *TSInfo,
5001 Expr *DimExpr,
5002 SourceLocation RParen);
5003
5004 /// ActOnExpressionTrait - Parsed one of the unary type trait support
5005 /// pseudo-functions.
5006 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5007 SourceLocation KWLoc,
5008 Expr *Queried,
5009 SourceLocation RParen);
5010
5011 ExprResult BuildExpressionTrait(ExpressionTrait OET,
5012 SourceLocation KWLoc,
5013 Expr *Queried,
5014 SourceLocation RParen);
5015
5016 ExprResult ActOnStartCXXMemberReference(Scope *S,
5017 Expr *Base,
5018 SourceLocation OpLoc,
5019 tok::TokenKind OpKind,
5020 ParsedType &ObjectType,
5021 bool &MayBePseudoDestructor);
5022
5023 ExprResult BuildPseudoDestructorExpr(Expr *Base,
5024 SourceLocation OpLoc,
5025 tok::TokenKind OpKind,
5026 const CXXScopeSpec &SS,
5027 TypeSourceInfo *ScopeType,
5028 SourceLocation CCLoc,
5029 SourceLocation TildeLoc,
5030 PseudoDestructorTypeStorage DestroyedType);
5031
5032 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5033 SourceLocation OpLoc,
5034 tok::TokenKind OpKind,
5035 CXXScopeSpec &SS,
5036 UnqualifiedId &FirstTypeName,
5037 SourceLocation CCLoc,
5038 SourceLocation TildeLoc,
5039 UnqualifiedId &SecondTypeName);
5040
5041 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5042 SourceLocation OpLoc,
5043 tok::TokenKind OpKind,
5044 SourceLocation TildeLoc,
5045 const DeclSpec& DS);
5046
5047 /// MaybeCreateExprWithCleanups - If the current full-expression
5048 /// requires any cleanups, surround it with a ExprWithCleanups node.
5049 /// Otherwise, just returns the passed-in expression.
5050 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5051 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5052 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5053
5054 MaterializeTemporaryExpr *
5055 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5056 bool BoundToLvalueReference);
5057
5058 ExprResult ActOnFinishFullExpr(Expr *Expr) {
5059 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5060 : SourceLocation());
5061 }
5062 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5063 bool DiscardedValue = false,
5064 bool IsConstexpr = false,
5065 bool IsLambdaInitCaptureInitializer = false);
5066 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5067
5068 // Marks SS invalid if it represents an incomplete type.
5069 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5070
5071 DeclContext *computeDeclContext(QualType T);
5072 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5073 bool EnteringContext = false);
5074 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5075 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5076
5077 /// \brief The parser has parsed a global nested-name-specifier '::'.
5078 ///
5079 /// \param CCLoc The location of the '::'.
5080 ///
5081 /// \param SS The nested-name-specifier, which will be updated in-place
5082 /// to reflect the parsed nested-name-specifier.
5083 ///
5084 /// \returns true if an error occurred, false otherwise.
5085 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5086
5087 /// \brief The parser has parsed a '__super' nested-name-specifier.
5088 ///
5089 /// \param SuperLoc The location of the '__super' keyword.
5090 ///
5091 /// \param ColonColonLoc The location of the '::'.
5092 ///
5093 /// \param SS The nested-name-specifier, which will be updated in-place
5094 /// to reflect the parsed nested-name-specifier.
5095 ///
5096 /// \returns true if an error occurred, false otherwise.
5097 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5098 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5099
5100 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5101 bool *CanCorrect = nullptr);
5102 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5103
5104 /// \brief Keeps information about an identifier in a nested-name-spec.
5105 ///
5106 struct NestedNameSpecInfo {
5107 /// \brief The type of the object, if we're parsing nested-name-specifier in
5108 /// a member access expression.
5109 ParsedType ObjectType;
5110
5111 /// \brief The identifier preceding the '::'.
5112 IdentifierInfo *Identifier;
5113
5114 /// \brief The location of the identifier.
5115 SourceLocation IdentifierLoc;
5116
5117 /// \brief The location of the '::'.
5118 SourceLocation CCLoc;
5119
5120 /// \brief Creates info object for the most typical case.
5121 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5122 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5123 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5124 CCLoc(ColonColonLoc) {
5125 }
5126
5127 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5128 SourceLocation ColonColonLoc, QualType ObjectType)
5129 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5130 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5131 }
5132 };
5133
5134 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5135 NestedNameSpecInfo &IdInfo);
5136
5137 bool BuildCXXNestedNameSpecifier(Scope *S,
5138 NestedNameSpecInfo &IdInfo,
5139 bool EnteringContext,
5140 CXXScopeSpec &SS,
5141 NamedDecl *ScopeLookupResult,
5142 bool ErrorRecoveryLookup,
5143 bool *IsCorrectedToColon = nullptr,
5144 bool OnlyNamespace = false);
5145
5146 /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5147 ///
5148 /// \param S The scope in which this nested-name-specifier occurs.
5149 ///
5150 /// \param IdInfo Parser information about an identifier in the
5151 /// nested-name-spec.
5152 ///
5153 /// \param EnteringContext Whether we're entering the context nominated by
5154 /// this nested-name-specifier.
5155 ///
5156 /// \param SS The nested-name-specifier, which is both an input
5157 /// parameter (the nested-name-specifier before this type) and an
5158 /// output parameter (containing the full nested-name-specifier,
5159 /// including this new type).
5160 ///
5161 /// \param ErrorRecoveryLookup If true, then this method is called to improve
5162 /// error recovery. In this case do not emit error message.
5163 ///
5164 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5165 /// are allowed. The bool value pointed by this parameter is set to 'true'
5166 /// if the identifier is treated as if it was followed by ':', not '::'.
5167 ///
5168 /// \param OnlyNamespace If true, only considers namespaces in lookup.
5169 ///
5170 /// \returns true if an error occurred, false otherwise.
5171 bool ActOnCXXNestedNameSpecifier(Scope *S,
5172 NestedNameSpecInfo &IdInfo,
5173 bool EnteringContext,
5174 CXXScopeSpec &SS,
5175 bool ErrorRecoveryLookup = false,
5176 bool *IsCorrectedToColon = nullptr,
5177 bool OnlyNamespace = false);
5178
5179 ExprResult ActOnDecltypeExpression(Expr *E);
5180
5181 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5182 const DeclSpec &DS,
5183 SourceLocation ColonColonLoc);
5184
5185 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5186 NestedNameSpecInfo &IdInfo,
5187 bool EnteringContext);
5188
5189 /// \brief The parser has parsed a nested-name-specifier
5190 /// 'template[opt] template-name < template-args >::'.
5191 ///
5192 /// \param S The scope in which this nested-name-specifier occurs.
5193 ///
5194 /// \param SS The nested-name-specifier, which is both an input
5195 /// parameter (the nested-name-specifier before this type) and an
5196 /// output parameter (containing the full nested-name-specifier,
5197 /// including this new type).
5198 ///
5199 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5200 /// \param TemplateName the template name.
5201 /// \param TemplateNameLoc The location of the template name.
5202 /// \param LAngleLoc The location of the opening angle bracket ('<').
5203 /// \param TemplateArgs The template arguments.
5204 /// \param RAngleLoc The location of the closing angle bracket ('>').
5205 /// \param CCLoc The location of the '::'.
5206 ///
5207 /// \param EnteringContext Whether we're entering the context of the
5208 /// nested-name-specifier.
5209 ///
5210 ///
5211 /// \returns true if an error occurred, false otherwise.
5212 bool ActOnCXXNestedNameSpecifier(Scope *S,
5213 CXXScopeSpec &SS,
5214 SourceLocation TemplateKWLoc,
5215 TemplateTy TemplateName,
5216 SourceLocation TemplateNameLoc,
5217 SourceLocation LAngleLoc,
5218 ASTTemplateArgsPtr TemplateArgs,
5219 SourceLocation RAngleLoc,
5220 SourceLocation CCLoc,
5221 bool EnteringContext);
5222
5223 /// \brief Given a C++ nested-name-specifier, produce an annotation value
5224 /// that the parser can use later to reconstruct the given
5225 /// nested-name-specifier.
5226 ///
5227 /// \param SS A nested-name-specifier.
5228 ///
5229 /// \returns A pointer containing all of the information in the
5230 /// nested-name-specifier \p SS.
5231 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5232
5233 /// \brief Given an annotation pointer for a nested-name-specifier, restore
5234 /// the nested-name-specifier structure.
5235 ///
5236 /// \param Annotation The annotation pointer, produced by
5237 /// \c SaveNestedNameSpecifierAnnotation().
5238 ///
5239 /// \param AnnotationRange The source range corresponding to the annotation.
5240 ///
5241 /// \param SS The nested-name-specifier that will be updated with the contents
5242 /// of the annotation pointer.
5243 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5244 SourceRange AnnotationRange,
5245 CXXScopeSpec &SS);
5246
5247 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5248
5249 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5250 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5251 /// After this method is called, according to [C++ 3.4.3p3], names should be
5252 /// looked up in the declarator-id's scope, until the declarator is parsed and
5253 /// ActOnCXXExitDeclaratorScope is called.
5254 /// The 'SS' should be a non-empty valid CXXScopeSpec.
5255 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5256
5257 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5258 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5259 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5260 /// Used to indicate that names should revert to being looked up in the
5261 /// defining scope.
5262 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5263
5264 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5265 /// initializer for the declaration 'Dcl'.
5266 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5267 /// static data member of class X, names should be looked up in the scope of
5268 /// class X.
5269 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5270
5271 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5272 /// initializer for the declaration 'Dcl'.
5273 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5274
5275 /// \brief Create a new lambda closure type.
5276 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5277 TypeSourceInfo *Info,
5278 bool KnownDependent,
5279 LambdaCaptureDefault CaptureDefault);
5280
5281 /// \brief Start the definition of a lambda expression.
5282 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5283 SourceRange IntroducerRange,
5284 TypeSourceInfo *MethodType,
5285 SourceLocation EndLoc,
5286 ArrayRef<ParmVarDecl *> Params,
5287 bool IsConstexprSpecified);
5288
5289 /// \brief Endow the lambda scope info with the relevant properties.
5290 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5291 CXXMethodDecl *CallOperator,
5292 SourceRange IntroducerRange,
5293 LambdaCaptureDefault CaptureDefault,
5294 SourceLocation CaptureDefaultLoc,
5295 bool ExplicitParams,
5296 bool ExplicitResultType,
5297 bool Mutable);
5298
5299 /// \brief Perform initialization analysis of the init-capture and perform
5300 /// any implicit conversions such as an lvalue-to-rvalue conversion if
5301 /// not being used to initialize a reference.
5302 ParsedType actOnLambdaInitCaptureInitialization(
5303 SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5304 LambdaCaptureInitKind InitKind, Expr *&Init) {
5305 return ParsedType::make(buildLambdaInitCaptureInitialization(
5306 Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5307 }
5308 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5309 IdentifierInfo *Id,
5310 bool DirectInit, Expr *&Init);
5311
5312 /// \brief Create a dummy variable within the declcontext of the lambda's
5313 /// call operator, for name lookup purposes for a lambda init capture.
5314 ///
5315 /// CodeGen handles emission of lambda captures, ignoring these dummy
5316 /// variables appropriately.
5317 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5318 QualType InitCaptureType,
5319 IdentifierInfo *Id,
5320 unsigned InitStyle, Expr *Init);
5321
5322 /// \brief Build the implicit field for an init-capture.
5323 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5324
5325 /// \brief Note that we have finished the explicit captures for the
5326 /// given lambda.
5327 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5328
5329 /// \brief Introduce the lambda parameters into scope.
5330 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5331
5332 /// \brief Deduce a block or lambda's return type based on the return
5333 /// statements present in the body.
5334 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5335
5336 /// ActOnStartOfLambdaDefinition - This is called just before we start
5337 /// parsing the body of a lambda; it analyzes the explicit captures and
5338 /// arguments, and sets up various data-structures for the body of the
5339 /// lambda.
5340 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5341 Declarator &ParamInfo, Scope *CurScope);
5342
5343 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5344 /// is invoked to pop the information about the lambda.
5345 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5346 bool IsInstantiation = false);
5347
5348 /// ActOnLambdaExpr - This is called when the body of a lambda expression
5349 /// was successfully completed.
5350 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5351 Scope *CurScope);
5352
5353 /// \brief Does copying/destroying the captured variable have side effects?
5354 bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5355
5356 /// \brief Diagnose if an explicit lambda capture is unused.
5357 void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5358
5359 /// \brief Complete a lambda-expression having processed and attached the
5360 /// lambda body.
5361 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5362 sema::LambdaScopeInfo *LSI);
5363
5364 /// \brief Define the "body" of the conversion from a lambda object to a
5365 /// function pointer.
5366 ///
5367 /// This routine doesn't actually define a sensible body; rather, it fills
5368 /// in the initialization expression needed to copy the lambda object into
5369 /// the block, and IR generation actually generates the real body of the
5370 /// block pointer conversion.
5371 void DefineImplicitLambdaToFunctionPointerConversion(
5372 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5373
5374 /// \brief Define the "body" of the conversion from a lambda object to a
5375 /// block pointer.
5376 ///
5377 /// This routine doesn't actually define a sensible body; rather, it fills
5378 /// in the initialization expression needed to copy the lambda object into
5379 /// the block, and IR generation actually generates the real body of the
5380 /// block pointer conversion.
5381 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5382 CXXConversionDecl *Conv);
5383
5384 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5385 SourceLocation ConvLocation,
5386 CXXConversionDecl *Conv,
5387 Expr *Src);
5388
5389 // ParseObjCStringLiteral - Parse Objective-C string literals.
5390 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5391 ArrayRef<Expr *> Strings);
5392
5393 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5394
5395 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5396 /// numeric literal expression. Type of the expression will be "NSNumber *"
5397 /// or "id" if NSNumber is unavailable.
5398 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5399 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5400 bool Value);
5401 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5402
5403 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5404 /// '@' prefixed parenthesized expression. The type of the expression will
5405 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5406 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5407 /// "const char *" or C structure with attribute 'objc_boxable'.
5408 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5409
5410 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5411 Expr *IndexExpr,
5412 ObjCMethodDecl *getterMethod,
5413 ObjCMethodDecl *setterMethod);
5414
5415 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5416 MutableArrayRef<ObjCDictionaryElement> Elements);
5417
5418 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5419 TypeSourceInfo *EncodedTypeInfo,
5420 SourceLocation RParenLoc);
5421 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5422 CXXConversionDecl *Method,
5423 bool HadMultipleCandidates);
5424
5425 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5426 SourceLocation EncodeLoc,
5427 SourceLocation LParenLoc,
5428 ParsedType Ty,
5429 SourceLocation RParenLoc);
5430
5431 /// ParseObjCSelectorExpression - Build selector expression for \@selector
5432 ExprResult ParseObjCSelectorExpression(Selector Sel,
5433 SourceLocation AtLoc,
5434 SourceLocation SelLoc,
5435 SourceLocation LParenLoc,
5436 SourceLocation RParenLoc,
5437 bool WarnMultipleSelectors);
5438
5439 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5440 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5441 SourceLocation AtLoc,
5442 SourceLocation ProtoLoc,
5443 SourceLocation LParenLoc,
5444 SourceLocation ProtoIdLoc,
5445 SourceLocation RParenLoc);
5446
5447 //===--------------------------------------------------------------------===//
5448 // C++ Declarations
5449 //
5450 Decl *ActOnStartLinkageSpecification(Scope *S,
5451 SourceLocation ExternLoc,
5452 Expr *LangStr,
5453 SourceLocation LBraceLoc);
5454 Decl *ActOnFinishLinkageSpecification(Scope *S,
5455 Decl *LinkageSpec,
5456 SourceLocation RBraceLoc);
5457
5458
5459 //===--------------------------------------------------------------------===//
5460 // C++ Classes
5461 //
5462 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5463 const CXXScopeSpec *SS = nullptr);
5464 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5465
5466 bool ActOnAccessSpecifier(AccessSpecifier Access,
5467 SourceLocation ASLoc,
5468 SourceLocation ColonLoc,
5469 AttributeList *Attrs = nullptr);
5470
5471 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5472 Declarator &D,
5473 MultiTemplateParamsArg TemplateParameterLists,
5474 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5475 InClassInitStyle InitStyle);
5476
5477 void ActOnStartCXXInClassMemberInitializer();
5478 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5479 SourceLocation EqualLoc,
5480 Expr *Init);
5481
5482 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5483 Scope *S,
5484 CXXScopeSpec &SS,
5485 IdentifierInfo *MemberOrBase,
5486 ParsedType TemplateTypeTy,
5487 const DeclSpec &DS,
5488 SourceLocation IdLoc,
5489 SourceLocation LParenLoc,
5490 ArrayRef<Expr *> Args,
5491 SourceLocation RParenLoc,
5492 SourceLocation EllipsisLoc);
5493
5494 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5495 Scope *S,
5496 CXXScopeSpec &SS,
5497 IdentifierInfo *MemberOrBase,
5498 ParsedType TemplateTypeTy,
5499 const DeclSpec &DS,
5500 SourceLocation IdLoc,
5501 Expr *InitList,
5502 SourceLocation EllipsisLoc);
5503
5504 MemInitResult BuildMemInitializer(Decl *ConstructorD,
5505 Scope *S,
5506 CXXScopeSpec &SS,
5507 IdentifierInfo *MemberOrBase,
5508 ParsedType TemplateTypeTy,
5509 const DeclSpec &DS,
5510 SourceLocation IdLoc,
5511 Expr *Init,
5512 SourceLocation EllipsisLoc);
5513
5514 MemInitResult BuildMemberInitializer(ValueDecl *Member,
5515 Expr *Init,
5516 SourceLocation IdLoc);
5517
5518 MemInitResult BuildBaseInitializer(QualType BaseType,
5519 TypeSourceInfo *BaseTInfo,
5520 Expr *Init,
5521 CXXRecordDecl *ClassDecl,
5522 SourceLocation EllipsisLoc);
5523
5524 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5525 Expr *Init,
5526 CXXRecordDecl *ClassDecl);
5527
5528 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5529 CXXCtorInitializer *Initializer);
5530
5531 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5532 ArrayRef<CXXCtorInitializer *> Initializers = None);
5533
5534 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5535
5536
5537 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5538 /// mark all the non-trivial destructors of its members and bases as
5539 /// referenced.
5540 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5541 CXXRecordDecl *Record);
5542
5543 /// \brief The list of classes whose vtables have been used within
5544 /// this translation unit, and the source locations at which the
5545 /// first use occurred.
5546 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5547
5548 /// \brief The list of vtables that are required but have not yet been
5549 /// materialized.
5550 SmallVector<VTableUse, 16> VTableUses;
5551
5552 /// \brief The set of classes whose vtables have been used within
5553 /// this translation unit, and a bit that will be true if the vtable is
5554 /// required to be emitted (otherwise, it should be emitted only if needed
5555 /// by code generation).
5556 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5557
5558 /// \brief Load any externally-stored vtable uses.
5559 void LoadExternalVTableUses();
5560
5561 /// \brief Note that the vtable for the given class was used at the
5562 /// given location.
5563 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5564 bool DefinitionRequired = false);
5565
5566 /// \brief Mark the exception specifications of all virtual member functions
5567 /// in the given class as needed.
5568 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5569 const CXXRecordDecl *RD);
5570
5571 /// MarkVirtualMembersReferenced - Will mark all members of the given
5572 /// CXXRecordDecl referenced.
5573 void MarkVirtualMembersReferenced(SourceLocation Loc,
5574 const CXXRecordDecl *RD);
5575
5576 /// \brief Define all of the vtables that have been used in this
5577 /// translation unit and reference any virtual members used by those
5578 /// vtables.
5579 ///
5580 /// \returns true if any work was done, false otherwise.
5581 bool DefineUsedVTables();
5582
5583 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5584
5585 void ActOnMemInitializers(Decl *ConstructorDecl,
5586 SourceLocation ColonLoc,
5587 ArrayRef<CXXCtorInitializer*> MemInits,
5588 bool AnyErrors);
5589
5590 /// \brief Check class-level dllimport/dllexport attribute. The caller must
5591 /// ensure that referenceDLLExportedClassMethods is called some point later
5592 /// when all outer classes of Class are complete.
5593 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5594
5595 void referenceDLLExportedClassMethods();
5596
5597 void propagateDLLAttrToBaseClassTemplate(
5598 CXXRecordDecl *Class, Attr *ClassAttr,
5599 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5600 SourceLocation BaseLoc);
5601
5602 void CheckCompletedCXXClass(CXXRecordDecl *Record);
5603 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5604 Decl *TagDecl,
5605 SourceLocation LBrac,
5606 SourceLocation RBrac,
5607 AttributeList *AttrList);
5608 void ActOnFinishCXXMemberDecls();
5609 void ActOnFinishCXXNonNestedClass(Decl *D);
5610
5611 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5612 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5613 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5614 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5615 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5616 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5617 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5618 void ActOnFinishDelayedMemberInitializers(Decl *Record);
5619 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5620 CachedTokens &Toks);
5621 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5622 bool IsInsideALocalClassWithinATemplateFunction();
5623
5624 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5625 Expr *AssertExpr,
5626 Expr *AssertMessageExpr,
5627 SourceLocation RParenLoc);
5628 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5629 Expr *AssertExpr,
5630 StringLiteral *AssertMessageExpr,
5631 SourceLocation RParenLoc,
5632 bool Failed);
5633
5634 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5635 SourceLocation FriendLoc,
5636 TypeSourceInfo *TSInfo);
5637 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5638 MultiTemplateParamsArg TemplateParams);
5639 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5640 MultiTemplateParamsArg TemplateParams);
5641
5642 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5643 StorageClass& SC);
5644 void CheckConstructor(CXXConstructorDecl *Constructor);
5645 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5646 StorageClass& SC);
5647 bool CheckDestructor(CXXDestructorDecl *Destructor);
5648 void CheckConversionDeclarator(Declarator &D, QualType &R,
5649 StorageClass& SC);
5650 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5651 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5652 StorageClass &SC);
5653 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5654
5655 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5656 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5657 const FunctionProtoType *T);
5658 void CheckDelayedMemberExceptionSpecs();
5659
5660 //===--------------------------------------------------------------------===//
5661 // C++ Derived Classes
5662 //
5663
5664 /// ActOnBaseSpecifier - Parsed a base specifier
5665 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5666 SourceRange SpecifierRange,
5667 bool Virtual, AccessSpecifier Access,
5668 TypeSourceInfo *TInfo,
5669 SourceLocation EllipsisLoc);
5670
5671 BaseResult ActOnBaseSpecifier(Decl *classdecl,
5672 SourceRange SpecifierRange,
5673 ParsedAttributes &Attrs,
5674 bool Virtual, AccessSpecifier Access,
5675 ParsedType basetype,
5676 SourceLocation BaseLoc,
5677 SourceLocation EllipsisLoc);
5678
5679 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5680 MutableArrayRef<CXXBaseSpecifier *> Bases);
5681 void ActOnBaseSpecifiers(Decl *ClassDecl,
5682 MutableArrayRef<CXXBaseSpecifier *> Bases);
5683
5684 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5685 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5686 CXXBasePaths &Paths);
5687
5688 // FIXME: I don't like this name.
5689 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5690
5691 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5692 SourceLocation Loc, SourceRange Range,
5693 CXXCastPath *BasePath = nullptr,
5694 bool IgnoreAccess = false);
5695 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5696 unsigned InaccessibleBaseID,
5697 unsigned AmbigiousBaseConvID,
5698 SourceLocation Loc, SourceRange Range,
5699 DeclarationName Name,
5700 CXXCastPath *BasePath,
5701 bool IgnoreAccess = false);
5702
5703 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5704
5705 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5706 const CXXMethodDecl *Old);
5707
5708 /// CheckOverridingFunctionReturnType - Checks whether the return types are
5709 /// covariant, according to C++ [class.virtual]p5.
5710 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5711 const CXXMethodDecl *Old);
5712
5713 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5714 /// spec is a subset of base spec.
5715 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5716 const CXXMethodDecl *Old);
5717
5718 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5719
5720 /// CheckOverrideControl - Check C++11 override control semantics.
5721 void CheckOverrideControl(NamedDecl *D);
5722
5723 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5724 /// not used in the declaration of an overriding method.
5725 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5726
5727 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5728 /// overrides a virtual member function marked 'final', according to
5729 /// C++11 [class.virtual]p4.
5730 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5731 const CXXMethodDecl *Old);
5732
5733
5734 //===--------------------------------------------------------------------===//
5735 // C++ Access Control
5736 //
5737
5738 enum AccessResult {
5739 AR_accessible,
5740 AR_inaccessible,
5741 AR_dependent,
5742 AR_delayed
5743 };
5744
5745 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5746 NamedDecl *PrevMemberDecl,
5747 AccessSpecifier LexicalAS);
5748
5749 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5750 DeclAccessPair FoundDecl);
5751 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5752 DeclAccessPair FoundDecl);
5753 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5754 SourceRange PlacementRange,
5755 CXXRecordDecl *NamingClass,
5756 DeclAccessPair FoundDecl,
5757 bool Diagnose = true);
5758 AccessResult CheckConstructorAccess(SourceLocation Loc,
5759 CXXConstructorDecl *D,
5760 DeclAccessPair FoundDecl,
5761 const InitializedEntity &Entity,
5762 bool IsCopyBindingRefToTemp = false);
5763 AccessResult CheckConstructorAccess(SourceLocation Loc,
5764 CXXConstructorDecl *D,
5765 DeclAccessPair FoundDecl,
5766 const InitializedEntity &Entity,
5767 const PartialDiagnostic &PDiag);
5768 AccessResult CheckDestructorAccess(SourceLocation Loc,
5769 CXXDestructorDecl *Dtor,
5770 const PartialDiagnostic &PDiag,
5771 QualType objectType = QualType());
5772 AccessResult CheckFriendAccess(NamedDecl *D);
5773 AccessResult CheckMemberAccess(SourceLocation UseLoc,
5774 CXXRecordDecl *NamingClass,
5775 DeclAccessPair Found);
5776 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5777 Expr *ObjectExpr,
5778 Expr *ArgExpr,
5779 DeclAccessPair FoundDecl);
5780 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5781 DeclAccessPair FoundDecl);
5782 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5783 QualType Base, QualType Derived,
5784 const CXXBasePath &Path,
5785 unsigned DiagID,
5786 bool ForceCheck = false,
5787 bool ForceUnprivileged = false);
5788 void CheckLookupAccess(const LookupResult &R);
5789 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5790 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5791 AccessSpecifier access,
5792 QualType objectType);
5793
5794 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5795 const MultiLevelTemplateArgumentList &TemplateArgs);
5796 void PerformDependentDiagnostics(const DeclContext *Pattern,
5797 const MultiLevelTemplateArgumentList &TemplateArgs);
5798
5799 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5800
5801 /// \brief When true, access checking violations are treated as SFINAE
5802 /// failures rather than hard errors.
5803 bool AccessCheckingSFINAE;
5804
5805 enum AbstractDiagSelID {
5806 AbstractNone = -1,
5807 AbstractReturnType,
5808 AbstractParamType,
5809 AbstractVariableType,
5810 AbstractFieldType,
5811 AbstractIvarType,
5812 AbstractSynthesizedIvarType,
5813 AbstractArrayType
5814 };
5815
5816 bool isAbstractType(SourceLocation Loc, QualType T);
5817 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5818 TypeDiagnoser &Diagnoser);
5819 template <typename... Ts>
5820 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5821 const Ts &...Args) {
5822 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5823 return RequireNonAbstractType(Loc, T, Diagnoser);
5824 }
5825
5826 void DiagnoseAbstractType(const CXXRecordDecl *RD);
5827
5828 //===--------------------------------------------------------------------===//
5829 // C++ Overloaded Operators [C++ 13.5]
5830 //
5831
5832 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5833
5834 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5835
5836 //===--------------------------------------------------------------------===//
5837 // C++ Templates [C++ 14]
5838 //
5839 void FilterAcceptableTemplateNames(LookupResult &R,
5840 bool AllowFunctionTemplates = true);
5841 bool hasAnyAcceptableTemplateNames(LookupResult &R,
5842 bool AllowFunctionTemplates = true);
5843
5844 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5845 QualType ObjectType, bool EnteringContext,
5846 bool &MemberOfUnknownSpecialization);
5847
5848 TemplateNameKind isTemplateName(Scope *S,
5849 CXXScopeSpec &SS,
5850 bool hasTemplateKeyword,
5851 UnqualifiedId &Name,
5852 ParsedType ObjectType,
5853 bool EnteringContext,
5854 TemplateTy &Template,
5855 bool &MemberOfUnknownSpecialization);
5856
5857 /// Determine whether a particular identifier might be the name in a C++1z
5858 /// deduction-guide declaration.
5859 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5860 SourceLocation NameLoc,
5861 ParsedTemplateTy *Template = nullptr);
5862
5863 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5864 SourceLocation IILoc,
5865 Scope *S,
5866 const CXXScopeSpec *SS,
5867 TemplateTy &SuggestedTemplate,
5868 TemplateNameKind &SuggestedKind);
5869
5870 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5871 NamedDecl *Instantiation,
5872 bool InstantiatedFromMember,
5873 const NamedDecl *Pattern,
5874 const NamedDecl *PatternDef,
5875 TemplateSpecializationKind TSK,
5876 bool Complain = true);
5877
5878 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5879 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5880
5881 Decl *ActOnTypeParameter(Scope *S, bool Typename,
5882 SourceLocation EllipsisLoc,
5883 SourceLocation KeyLoc,
5884 IdentifierInfo *ParamName,
5885 SourceLocation ParamNameLoc,
5886 unsigned Depth, unsigned Position,
5887 SourceLocation EqualLoc,
5888 ParsedType DefaultArg);
5889
5890 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5891 SourceLocation Loc);
5892 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5893
5894 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5895 unsigned Depth,
5896 unsigned Position,
5897 SourceLocation EqualLoc,
5898 Expr *DefaultArg);
5899 Decl *ActOnTemplateTemplateParameter(Scope *S,
5900 SourceLocation TmpLoc,
5901 TemplateParameterList *Params,
5902 SourceLocation EllipsisLoc,
5903 IdentifierInfo *ParamName,
5904 SourceLocation ParamNameLoc,
5905 unsigned Depth,
5906 unsigned Position,
5907 SourceLocation EqualLoc,
5908 ParsedTemplateArgument DefaultArg);
5909
5910 TemplateParameterList *
5911 ActOnTemplateParameterList(unsigned Depth,
5912 SourceLocation ExportLoc,
5913 SourceLocation TemplateLoc,
5914 SourceLocation LAngleLoc,
5915 ArrayRef<Decl *> Params,
5916 SourceLocation RAngleLoc,
5917 Expr *RequiresClause);
5918
5919 /// \brief The context in which we are checking a template parameter list.
5920 enum TemplateParamListContext {
5921 TPC_ClassTemplate,
5922 TPC_VarTemplate,
5923 TPC_FunctionTemplate,
5924 TPC_ClassTemplateMember,
5925 TPC_FriendClassTemplate,
5926 TPC_FriendFunctionTemplate,
5927 TPC_FriendFunctionTemplateDefinition,
5928 TPC_TypeAliasTemplate
5929 };
5930
5931 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5932 TemplateParameterList *OldParams,
5933 TemplateParamListContext TPC);
5934 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5935 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5936 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5937 ArrayRef<TemplateParameterList *> ParamLists,
5938 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5939
5940 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5941 SourceLocation KWLoc, CXXScopeSpec &SS,
5942 IdentifierInfo *Name, SourceLocation NameLoc,
5943 AttributeList *Attr,
5944 TemplateParameterList *TemplateParams,
5945 AccessSpecifier AS,
5946 SourceLocation ModulePrivateLoc,
5947 SourceLocation FriendLoc,
5948 unsigned NumOuterTemplateParamLists,
5949 TemplateParameterList **OuterTemplateParamLists,
5950 SkipBodyInfo *SkipBody = nullptr);
5951
5952 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
5953 QualType NTTPType,
5954 SourceLocation Loc);
5955
5956 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5957 TemplateArgumentListInfo &Out);
5958
5959 void NoteAllFoundTemplates(TemplateName Name);
5960
5961 QualType CheckTemplateIdType(TemplateName Template,
5962 SourceLocation TemplateLoc,
5963 TemplateArgumentListInfo &TemplateArgs);
5964
5965 TypeResult
5966 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5967 TemplateTy Template, IdentifierInfo *TemplateII,
5968 SourceLocation TemplateIILoc,
5969 SourceLocation LAngleLoc,
5970 ASTTemplateArgsPtr TemplateArgs,
5971 SourceLocation RAngleLoc,
5972 bool IsCtorOrDtorName = false,
5973 bool IsClassName = false);
5974
5975 /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5976 /// such as \c class T::template apply<U>.
5977 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5978 TypeSpecifierType TagSpec,
5979 SourceLocation TagLoc,
5980 CXXScopeSpec &SS,
5981 SourceLocation TemplateKWLoc,
5982 TemplateTy TemplateD,
5983 SourceLocation TemplateLoc,
5984 SourceLocation LAngleLoc,
5985 ASTTemplateArgsPtr TemplateArgsIn,
5986 SourceLocation RAngleLoc);
5987
5988 DeclResult ActOnVarTemplateSpecialization(
5989 Scope *S, Declarator &D, TypeSourceInfo *DI,
5990 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5991 StorageClass SC, bool IsPartialSpecialization);
5992
5993 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5994 SourceLocation TemplateLoc,
5995 SourceLocation TemplateNameLoc,
5996 const TemplateArgumentListInfo &TemplateArgs);
5997
5998 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
5999 const DeclarationNameInfo &NameInfo,
6000 VarTemplateDecl *Template,
6001 SourceLocation TemplateLoc,
6002 const TemplateArgumentListInfo *TemplateArgs);
6003
6004 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6005 SourceLocation TemplateKWLoc,
6006 LookupResult &R,
6007 bool RequiresADL,
6008 const TemplateArgumentListInfo *TemplateArgs);
6009
6010 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6011 SourceLocation TemplateKWLoc,
6012 const DeclarationNameInfo &NameInfo,
6013 const TemplateArgumentListInfo *TemplateArgs);
6014
6015 TemplateNameKind ActOnDependentTemplateName(
6016 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6017 UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6018 TemplateTy &Template, bool AllowInjectedClassName = false);
6019
6020 DeclResult
6021 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6022 SourceLocation KWLoc,
6023 SourceLocation ModulePrivateLoc,
6024 TemplateIdAnnotation &TemplateId,
6025 AttributeList *Attr,
6026 MultiTemplateParamsArg TemplateParameterLists,
6027 SkipBodyInfo *SkipBody = nullptr);
6028
6029 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6030 TemplateDecl *PrimaryTemplate,
6031 unsigned NumExplicitArgs,
6032 ArrayRef<TemplateArgument> Args);
6033 void CheckTemplatePartialSpecialization(
6034 ClassTemplatePartialSpecializationDecl *Partial);
6035 void CheckTemplatePartialSpecialization(
6036 VarTemplatePartialSpecializationDecl *Partial);
6037
6038 Decl *ActOnTemplateDeclarator(Scope *S,
6039 MultiTemplateParamsArg TemplateParameterLists,
6040 Declarator &D);
6041
6042 bool
6043 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6044 TemplateSpecializationKind NewTSK,
6045 NamedDecl *PrevDecl,
6046 TemplateSpecializationKind PrevTSK,
6047 SourceLocation PrevPtOfInstantiation,
6048 bool &SuppressNew);
6049
6050 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6051 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6052 LookupResult &Previous);
6053
6054 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6055 TemplateArgumentListInfo *ExplicitTemplateArgs,
6056 LookupResult &Previous);
6057 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6058
6059 DeclResult
6060 ActOnExplicitInstantiation(Scope *S,
6061 SourceLocation ExternLoc,
6062 SourceLocation TemplateLoc,
6063 unsigned TagSpec,
6064 SourceLocation KWLoc,
6065 const CXXScopeSpec &SS,
6066 TemplateTy Template,
6067 SourceLocation TemplateNameLoc,
6068 SourceLocation LAngleLoc,
6069 ASTTemplateArgsPtr TemplateArgs,
6070 SourceLocation RAngleLoc,
6071 AttributeList *Attr);
6072
6073 DeclResult
6074 ActOnExplicitInstantiation(Scope *S,
6075 SourceLocation ExternLoc,
6076 SourceLocation TemplateLoc,
6077 unsigned TagSpec,
6078 SourceLocation KWLoc,
6079 CXXScopeSpec &SS,
6080 IdentifierInfo *Name,
6081 SourceLocation NameLoc,
6082 AttributeList *Attr);
6083
6084 DeclResult ActOnExplicitInstantiation(Scope *S,
6085 SourceLocation ExternLoc,
6086 SourceLocation TemplateLoc,
6087 Declarator &D);
6088
6089 TemplateArgumentLoc
6090 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6091 SourceLocation TemplateLoc,
6092 SourceLocation RAngleLoc,
6093 Decl *Param,
6094 SmallVectorImpl<TemplateArgument>
6095 &Converted,
6096 bool &HasDefaultArg);
6097
6098 /// \brief Specifies the context in which a particular template
6099 /// argument is being checked.
6100 enum CheckTemplateArgumentKind {
6101 /// \brief The template argument was specified in the code or was
6102 /// instantiated with some deduced template arguments.
6103 CTAK_Specified,
6104
6105 /// \brief The template argument was deduced via template argument
6106 /// deduction.
6107 CTAK_Deduced,
6108
6109 /// \brief The template argument was deduced from an array bound
6110 /// via template argument deduction.
6111 CTAK_DeducedFromArrayBound
6112 };
6113
6114 bool CheckTemplateArgument(NamedDecl *Param,
6115 TemplateArgumentLoc &Arg,
6116 NamedDecl *Template,
6117 SourceLocation TemplateLoc,
6118 SourceLocation RAngleLoc,
6119 unsigned ArgumentPackIndex,
6120 SmallVectorImpl<TemplateArgument> &Converted,
6121 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6122
6123 /// \brief Check that the given template arguments can be be provided to
6124 /// the given template, converting the arguments along the way.
6125 ///
6126 /// \param Template The template to which the template arguments are being
6127 /// provided.
6128 ///
6129 /// \param TemplateLoc The location of the template name in the source.
6130 ///
6131 /// \param TemplateArgs The list of template arguments. If the template is
6132 /// a template template parameter, this function may extend the set of
6133 /// template arguments to also include substituted, defaulted template
6134 /// arguments.
6135 ///
6136 /// \param PartialTemplateArgs True if the list of template arguments is
6137 /// intentionally partial, e.g., because we're checking just the initial
6138 /// set of template arguments.
6139 ///
6140 /// \param Converted Will receive the converted, canonicalized template
6141 /// arguments.
6142 ///
6143 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6144 /// contain the converted forms of the template arguments as written.
6145 /// Otherwise, \p TemplateArgs will not be modified.
6146 ///
6147 /// \returns true if an error occurred, false otherwise.
6148 bool CheckTemplateArgumentList(TemplateDecl *Template,
6149 SourceLocation TemplateLoc,
6150 TemplateArgumentListInfo &TemplateArgs,
6151 bool PartialTemplateArgs,
6152 SmallVectorImpl<TemplateArgument> &Converted,
6153 bool UpdateArgsWithConversions = true);
6154
6155 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6156 TemplateArgumentLoc &Arg,
6157 SmallVectorImpl<TemplateArgument> &Converted);
6158
6159 bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6160 TypeSourceInfo *Arg);
6161 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6162 QualType InstantiatedParamType, Expr *Arg,
6163 TemplateArgument &Converted,
6164 CheckTemplateArgumentKind CTAK = CTAK_Specified);
6165 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6166 TemplateArgumentLoc &Arg,
6167 unsigned ArgumentPackIndex);
6168
6169 ExprResult
6170 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6171 QualType ParamType,
6172 SourceLocation Loc);
6173 ExprResult
6174 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6175 SourceLocation Loc);
6176
6177 /// \brief Enumeration describing how template parameter lists are compared
6178 /// for equality.
6179 enum TemplateParameterListEqualKind {
6180 /// \brief We are matching the template parameter lists of two templates
6181 /// that might be redeclarations.
6182 ///
6183 /// \code
6184 /// template<typename T> struct X;
6185 /// template<typename T> struct X;
6186 /// \endcode
6187 TPL_TemplateMatch,
6188
6189 /// \brief We are matching the template parameter lists of two template
6190 /// template parameters as part of matching the template parameter lists
6191 /// of two templates that might be redeclarations.
6192 ///
6193 /// \code
6194 /// template<template<int I> class TT> struct X;
6195 /// template<template<int Value> class Other> struct X;
6196 /// \endcode
6197 TPL_TemplateTemplateParmMatch,
6198
6199 /// \brief We are matching the template parameter lists of a template
6200 /// template argument against the template parameter lists of a template
6201 /// template parameter.
6202 ///
6203 /// \code
6204 /// template<template<int Value> class Metafun> struct X;
6205 /// template<int Value> struct integer_c;
6206 /// X<integer_c> xic;
6207 /// \endcode
6208 TPL_TemplateTemplateArgumentMatch
6209 };
6210
6211 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6212 TemplateParameterList *Old,
6213 bool Complain,
6214 TemplateParameterListEqualKind Kind,
6215 SourceLocation TemplateArgLoc
6216 = SourceLocation());
6217
6218 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6219
6220 /// \brief Called when the parser has parsed a C++ typename
6221 /// specifier, e.g., "typename T::type".
6222 ///
6223 /// \param S The scope in which this typename type occurs.
6224 /// \param TypenameLoc the location of the 'typename' keyword
6225 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6226 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6227 /// \param IdLoc the location of the identifier.
6228 TypeResult
6229 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6230 const CXXScopeSpec &SS, const IdentifierInfo &II,
6231 SourceLocation IdLoc);
6232
6233 /// \brief Called when the parser has parsed a C++ typename
6234 /// specifier that ends in a template-id, e.g.,
6235 /// "typename MetaFun::template apply<T1, T2>".
6236 ///
6237 /// \param S The scope in which this typename type occurs.
6238 /// \param TypenameLoc the location of the 'typename' keyword
6239 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6240 /// \param TemplateLoc the location of the 'template' keyword, if any.
6241 /// \param TemplateName The template name.
6242 /// \param TemplateII The identifier used to name the template.
6243 /// \param TemplateIILoc The location of the template name.
6244 /// \param LAngleLoc The location of the opening angle bracket ('<').
6245 /// \param TemplateArgs The template arguments.
6246 /// \param RAngleLoc The location of the closing angle bracket ('>').
6247 TypeResult
6248 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6249 const CXXScopeSpec &SS,
6250 SourceLocation TemplateLoc,
6251 TemplateTy TemplateName,
6252 IdentifierInfo *TemplateII,
6253 SourceLocation TemplateIILoc,
6254 SourceLocation LAngleLoc,
6255 ASTTemplateArgsPtr TemplateArgs,
6256 SourceLocation RAngleLoc);
6257
6258 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6259 SourceLocation KeywordLoc,
6260 NestedNameSpecifierLoc QualifierLoc,
6261 const IdentifierInfo &II,
6262 SourceLocation IILoc);
6263
6264 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6265 SourceLocation Loc,
6266 DeclarationName Name);
6267 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6268
6269 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6270 bool RebuildTemplateParamsInCurrentInstantiation(
6271 TemplateParameterList *Params);
6272
6273 std::string
6274 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6275 const TemplateArgumentList &Args);
6276
6277 std::string
6278 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6279 const TemplateArgument *Args,
6280 unsigned NumArgs);
6281
6282 //===--------------------------------------------------------------------===//
6283 // C++ Variadic Templates (C++0x [temp.variadic])
6284 //===--------------------------------------------------------------------===//
6285
6286 /// Determine whether an unexpanded parameter pack might be permitted in this
6287 /// location. Useful for error recovery.
6288 bool isUnexpandedParameterPackPermitted();
6289
6290 /// \brief The context in which an unexpanded parameter pack is
6291 /// being diagnosed.
6292 ///
6293 /// Note that the values of this enumeration line up with the first
6294 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6295 enum UnexpandedParameterPackContext {
6296 /// \brief An arbitrary expression.
6297 UPPC_Expression = 0,
6298
6299 /// \brief The base type of a class type.
6300 UPPC_BaseType,
6301
6302 /// \brief The type of an arbitrary declaration.
6303 UPPC_DeclarationType,
6304
6305 /// \brief The type of a data member.
6306 UPPC_DataMemberType,
6307
6308 /// \brief The size of a bit-field.
6309 UPPC_BitFieldWidth,
6310
6311 /// \brief The expression in a static assertion.
6312 UPPC_StaticAssertExpression,
6313
6314 /// \brief The fixed underlying type of an enumeration.
6315 UPPC_FixedUnderlyingType,
6316
6317 /// \brief The enumerator value.
6318 UPPC_EnumeratorValue,
6319
6320 /// \brief A using declaration.
6321 UPPC_UsingDeclaration,
6322
6323 /// \brief A friend declaration.
6324 UPPC_FriendDeclaration,
6325
6326 /// \brief A declaration qualifier.
6327 UPPC_DeclarationQualifier,
6328
6329 /// \brief An initializer.
6330 UPPC_Initializer,
6331
6332 /// \brief A default argument.
6333 UPPC_DefaultArgument,
6334
6335 /// \brief The type of a non-type template parameter.
6336 UPPC_NonTypeTemplateParameterType,
6337
6338 /// \brief The type of an exception.
6339 UPPC_ExceptionType,
6340
6341 /// \brief Partial specialization.
6342 UPPC_PartialSpecialization,
6343
6344 /// \brief Microsoft __if_exists.
6345 UPPC_IfExists,
6346
6347 /// \brief Microsoft __if_not_exists.
6348 UPPC_IfNotExists,
6349
6350 /// \brief Lambda expression.
6351 UPPC_Lambda,
6352
6353 /// \brief Block expression,
6354 UPPC_Block
6355 };
6356
6357 /// \brief Diagnose unexpanded parameter packs.
6358 ///
6359 /// \param Loc The location at which we should emit the diagnostic.
6360 ///
6361 /// \param UPPC The context in which we are diagnosing unexpanded
6362 /// parameter packs.
6363 ///
6364 /// \param Unexpanded the set of unexpanded parameter packs.
6365 ///
6366 /// \returns true if an error occurred, false otherwise.
6367 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6368 UnexpandedParameterPackContext UPPC,
6369 ArrayRef<UnexpandedParameterPack> Unexpanded);
6370
6371 /// \brief If the given type contains an unexpanded parameter pack,
6372 /// diagnose the error.
6373 ///
6374 /// \param Loc The source location where a diagnostc should be emitted.
6375 ///
6376 /// \param T The type that is being checked for unexpanded parameter
6377 /// packs.
6378 ///
6379 /// \returns true if an error occurred, false otherwise.
6380 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6381 UnexpandedParameterPackContext UPPC);
6382
6383 /// \brief If the given expression contains an unexpanded parameter
6384 /// pack, diagnose the error.
6385 ///
6386 /// \param E The expression that is being checked for unexpanded
6387 /// parameter packs.
6388 ///
6389 /// \returns true if an error occurred, false otherwise.
6390 bool DiagnoseUnexpandedParameterPack(Expr *E,
6391 UnexpandedParameterPackContext UPPC = UPPC_Expression);
6392
6393 /// \brief If the given nested-name-specifier contains an unexpanded
6394 /// parameter pack, diagnose the error.
6395 ///
6396 /// \param SS The nested-name-specifier that is being checked for
6397 /// unexpanded parameter packs.
6398 ///
6399 /// \returns true if an error occurred, false otherwise.
6400 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6401 UnexpandedParameterPackContext UPPC);
6402
6403 /// \brief If the given name contains an unexpanded parameter pack,
6404 /// diagnose the error.
6405 ///
6406 /// \param NameInfo The name (with source location information) that
6407 /// is being checked for unexpanded parameter packs.
6408 ///
6409 /// \returns true if an error occurred, false otherwise.
6410 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6411 UnexpandedParameterPackContext UPPC);
6412
6413 /// \brief If the given template name contains an unexpanded parameter pack,
6414 /// diagnose the error.
6415 ///
6416 /// \param Loc The location of the template name.
6417 ///
6418 /// \param Template The template name that is being checked for unexpanded
6419 /// parameter packs.
6420 ///
6421 /// \returns true if an error occurred, false otherwise.
6422 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6423 TemplateName Template,
6424 UnexpandedParameterPackContext UPPC);
6425
6426 /// \brief If the given template argument contains an unexpanded parameter
6427 /// pack, diagnose the error.
6428 ///
6429 /// \param Arg The template argument that is being checked for unexpanded
6430 /// parameter packs.
6431 ///
6432 /// \returns true if an error occurred, false otherwise.
6433 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6434 UnexpandedParameterPackContext UPPC);
6435
6436 /// \brief Collect the set of unexpanded parameter packs within the given
6437 /// template argument.
6438 ///
6439 /// \param Arg The template argument that will be traversed to find
6440 /// unexpanded parameter packs.
6441 void collectUnexpandedParameterPacks(TemplateArgument Arg,
6442 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6443
6444 /// \brief Collect the set of unexpanded parameter packs within the given
6445 /// template argument.
6446 ///
6447 /// \param Arg The template argument that will be traversed to find
6448 /// unexpanded parameter packs.
6449 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6450 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6451
6452 /// \brief Collect the set of unexpanded parameter packs within the given
6453 /// type.
6454 ///
6455 /// \param T The type that will be traversed to find
6456 /// unexpanded parameter packs.
6457 void collectUnexpandedParameterPacks(QualType T,
6458 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6459
6460 /// \brief Collect the set of unexpanded parameter packs within the given
6461 /// type.
6462 ///
6463 /// \param TL The type that will be traversed to find
6464 /// unexpanded parameter packs.
6465 void collectUnexpandedParameterPacks(TypeLoc TL,
6466 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6467
6468 /// \brief Collect the set of unexpanded parameter packs within the given
6469 /// nested-name-specifier.
6470 ///
6471 /// \param NNS The nested-name-specifier that will be traversed to find
6472 /// unexpanded parameter packs.
6473 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6474 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6475
6476 /// \brief Collect the set of unexpanded parameter packs within the given
6477 /// name.
6478 ///
6479 /// \param NameInfo The name that will be traversed to find
6480 /// unexpanded parameter packs.
6481 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6482 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6483
6484 /// \brief Invoked when parsing a template argument followed by an
6485 /// ellipsis, which creates a pack expansion.
6486 ///
6487 /// \param Arg The template argument preceding the ellipsis, which
6488 /// may already be invalid.
6489 ///
6490 /// \param EllipsisLoc The location of the ellipsis.
6491 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6492 SourceLocation EllipsisLoc);
6493
6494 /// \brief Invoked when parsing a type followed by an ellipsis, which
6495 /// creates a pack expansion.
6496 ///
6497 /// \param Type The type preceding the ellipsis, which will become
6498 /// the pattern of the pack expansion.
6499 ///
6500 /// \param EllipsisLoc The location of the ellipsis.
6501 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6502
6503 /// \brief Construct a pack expansion type from the pattern of the pack
6504 /// expansion.
6505 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6506 SourceLocation EllipsisLoc,
6507 Optional<unsigned> NumExpansions);
6508
6509 /// \brief Construct a pack expansion type from the pattern of the pack
6510 /// expansion.
6511 QualType CheckPackExpansion(QualType Pattern,
6512 SourceRange PatternRange,
6513 SourceLocation EllipsisLoc,
6514 Optional<unsigned> NumExpansions);
6515
6516 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6517 /// creates a pack expansion.
6518 ///
6519 /// \param Pattern The expression preceding the ellipsis, which will become
6520 /// the pattern of the pack expansion.
6521 ///
6522 /// \param EllipsisLoc The location of the ellipsis.
6523 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6524
6525 /// \brief Invoked when parsing an expression followed by an ellipsis, which
6526 /// creates a pack expansion.
6527 ///
6528 /// \param Pattern The expression preceding the ellipsis, which will become
6529 /// the pattern of the pack expansion.
6530 ///
6531 /// \param EllipsisLoc The location of the ellipsis.
6532 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6533 Optional<unsigned> NumExpansions);
6534
6535 /// \brief Determine whether we could expand a pack expansion with the
6536 /// given set of parameter packs into separate arguments by repeatedly
6537 /// transforming the pattern.
6538 ///
6539 /// \param EllipsisLoc The location of the ellipsis that identifies the
6540 /// pack expansion.
6541 ///
6542 /// \param PatternRange The source range that covers the entire pattern of
6543 /// the pack expansion.
6544 ///
6545 /// \param Unexpanded The set of unexpanded parameter packs within the
6546 /// pattern.
6547 ///
6548 /// \param ShouldExpand Will be set to \c true if the transformer should
6549 /// expand the corresponding pack expansions into separate arguments. When
6550 /// set, \c NumExpansions must also be set.
6551 ///
6552 /// \param RetainExpansion Whether the caller should add an unexpanded
6553 /// pack expansion after all of the expanded arguments. This is used
6554 /// when extending explicitly-specified template argument packs per
6555 /// C++0x [temp.arg.explicit]p9.
6556 ///
6557 /// \param NumExpansions The number of separate arguments that will be in
6558 /// the expanded form of the corresponding pack expansion. This is both an
6559 /// input and an output parameter, which can be set by the caller if the
6560 /// number of expansions is known a priori (e.g., due to a prior substitution)
6561 /// and will be set by the callee when the number of expansions is known.
6562 /// The callee must set this value when \c ShouldExpand is \c true; it may
6563 /// set this value in other cases.
6564 ///
6565 /// \returns true if an error occurred (e.g., because the parameter packs
6566 /// are to be instantiated with arguments of different lengths), false
6567 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6568 /// must be set.
6569 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6570 SourceRange PatternRange,
6571 ArrayRef<UnexpandedParameterPack> Unexpanded,
6572 const MultiLevelTemplateArgumentList &TemplateArgs,
6573 bool &ShouldExpand,
6574 bool &RetainExpansion,
6575 Optional<unsigned> &NumExpansions);
6576
6577 /// \brief Determine the number of arguments in the given pack expansion
6578 /// type.
6579 ///
6580 /// This routine assumes that the number of arguments in the expansion is
6581 /// consistent across all of the unexpanded parameter packs in its pattern.
6582 ///
6583 /// Returns an empty Optional if the type can't be expanded.
6584 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6585 const MultiLevelTemplateArgumentList &TemplateArgs);
6586
6587 /// \brief Determine whether the given declarator contains any unexpanded
6588 /// parameter packs.
6589 ///
6590 /// This routine is used by the parser to disambiguate function declarators
6591 /// with an ellipsis prior to the ')', e.g.,
6592 ///
6593 /// \code
6594 /// void f(T...);
6595 /// \endcode
6596 ///
6597 /// To determine whether we have an (unnamed) function parameter pack or
6598 /// a variadic function.
6599 ///
6600 /// \returns true if the declarator contains any unexpanded parameter packs,
6601 /// false otherwise.
6602 bool containsUnexpandedParameterPacks(Declarator &D);
6603
6604 /// \brief Returns the pattern of the pack expansion for a template argument.
6605 ///
6606 /// \param OrigLoc The template argument to expand.
6607 ///
6608 /// \param Ellipsis Will be set to the location of the ellipsis.
6609 ///
6610 /// \param NumExpansions Will be set to the number of expansions that will
6611 /// be generated from this pack expansion, if known a priori.
6612 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6613 TemplateArgumentLoc OrigLoc,
6614 SourceLocation &Ellipsis,
6615 Optional<unsigned> &NumExpansions) const;
6616
6617 /// Given a template argument that contains an unexpanded parameter pack, but
6618 /// which has already been substituted, attempt to determine the number of
6619 /// elements that will be produced once this argument is fully-expanded.
6620 ///
6621 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6622 /// avoid actually expanding the pack where possible.
6623 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6624
6625 //===--------------------------------------------------------------------===//
6626 // C++ Template Argument Deduction (C++ [temp.deduct])
6627 //===--------------------------------------------------------------------===//
6628
6629 /// Adjust the type \p ArgFunctionType to match the calling convention,
6630 /// noreturn, and optionally the exception specification of \p FunctionType.
6631 /// Deduction often wants to ignore these properties when matching function
6632 /// types.
6633 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6634 bool AdjustExceptionSpec = false);
6635
6636 /// \brief Describes the result of template argument deduction.
6637 ///
6638 /// The TemplateDeductionResult enumeration describes the result of
6639 /// template argument deduction, as returned from
6640 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6641 /// structure provides additional information about the results of
6642 /// template argument deduction, e.g., the deduced template argument
6643 /// list (if successful) or the specific template parameters or
6644 /// deduced arguments that were involved in the failure.
6645 enum TemplateDeductionResult {
6646 /// \brief Template argument deduction was successful.
6647 TDK_Success = 0,
6648 /// \brief The declaration was invalid; do nothing.
6649 TDK_Invalid,
6650 /// \brief Template argument deduction exceeded the maximum template
6651 /// instantiation depth (which has already been diagnosed).
6652 TDK_InstantiationDepth,
6653 /// \brief Template argument deduction did not deduce a value
6654 /// for every template parameter.
6655 TDK_Incomplete,
6656 /// \brief Template argument deduction produced inconsistent
6657 /// deduced values for the given template parameter.
6658 TDK_Inconsistent,
6659 /// \brief Template argument deduction failed due to inconsistent
6660 /// cv-qualifiers on a template parameter type that would
6661 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6662 /// but were given a non-const "X".
6663 TDK_Underqualified,
6664 /// \brief Substitution of the deduced template argument values
6665 /// resulted in an error.
6666 TDK_SubstitutionFailure,
6667 /// \brief After substituting deduced template arguments, a dependent
6668 /// parameter type did not match the corresponding argument.
6669 TDK_DeducedMismatch,
6670 /// \brief After substituting deduced template arguments, an element of
6671 /// a dependent parameter type did not match the corresponding element
6672 /// of the corresponding argument (when deducing from an initializer list).
6673 TDK_DeducedMismatchNested,
6674 /// \brief A non-depnedent component of the parameter did not match the
6675 /// corresponding component of the argument.
6676 TDK_NonDeducedMismatch,
6677 /// \brief When performing template argument deduction for a function
6678 /// template, there were too many call arguments.
6679 TDK_TooManyArguments,
6680 /// \brief When performing template argument deduction for a function
6681 /// template, there were too few call arguments.
6682 TDK_TooFewArguments,
6683 /// \brief The explicitly-specified template arguments were not valid
6684 /// template arguments for the given template.
6685 TDK_InvalidExplicitArguments,
6686 /// \brief Checking non-dependent argument conversions failed.
6687 TDK_NonDependentConversionFailure,
6688 /// \brief Deduction failed; that's all we know.
6689 TDK_MiscellaneousDeductionFailure,
6690 /// \brief CUDA Target attributes do not match.
6691 TDK_CUDATargetMismatch
6692 };
6693
6694 TemplateDeductionResult
6695 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6696 const TemplateArgumentList &TemplateArgs,
6697 sema::TemplateDeductionInfo &Info);
6698
6699 TemplateDeductionResult
6700 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6701 const TemplateArgumentList &TemplateArgs,
6702 sema::TemplateDeductionInfo &Info);
6703
6704 TemplateDeductionResult SubstituteExplicitTemplateArguments(
6705 FunctionTemplateDecl *FunctionTemplate,
6706 TemplateArgumentListInfo &ExplicitTemplateArgs,
6707 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6708 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6709 sema::TemplateDeductionInfo &Info);
6710
6711 /// brief A function argument from which we performed template argument
6712 // deduction for a call.
6713 struct OriginalCallArg {
6714