1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/APINotes/APINotesManager.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/AttrIterator.h"
22#include "clang/AST/CharUnits.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DeclarationName.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprConcepts.h"
30#include "clang/AST/ExternalASTSource.h"
31#include "clang/AST/NestedNameSpecifier.h"
32#include "clang/AST/OperationKinds.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
37#include "clang/Basic/AttrSubjectMatchRules.h"
38#include "clang/Basic/BuiltinTraits.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/CapturedStmt.h"
41#include "clang/Basic/Cuda.h"
42#include "clang/Basic/DiagnosticSema.h"
43#include "clang/Basic/ExceptionSpecificationType.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/Lambda.h"
46#include "clang/Basic/LangOptions.h"
47#include "clang/Basic/Module.h"
48#include "clang/Basic/OpenCLOptions.h"
49#include "clang/Basic/OperatorKinds.h"
50#include "clang/Basic/PartialDiagnostic.h"
51#include "clang/Basic/PragmaKinds.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/Specifiers.h"
54#include "clang/Basic/StackExhaustionHandler.h"
55#include "clang/Basic/TemplateKinds.h"
56#include "clang/Basic/TokenKinds.h"
57#include "clang/Lex/TextEncoding.h"
58#include "clang/Sema/AnalysisBasedWarnings.h"
59#include "clang/Sema/Attr.h"
60#include "clang/Sema/CleanupInfo.h"
61#include "clang/Sema/DeclSpec.h"
62#include "clang/Sema/ExternalSemaSource.h"
63#include "clang/Sema/IdentifierResolver.h"
64#include "clang/Sema/Ownership.h"
65#include "clang/Sema/ParsedAttr.h"
66#include "clang/Sema/Redeclaration.h"
67#include "clang/Sema/Scope.h"
68#include "clang/Sema/SemaBase.h"
69#include "clang/Sema/SemaConcept.h"
70#include "clang/Sema/TypoCorrection.h"
71#include "clang/Sema/Weak.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/BitmaskEnum.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FloatingPointMode.h"
78#include "llvm/ADT/FoldingSet.h"
79#include "llvm/ADT/MapVector.h"
80#include "llvm/ADT/PointerIntPair.h"
81#include "llvm/ADT/PointerUnion.h"
82#include "llvm/ADT/STLExtras.h"
83#include "llvm/ADT/STLForwardCompat.h"
84#include "llvm/ADT/STLFunctionalExtras.h"
85#include "llvm/ADT/SetVector.h"
86#include "llvm/ADT/SmallBitVector.h"
87#include "llvm/ADT/SmallPtrSet.h"
88#include "llvm/ADT/SmallSet.h"
89#include "llvm/ADT/SmallVector.h"
90#include "llvm/ADT/StringExtras.h"
91#include "llvm/ADT/StringMap.h"
92#include "llvm/ADT/TinyPtrVector.h"
93#include "llvm/Support/Allocator.h"
94#include "llvm/Support/Compiler.h"
95#include "llvm/Support/Error.h"
96#include "llvm/Support/ErrorHandling.h"
97#include <cassert>
98#include <climits>
99#include <cstddef>
100#include <cstdint>
101#include <deque>
102#include <functional>
103#include <iterator>
104#include <memory>
105#include <optional>
106#include <string>
107#include <tuple>
108#include <type_traits>
109#include <utility>
110#include <vector>
111
112namespace llvm {
113struct InlineAsmIdentifierInfo;
114} // namespace llvm
115
116namespace clang {
117class ADLResult;
118class APValue;
119class ASTConstraintSatisfaction;
120class ASTConsumer;
121class ASTContext;
122class ASTDeclReader;
123class ASTMutationListener;
124class ASTReader;
125class ASTWriter;
126class CXXBasePath;
127class CXXBasePaths;
128class CXXFieldCollector;
129class CodeCompleteConsumer;
130enum class ComparisonCategoryType : unsigned char;
131class ConstraintSatisfaction;
132class DarwinSDKInfo;
133class DeclGroupRef;
134class DeducedTemplateArgument;
135struct DeductionFailureInfo;
136class DependentDiagnostic;
137class Designation;
138class IdentifierInfo;
139struct ImplicitAllocationArguments;
140class ImplicitConversionSequence;
141typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
142class InitializationKind;
143class InitializationSequence;
144class InitializedEntity;
145enum class LangAS : unsigned int;
146class LocalInstantiationScope;
147class LookupResult;
148class MangleNumberingContext;
149typedef ArrayRef<IdentifierLoc> ModuleIdPath;
150class ModuleLoader;
151class MultiLevelTemplateArgumentList;
152struct NormalizedConstraint;
153class ObjCInterfaceDecl;
154class ObjCMethodDecl;
155struct OverloadCandidate;
156enum class OverloadCandidateParamOrder : char;
157enum OverloadCandidateRewriteKind : unsigned;
158class OverloadCandidateSet;
159class Preprocessor;
160struct APINotesSelectorDiagnosticState;
161struct ResolvedAllocation;
162class SemaAMDGPU;
163class SemaARM;
164class SemaAVR;
165class SemaBPF;
166class SemaCodeCompletion;
167class SemaCUDA;
168class SemaDirectX;
169class SemaHLSL;
170class SemaHexagon;
171class SemaLoongArch;
172class SemaM68k;
173class SemaMIPS;
174class SemaMSP430;
175class SemaNVPTX;
176class SemaObjC;
177class SemaOpenACC;
178class SemaOpenCL;
179class SemaOpenMP;
180class SemaPPC;
181class SemaPseudoObject;
182class SemaRISCV;
183class SemaSPIRV;
184class SemaSYCL;
185class SemaSwift;
186class SemaSystemZ;
187class SemaWasm;
188class SemaX86;
189class StandardConversionSequence;
190class TemplateArgument;
191class TemplateArgumentLoc;
192class TemplatePartialOrderingContext;
193class TemplateSpecCandidateSet;
194class Token;
195class TypeConstraint;
196class TypoCorrectionConsumer;
197class UnresolvedSetImpl;
198class UnresolvedSetIterator;
199class VisibleDeclConsumer;
200
201namespace sema {
202class BlockScopeInfo;
203class Capture;
204class CapturedRegionScopeInfo;
205class CapturingScopeInfo;
206class CompoundScopeInfo;
207class DelayedDiagnostic;
208class DelayedDiagnosticPool;
209class FunctionScopeInfo;
210class LambdaScopeInfo;
211class SemaPPCallbacks;
212class TemplateDeductionInfo;
213} // namespace sema
214
215// AssignmentAction - This is used by all the assignment diagnostic functions
216// to represent what is actually causing the operation
217enum class AssignmentAction {
218 Assigning,
219 Passing,
220 Returning,
221 Converting,
222 Initializing,
223 Sending,
224 Casting,
225 Passing_CFAudited
226};
227
228// Inline capacity for type-aware, aligned, and unaligned allocation argument
229// list candidates.
230using AllocationArgumentSet = SmallVector<ImplicitAllocationArguments, 3>;
231
232namespace threadSafety {
233class BeforeSet;
234void threadSafetyCleanup(BeforeSet *Cache);
235} // namespace threadSafety
236
237// FIXME: No way to easily map from TemplateTypeParmTypes to
238// TemplateTypeParmDecls, so we have this horrible PointerUnion.
239typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
240 const TemplateSpecializationType *,
241 const SubstBuiltinTemplatePackType *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
300 : Ctx(Ctx), Enabled(Enabled) {}
301
302 void enterCondition(Sema &S, SourceLocation Tok);
303 void enterReturn(Sema &S, SourceLocation Tok);
304 void enterVariableInit(SourceLocation Tok, Decl *D);
305 /// Handles e.g. BaseType{ .D = Tok...
306 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
307 const Designation &D);
308 /// Computing a type for the function argument may require running
309 /// overloading, so we postpone its computation until it is actually needed.
310 ///
311 /// Clients should be very careful when using this function, as it stores a
312 /// function_ref, clients should make sure all calls to get() with the same
313 /// location happen while function_ref is alive.
314 ///
315 /// The callback should also emit signature help as a side-effect, but only
316 /// if the completion point has been reached.
317 void enterFunctionArgument(SourceLocation Tok,
318 llvm::function_ref<QualType()> ComputeType);
319
320 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
321 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
322 SourceLocation OpLoc);
323 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
324 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
325 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
326 /// Handles all type casts, including C-style cast, C++ casts, etc.
327 void enterTypeCast(SourceLocation Tok, QualType CastType);
328
329 /// Get the expected type associated with this location, if any.
330 ///
331 /// If the location is a function argument, determining the expected type
332 /// involves considering all function overloads and the arguments so far.
333 /// In this case, signature help for these function overloads will be reported
334 /// as a side-effect (only if the completion point has been reached).
335 QualType get(SourceLocation Tok) const {
336 if (!Enabled || Tok != ExpectedLoc)
337 return QualType();
338 if (!Type.isNull())
339 return Type;
340 if (ComputeType)
341 return ComputeType();
342 return QualType();
343 }
344
345private:
346 ASTContext *Ctx;
347 bool Enabled;
348 /// Start position of a token for which we store expected type.
349 SourceLocation ExpectedLoc;
350 /// Expected type for a token starting at ExpectedLoc.
351 QualType Type;
352 /// A function to compute expected type at ExpectedLoc. It is only considered
353 /// if Type is null.
354 llvm::function_ref<QualType()> ComputeType;
355};
356
357struct SkipBodyInfo {
358 SkipBodyInfo() = default;
359 bool ShouldSkip = false;
360 bool CheckSameAsPrevious = false;
361 NamedDecl *Previous = nullptr;
362 NamedDecl *New = nullptr;
363};
364
365/// Describes the result of template argument deduction.
366///
367/// The TemplateDeductionResult enumeration describes the result of
368/// template argument deduction, as returned from
369/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
370/// structure provides additional information about the results of
371/// template argument deduction, e.g., the deduced template argument
372/// list (if successful) or the specific template parameters or
373/// deduced arguments that were involved in the failure.
374enum class TemplateDeductionResult {
375 /// Template argument deduction was successful.
376 Success = 0,
377 /// The declaration was invalid; do nothing.
378 Invalid,
379 /// Template argument deduction exceeded the maximum template
380 /// instantiation depth (which has already been diagnosed).
381 InstantiationDepth,
382 /// Template argument deduction did not deduce a value
383 /// for every template parameter.
384 Incomplete,
385 /// Template argument deduction did not deduce a value for every
386 /// expansion of an expanded template parameter pack.
387 IncompletePack,
388 /// Template argument deduction produced inconsistent
389 /// deduced values for the given template parameter.
390 Inconsistent,
391 /// Template argument deduction failed due to inconsistent
392 /// cv-qualifiers on a template parameter type that would
393 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
394 /// but were given a non-const "X".
395 Underqualified,
396 /// Substitution of the deduced template argument values
397 /// resulted in an error.
398 SubstitutionFailure,
399 /// After substituting deduced template arguments, a dependent
400 /// parameter type did not match the corresponding argument.
401 DeducedMismatch,
402 /// After substituting deduced template arguments, an element of
403 /// a dependent parameter type did not match the corresponding element
404 /// of the corresponding argument (when deducing from an initializer list).
405 DeducedMismatchNested,
406 /// A non-depnedent component of the parameter did not match the
407 /// corresponding component of the argument.
408 NonDeducedMismatch,
409 /// When performing template argument deduction for a function
410 /// template, there were too many call arguments.
411 TooManyArguments,
412 /// When performing template argument deduction for a function
413 /// template, there were too few call arguments.
414 TooFewArguments,
415 /// The explicitly-specified template arguments were not valid
416 /// template arguments for the given template.
417 InvalidExplicitArguments,
418 /// Checking non-dependent argument conversions failed.
419 NonDependentConversionFailure,
420 /// The deduced arguments did not satisfy the constraints associated
421 /// with the template.
422 ConstraintsNotSatisfied,
423 /// Deduction failed; that's all we know.
424 MiscellaneousDeductionFailure,
425 /// CUDA Target attributes do not match.
426 CUDATargetMismatch,
427 /// Some error which was already diagnosed.
428 AlreadyDiagnosed
429};
430
431/// The kind of conversion being performed.
432enum class CheckedConversionKind {
433 /// An implicit conversion.
434 Implicit,
435 /// A C-style cast.
436 CStyleCast,
437 /// A functional-style cast.
438 FunctionalCast,
439 /// A cast other than a C-style cast.
440 OtherCast,
441 /// A conversion for an operand of a builtin overloaded operator.
442 ForBuiltinOverloadedOp
443};
444
445enum class TagUseKind {
446 Reference, // Reference to a tag: 'struct foo *X;'
447 Declaration, // Fwd decl of a tag: 'struct foo;'
448 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
449 Friend // Friend declaration: 'friend struct foo;'
450};
451
452/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
453enum class FunctionEffectMode : uint8_t {
454 None, // effect is not present.
455 False, // effect(false).
456 True, // effect(true).
457 Dependent // effect(expr) where expr is dependent.
458};
459
460/// pragma clang section kind
461enum class PragmaClangSectionKind {
462 Invalid = 0,
463 BSS = 1,
464 Data = 2,
465 Rodata = 3,
466 Text = 4,
467 Relro = 5
468};
469
470enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
471
472enum class PragmaOptionsAlignKind {
473 Native, // #pragma options align=native
474 Natural, // #pragma options align=natural
475 Packed, // #pragma options align=packed
476 Power, // #pragma options align=power
477 Mac68k, // #pragma options align=mac68k
478 Reset // #pragma options align=reset
479};
480
481enum class TUFragmentKind {
482 /// The global module fragment, between 'module;' and a module-declaration.
483 Global,
484 /// A normal translation unit fragment. For a non-module unit, this is the
485 /// entire translation unit. Otherwise, it runs from the module-declaration
486 /// to the private-module-fragment (if any) or the end of the TU (if not).
487 Normal,
488 /// The private module fragment, between 'module :private;' and the end of
489 /// the translation unit.
490 Private
491};
492
493enum class FormatStringType {
494 Scanf,
495 Printf,
496 NSString,
497 Strftime,
498 Strfmon,
499 Kprintf,
500 FreeBSDKPrintf,
501 OSTrace,
502 OSLog,
503 Unknown
504};
505
506// Used for emitting the right warning by DefaultVariadicArgumentPromotion
507enum class VariadicCallType {
508 Function,
509 Block,
510 Method,
511 Constructor,
512 DoesNotApply
513};
514
515enum class BuiltinCountedByRefKind {
516 Assignment,
517 Initializer,
518 FunctionArg,
519 ReturnArg,
520 ArraySubscript,
521 BinaryExpr,
522};
523
524// Contexts where using non-trivial C union types can be disallowed. This is
525// passed to err_non_trivial_c_union_in_invalid_context.
526enum class NonTrivialCUnionContext {
527 // Function parameter.
528 FunctionParam,
529 // Function return.
530 FunctionReturn,
531 // Default-initialized object.
532 DefaultInitializedObject,
533 // Variable with automatic storage duration.
534 AutoVar,
535 // Initializer expression that might copy from another object.
536 CopyInit,
537 // Assignment.
538 Assignment,
539 // Compound literal.
540 CompoundLiteral,
541 // Block capture.
542 BlockCapture,
543 // lvalue-to-rvalue conversion of volatile type.
544 LValueToRValueVolatile,
545};
546
547/// Describes the result of the name lookup and resolution performed
548/// by \c Sema::ClassifyName().
549enum class NameClassificationKind {
550 /// This name is not a type or template in this context, but might be
551 /// something else.
552 Unknown,
553 /// Classification failed; an error has been produced.
554 Error,
555 /// The name has been typo-corrected to a keyword.
556 Keyword,
557 /// The name was classified as a type.
558 Type,
559 /// The name was classified as a specific non-type, non-template
560 /// declaration. ActOnNameClassifiedAsNonType should be called to
561 /// convert the declaration to an expression.
562 NonType,
563 /// The name was classified as an ADL-only function name.
564 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
565 /// result to an expression.
566 UndeclaredNonType,
567 /// The name denotes a member of a dependent type that could not be
568 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
569 /// convert the result to an expression.
570 DependentNonType,
571 /// The name was classified as an overload set, and an expression
572 /// representing that overload set has been formed.
573 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
574 /// expression referencing the overload set.
575 OverloadSet,
576 /// The name was classified as a template whose specializations are types.
577 TypeTemplate,
578 /// The name was classified as a variable template name.
579 VarTemplate,
580 /// The name was classified as a function template name.
581 FunctionTemplate,
582 /// The name was classified as an ADL-only function template name.
583 UndeclaredTemplate,
584 /// The name was classified as a concept name.
585 Concept,
586};
587
588enum class PointerAuthDiscArgKind {
589 // Address discrimination argument of __ptrauth.
590 Addr,
591
592 // Extra discriminator argument of __ptrauth.
593 Extra,
594};
595
596/// Common ways to introduce type names without a tag for use in diagnostics.
597/// Keep in sync with err_tag_reference_non_tag.
598enum class NonTagKind {
599 NonStruct,
600 NonClass,
601 NonUnion,
602 NonEnum,
603 Typedef,
604 TypeAlias,
605 Template,
606 TypeAliasTemplate,
607 TemplateTemplateArgument,
608};
609
610enum class OffsetOfKind {
611 // Not parsing a type within __builtin_offsetof.
612 Outside,
613 // Parsing a type within __builtin_offsetof.
614 Builtin,
615 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
616 // To improve our diagnostic message.
617 Macro,
618};
619
620/// Describes the kind of merge to perform for availability
621/// attributes (including "deprecated", "unavailable", and "availability").
622enum class AvailabilityMergeKind {
623 /// Don't merge availability attributes at all.
624 None,
625 /// Merge availability attributes for a redeclaration, which requires
626 /// an exact match.
627 Redeclaration,
628 /// Merge availability attributes for an override, which requires
629 /// an exact match or a weakening of constraints.
630 Override,
631 /// Merge availability attributes for an implementation of
632 /// a protocol requirement.
633 ProtocolImplementation,
634 /// Merge availability attributes for an implementation of
635 /// an optional protocol requirement.
636 OptionalProtocolImplementation
637};
638
639enum class TrivialABIHandling {
640 /// The triviality of a method unaffected by "trivial_abi".
641 IgnoreTrivialABI,
642
643 /// The triviality of a method affected by "trivial_abi".
644 ConsiderTrivialABI
645};
646
647enum class TryCaptureKind { Implicit, ExplicitByVal, ExplicitByRef };
648
649enum class AllowFoldKind {
650 No,
651 Allow,
652};
653
654/// Context in which we're performing a usual arithmetic conversion.
655enum class ArithConvKind {
656 /// An arithmetic operation.
657 Arithmetic,
658 /// A bitwise operation.
659 BitwiseOp,
660 /// A comparison.
661 Comparison,
662 /// A conditional (?:) operator.
663 Conditional,
664 /// A compound assignment expression.
665 CompAssign,
666};
667
668// Used for determining in which context a type is allowed to be passed to a
669// vararg function.
670enum class VarArgKind {
671 Valid,
672 ValidInCXX11,
673 Undefined,
674 MSVCUndefined,
675 Invalid
676};
677
678/// AssignConvertType - All of the 'assignment' semantic checks return this
679/// enum to indicate whether the assignment was allowed. These checks are
680/// done for simple assignments, as well as initialization, return from
681/// function, argument passing, etc. The query is phrased in terms of a
682/// source and destination type.
683enum class AssignConvertType {
684 /// Compatible - the types are compatible according to the standard.
685 Compatible,
686
687 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
688 /// a void * can implicitly convert to another pointer type, which we
689 /// differentiate for better diagnostic behavior.
690 CompatibleVoidPtrToNonVoidPtr,
691
692 /// PointerToInt - The assignment converts a pointer to an int, which we
693 /// accept as an extension.
694 PointerToInt,
695
696 /// IntToPointer - The assignment converts an int to a pointer, which we
697 /// accept as an extension.
698 IntToPointer,
699
700 /// FunctionVoidPointer - The assignment is between a function pointer and
701 /// void*, which the standard doesn't allow, but we accept as an extension.
702 FunctionVoidPointer,
703
704 /// IncompatiblePointer - The assignment is between two pointers types that
705 /// are not compatible, but we accept them as an extension.
706 IncompatiblePointer,
707
708 /// IncompatibleFunctionPointer - The assignment is between two function
709 /// pointers types that are not compatible, but we accept them as an
710 /// extension.
711 IncompatibleFunctionPointer,
712
713 /// IncompatibleFunctionPointerStrict - The assignment is between two
714 /// function pointer types that are not identical, but are compatible,
715 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
716 /// may trip an indirect call runtime check.
717 IncompatibleFunctionPointerStrict,
718
719 /// IncompatiblePointerSign - The assignment is between two pointers types
720 /// which point to integers which have a different sign, but are otherwise
721 /// identical. This is a subset of the above, but broken out because it's by
722 /// far the most common case of incompatible pointers.
723 IncompatiblePointerSign,
724
725 /// CompatiblePointerDiscardsQualifiers - The assignment discards
726 /// c/v/r qualifiers, which we accept as an extension.
727 CompatiblePointerDiscardsQualifiers,
728
729 /// IncompatiblePointerDiscardsQualifiers - The assignment
730 /// discards qualifiers that we don't permit to be discarded,
731 /// like address spaces.
732 IncompatiblePointerDiscardsQualifiers,
733
734 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
735 /// discards overflow behavior annotations between otherwise compatible
736 /// pointer types.
737 IncompatiblePointerDiscardsOverflowBehavior,
738
739 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
740 /// changes address spaces in nested pointer types which is not allowed.
741 /// For instance, converting __private int ** to __generic int ** is
742 /// illegal even though __private could be converted to __generic.
743 IncompatibleNestedPointerAddressSpaceMismatch,
744
745 /// IncompatibleNestedPointerQualifiers - The assignment is between two
746 /// nested pointer types, and the qualifiers other than the first two
747 /// levels differ e.g. char ** -> const char **, but we accept them as an
748 /// extension.
749 IncompatibleNestedPointerQualifiers,
750
751 /// IncompatibleVectors - The assignment is between two vector types that
752 /// have the same size, which we accept as an extension.
753 IncompatibleVectors,
754
755 /// IntToBlockPointer - The assignment converts an int to a block
756 /// pointer. We disallow this.
757 IntToBlockPointer,
758
759 /// IncompatibleBlockPointer - The assignment is between two block
760 /// pointers types that are not compatible.
761 IncompatibleBlockPointer,
762
763 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
764 /// id type and something else (that is incompatible with it). For example,
765 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
766 IncompatibleObjCQualifiedId,
767
768 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
769 /// object with __weak qualifier.
770 IncompatibleObjCWeakRef,
771
772 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
773 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
774 IncompatibleOBTKinds,
775
776 /// CompatibleOBTDiscards - Assignment discards overflow behavior
777 CompatibleOBTDiscards,
778
779 /// Incompatible - We reject this conversion outright, it is invalid to
780 /// represent it in the AST.
781 Incompatible
782};
783
784/// The scope in which to find allocation functions.
785enum class AllocationFunctionScope {
786 /// Only look for allocation functions in the global scope.
787 Global,
788 /// Only look for allocation functions in the scope of the
789 /// allocated class.
790 Class,
791 /// Look for allocation functions in both the global scope
792 /// and in the scope of the allocated class.
793 Both
794};
795
796/// Describes the result of an "if-exists" condition check.
797enum class IfExistsResult {
798 /// The symbol exists.
799 Exists,
800
801 /// The symbol does not exist.
802 DoesNotExist,
803
804 /// The name is a dependent name, so the results will differ
805 /// from one instantiation to the next.
806 Dependent,
807
808 /// An error occurred.
809 Error
810};
811
812enum class CorrectTypoKind {
813 NonError, // CorrectTypo used in a non error recovery situation.
814 ErrorRecovery // CorrectTypo used in normal error recovery.
815};
816
817enum class OverloadKind {
818 /// This is a legitimate overload: the existing declarations are
819 /// functions or function templates with different signatures.
820 Overload,
821
822 /// This is not an overload because the signature exactly matches
823 /// an existing declaration.
824 Match,
825
826 /// This is not an overload because the lookup results contain a
827 /// non-function.
828 NonFunction
829};
830
831/// Contexts in which a converted constant expression is required.
832enum class CCEKind {
833 CaseValue, ///< Expression in a case label.
834 Enumerator, ///< Enumerator value with fixed underlying type.
835 TemplateArg, ///< Value of a non-type template parameter.
836 TempArgStrict, ///< As above, but applies strict template checking
837 ///< rules.
838 ArrayBound, ///< Array bound in array declarator or new-expression.
839 ExplicitBool, ///< Condition in an explicit(bool) specifier.
840 Noexcept, ///< Condition in a noexcept(bool) specifier.
841 StaticAssertMessageSize, ///< Call to size() in a static assert
842 ///< message.
843 StaticAssertMessageData, ///< Call to data() in a static assert
844 ///< message.
845 PackIndex ///< Index of a pack indexing expression or specifier.
846};
847
848/// Enums for the diagnostics of target, target_version and target_clones.
849namespace DiagAttrParams {
850enum DiagType { Unsupported, Duplicate, Unknown };
851enum Specifier { None, CPU, Tune };
852enum AttrName { Target, TargetClones, TargetVersion };
853} // end namespace DiagAttrParams
854
855void inferNoReturnAttr(Sema &S, Decl *D);
856
857#ifdef __GNUC__
858#pragma GCC diagnostic push
859#pragma GCC diagnostic ignored "-Wattributes"
860#endif
861/// Sema - This implements semantic analysis and AST building for C.
862/// \nosubgrouping
863class Sema final : public SemaBase {
864#ifdef __GNUC__
865#pragma GCC diagnostic pop
866#endif
867 // Table of Contents
868 // -----------------
869 // 1. Semantic Analysis (Sema.cpp)
870 // 2. API Notes (SemaAPINotes.cpp)
871 // 3. C++ Access Control (SemaAccess.cpp)
872 // 4. Attributes (SemaAttr.cpp)
873 // 5. Availability Attribute Handling (SemaAvailability.cpp)
874 // 6. Bounds Safety (SemaBoundsSafety.cpp)
875 // 7. Casts (SemaCast.cpp)
876 // 8. Extra Semantic Checking (SemaChecking.cpp)
877 // 9. C++ Coroutines (SemaCoroutine.cpp)
878 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
879 // 11. Declarations (SemaDecl.cpp)
880 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
881 // 13. C++ Declarations (SemaDeclCXX.cpp)
882 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
883 // 15. Expressions (SemaExpr.cpp)
884 // 16. C++ Expressions (SemaExprCXX.cpp)
885 // 17. Member Access Expressions (SemaExprMember.cpp)
886 // 18. Initializers (SemaInit.cpp)
887 // 19. C++ Lambda Expressions (SemaLambda.cpp)
888 // 20. Name Lookup (SemaLookup.cpp)
889 // 21. Modules (SemaModule.cpp)
890 // 22. C++ Overloading (SemaOverload.cpp)
891 // 23. Statements (SemaStmt.cpp)
892 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
893 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
894 // 26. C++ Templates (SemaTemplate.cpp)
895 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
896 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
897 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
898 // 30. C++ Template Declaration Instantiation
899 // (SemaTemplateInstantiateDecl.cpp)
900 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
901 // 32. Constraints and Concepts (SemaConcept.cpp)
902 // 33. Types (SemaType.cpp)
903 // 34. FixIt Helpers (SemaFixItUtils.cpp)
904 // 35. Function Effects (SemaFunctionEffects.cpp)
905 // 36. C++ Expansion Statements (SemaExpand.cpp)
906
907 /// \name Semantic Analysis
908 /// Implementations are in Sema.cpp
909 ///@{
910
911public:
912 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
913 TranslationUnitKind TUKind = TU_Complete,
914 CodeCompleteConsumer *CompletionConsumer = nullptr);
915 ~Sema();
916
917 /// Perform initialization that occurs after the parser has been
918 /// initialized but before it parses anything.
919 void Initialize();
920
921 /// This virtual key function only exists to limit the emission of debug info
922 /// describing the Sema class. GCC and Clang only emit debug info for a class
923 /// with a vtable when the vtable is emitted. Sema is final and not
924 /// polymorphic, but the debug info size savings are so significant that it is
925 /// worth adding a vtable just to take advantage of this optimization.
926 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
927
928 const LangOptions &getLangOpts() const { return LangOpts; }
929 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
930 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
931
932 DiagnosticsEngine &getDiagnostics() const { return Diags; }
933 SourceManager &getSourceManager() const { return SourceMgr; }
934 Preprocessor &getPreprocessor() const { return PP; }
935 ASTContext &getASTContext() const { return Context; }
936 ASTConsumer &getASTConsumer() const { return Consumer; }
937 ASTMutationListener *getASTMutationListener() const;
938 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
939
940 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
941 StringRef Platform);
942 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
943
944 /// Registers an external source. If an external source already exists,
945 /// creates a multiplex external source and appends to it.
946 ///
947 ///\param[in] E - A non-null external sema source.
948 ///
949 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
950
951 /// Print out statistics about the semantic analysis.
952 void PrintStats() const;
953
954 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
955 /// guaranteed). Produces a warning if we're low on stack space and allocates
956 /// more in that case. Use this in code that may recurse deeply (for example,
957 /// in template instantiation) to avoid stack overflow.
958 void runWithSufficientStackSpace(SourceLocation Loc,
959 llvm::function_ref<void()> Fn);
960
961 /// Returns default addr space for method qualifiers.
962 LangAS getDefaultCXXMethodAddrSpace() const;
963
964 /// Load weak undeclared identifiers from the external source.
965 void LoadExternalWeakUndeclaredIdentifiers();
966
967 /// Load #pragma redefine_extname'd undeclared identifiers from the external
968 /// source.
969 void LoadExternalExtnameUndeclaredIdentifiers();
970
971 /// Determine if VD, which must be a variable or function, is an external
972 /// symbol that nonetheless can't be referenced from outside this translation
973 /// unit because its type has no linkage and it's not extern "C".
974 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
975
976 /// Determines whether the given source location is in the main file
977 /// and we're in a context where we should warn about unused entities.
978 bool isMainFileLoc(SourceLocation Loc) const;
979
980 /// Obtain a sorted list of functions that are undefined but ODR-used.
981 void getUndefinedButUsed(
982 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
983
984 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
985 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
986 /// Retrieves list of suspicious delete-expressions that will be checked at
987 /// the end of translation unit.
988 const llvm::MapVector<FieldDecl *, DeleteLocs> &
989 getMismatchingDeleteExpressions() const;
990
991 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
992 /// This is closely coupled to the SemaDiagnosticBuilder class and
993 /// should not be used elsewhere.
994 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
995
996 void addImplicitTypedef(StringRef Name, QualType T);
997
998 /// Whether uncompilable error has occurred. This includes error happens
999 /// in deferred diagnostics.
1000 bool hasUncompilableErrorOccurred() const;
1001
1002 /// Looks through the macro-expansion chain for the given
1003 /// location, looking for a macro expansion with the given name.
1004 /// If one is found, returns true and sets the location to that
1005 /// expansion loc.
1006 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1007
1008 /// Calls \c Lexer::getLocForEndOfToken()
1009 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1010
1011 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1012 /// locations of both ends of the token can be resolved it return that
1013 /// range; Otherwise it returns an invalid SourceRange.
1014 SourceRange getRangeForNextToken(
1015 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1016 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1017
1018 /// Retrieve the module loader associated with the preprocessor.
1019 ModuleLoader &getModuleLoader() const;
1020
1021 /// Invent a new identifier for parameters of abbreviated templates.
1022 IdentifierInfo *
1023 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1024 unsigned Index);
1025
1026 void emitAndClearUnusedLocalTypedefWarnings();
1027
1028 // Emit all deferred diagnostics.
1029 void emitDeferredDiags();
1030
1031 /// This is called before the very first declaration in the translation unit
1032 /// is parsed. Note that the ASTContext may have already injected some
1033 /// declarations.
1034 void ActOnStartOfTranslationUnit();
1035 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1036 /// translation unit when EOF is reached and all but the top-level scope is
1037 /// popped.
1038 void ActOnEndOfTranslationUnit();
1039 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1040
1041 /// Determines the active Scope associated with the given declaration
1042 /// context.
1043 ///
1044 /// This routine maps a declaration context to the active Scope object that
1045 /// represents that declaration context in the parser. It is typically used
1046 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1047 /// declarations) that injects a name for name-lookup purposes and, therefore,
1048 /// must update the Scope.
1049 ///
1050 /// \returns The scope corresponding to the given declaraion context, or NULL
1051 /// if no such scope is open.
1052 Scope *getScopeForContext(DeclContext *Ctx);
1053
1054 void PushFunctionScope();
1055 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1056 sema::LambdaScopeInfo *PushLambdaScope();
1057
1058 /// This is used to inform Sema what the current TemplateParameterDepth
1059 /// is during Parsing. Currently it is used to pass on the depth
1060 /// when parsing generic lambda 'auto' parameters.
1061 void RecordParsingTemplateParameterDepth(unsigned Depth);
1062
1063 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1064 RecordDecl *RD, CapturedRegionKind K,
1065 unsigned OpenMPCaptureLevel = 0);
1066
1067 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1068 /// time after they've been popped.
1069 class PoppedFunctionScopeDeleter {
1070 Sema *Self;
1071
1072 public:
1073 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1074 void operator()(sema::FunctionScopeInfo *Scope) const;
1075 };
1076
1077 using PoppedFunctionScopePtr =
1078 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1079
1080 /// Pop a function (or block or lambda or captured region) scope from the
1081 /// stack.
1082 ///
1083 /// \param WP The warning policy to use for CFG-based warnings, or null if
1084 /// such warnings should not be produced.
1085 /// \param D The declaration corresponding to this function scope, if
1086 /// producing CFG-based warnings.
1087 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1088 PoppedFunctionScopePtr
1089 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1090 Decl *D = nullptr, QualType BlockType = QualType());
1091
1092 sema::FunctionScopeInfo *getEnclosingFunction() const;
1093
1094 void setFunctionHasBranchIntoScope();
1095 void setFunctionHasBranchProtectedScope();
1096 void setFunctionHasIndirectGoto();
1097 void setFunctionHasMustTail();
1098
1099 void PushCompoundScope(bool IsStmtExpr);
1100 void PopCompoundScope();
1101
1102 /// Determine whether any errors occurred within this function/method/
1103 /// block.
1104 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1105
1106 /// Retrieve the current block, if any.
1107 sema::BlockScopeInfo *getCurBlock();
1108
1109 /// Get the innermost lambda or block enclosing the current location, if any.
1110 /// This looks through intervening non-lambda, non-block scopes such as local
1111 /// functions.
1112 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1113
1114 /// Retrieve the current lambda scope info, if any.
1115 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1116 /// lambda scope info ignoring all inner capturing scopes that are not
1117 /// lambda scopes.
1118 sema::LambdaScopeInfo *
1119 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1120
1121 /// Retrieve the current generic lambda info, if any.
1122 sema::LambdaScopeInfo *getCurGenericLambda();
1123
1124 /// Retrieve the current captured region, if any.
1125 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1126
1127 void ActOnComment(SourceRange Comment);
1128
1129 /// Returns true if any of the documentation warnings is enabled at \p Loc.
1130 bool areDocumentationDiagsEnabled(SourceLocation Loc);
1131
1132 /// Discard the areDocumentationDiagsEnabled() cache, for when a
1133 /// `#pragma clang diagnostic` has changed diagnostic severities.
1134 void clearDocumentationDiagsCache();
1135
1136private:
1137 /// The uncached answer for both documentation groups at \p Loc.
1138 bool computeDocumentationDiagsAt(SourceLocation Loc) const;
1139
1140 /// Caches results for areDocumentationDiagsEnabled().
1141 /// Flushed whenever a diagnostic pragma changes severities.
1142 /// Level one is keyed on the diagnostic state alone.
1143 const void *DocDiagsStateKey = nullptr;
1144 bool DocDiagsEnabledIgnoringSystem = false;
1145
1146 /// Level two, for when the location does matter. Bit i of each mask is a
1147 /// DiagStateSystemClass value; bit 0 is unused.
1148 uint8_t DocDiagsExactComputed = 0;
1149 uint8_t DocDiagsExactEnabled = 0;
1150
1151public:
1152 /// Returns true if a comment at \p Loc should be retained in the AST
1153 /// (some consumer such as -Wdocumentation, -fparse-all-comments, code
1154 /// completion, or AST-file serialization may read it back).
1155 bool shouldRetainCommentsInAST(SourceLocation Loc);
1156
1157 /// Retrieve the parser's current scope.
1158 ///
1159 /// This routine must only be used when it is certain that semantic analysis
1160 /// and the parser are in precisely the same context, which is not the case
1161 /// when, e.g., we are performing any kind of template instantiation.
1162 /// Therefore, the only safe places to use this scope are in the parser
1163 /// itself and in routines directly invoked from the parser and *never* from
1164 /// template substitution or instantiation.
1165 Scope *getCurScope() const { return CurScope; }
1166
1167 IdentifierInfo *getSuperIdentifier() const;
1168
1169 DeclContext *getCurLexicalContext() const {
1170 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1171 }
1172
1173 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1174 const FunctionDecl *FD = nullptr);
1175 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1176 const PartialDiagnostic &PD,
1177 const FunctionDecl *FD = nullptr) {
1178 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1179 }
1180
1181 /// Check if the type is allowed to be used for the current target.
1182 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1183 ValueDecl *D = nullptr);
1184
1185 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1186 /// cast. If there is already an implicit cast, merge into the existing one.
1187 /// If isLvalue, the result of the cast is an lvalue.
1188 ExprResult ImpCastExprToType(
1189 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1190 const CXXCastPath *BasePath = nullptr,
1191 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1192
1193 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1194 /// to the conversion from scalar type ScalarTy to the Boolean type.
1195 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1196
1197 /// If \p AllowLambda is true, treat lambda as function.
1198 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1199
1200 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1201 /// current context is not inside a function. If \p AllowLambda is true,
1202 /// this can return the call operator of an enclosing lambda, otherwise
1203 /// lambdas are skipped when looking for an enclosing function.
1204 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1205
1206 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1207 /// the method decl for the method being parsed. If we're currently
1208 /// in a 'block', this returns the containing context.
1209 ObjCMethodDecl *getCurMethodDecl();
1210
1211 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1212 /// or C function we're in, otherwise return null. If we're currently
1213 /// in a 'block', this returns the containing context.
1214 NamedDecl *getCurFunctionOrMethodDecl() const;
1215
1216 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1217 /// _Nonnull one.
1218 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1219 SourceLocation Loc);
1220
1221 /// Warn when implicitly casting 0 to nullptr.
1222 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1223
1224 /// Warn when implicitly changing function effects.
1225 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1226 SourceLocation Loc);
1227
1228 /// makeUnavailableInSystemHeader - There is an error in the current
1229 /// context. If we're still in a system header, and we can plausibly
1230 /// make the relevant declaration unavailable instead of erroring, do
1231 /// so and return true.
1232 bool makeUnavailableInSystemHeader(SourceLocation loc,
1233 UnavailableAttr::ImplicitReason reason);
1234
1235 /// Retrieve a suitable printing policy for diagnostics.
1236 PrintingPolicy getPrintingPolicy() const {
1237 return getPrintingPolicy(Ctx: Context, PP);
1238 }
1239
1240 /// Retrieve a suitable printing policy for diagnostics.
1241 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1242 const Preprocessor &PP);
1243
1244 /// Scope actions.
1245 void ActOnTranslationUnitScope(Scope *S);
1246
1247 /// Determine whether \param D is function like (function or function
1248 /// template) for parsing.
1249 bool isDeclaratorFunctionLike(Declarator &D);
1250
1251 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1252 /// because that allows us not to duplicate the constants in clang code,
1253 /// which we must to since we can't directly use the llvm constants.
1254 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1255 ///
1256 /// This is the greatest alignment value supported by load, store, and alloca
1257 /// instructions, and global values.
1258 static const unsigned MaxAlignmentExponent = 32;
1259 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1260
1261 /// Flag indicating whether or not to collect detailed statistics.
1262 bool CollectStats;
1263
1264 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1265
1266 /// Stack containing information about each of the nested
1267 /// function, block, and method scopes that are currently active.
1268 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1269
1270 /// The index of the first FunctionScope that corresponds to the current
1271 /// context.
1272 unsigned FunctionScopesStart = 0;
1273
1274 /// Track the number of currently active capturing scopes.
1275 unsigned CapturingFunctionScopes = 0;
1276
1277 llvm::BumpPtrAllocator BumpAlloc;
1278
1279 /// The kind of translation unit we are processing.
1280 ///
1281 /// When we're processing a complete translation unit, Sema will perform
1282 /// end-of-translation-unit semantic tasks (such as creating
1283 /// initializers for tentative definitions in C) once parsing has
1284 /// completed. Modules and precompiled headers perform different kinds of
1285 /// checks.
1286 const TranslationUnitKind TUKind;
1287
1288 /// Translation Unit Scope - useful to Objective-C actions that need
1289 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1290 /// For example, user-defined classes, built-in "id" type, etc.
1291 Scope *TUScope;
1292
1293 void incrementMSManglingNumber() const {
1294 return CurScope->incrementMSManglingNumber();
1295 }
1296
1297 /// Try to recover by turning the given expression into a
1298 /// call. Returns true if recovery was attempted or an error was
1299 /// emitted; this may also leave the ExprResult invalid.
1300 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1301 bool ForceComplain = false,
1302 bool (*IsPlausibleResult)(QualType) = nullptr);
1303
1304 // Adds implicit lifetime bound attribute for implicit this to its
1305 // TypeSourceInfo.
1306 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1307
1308 /// Figure out if an expression could be turned into a call.
1309 ///
1310 /// Use this when trying to recover from an error where the programmer may
1311 /// have written just the name of a function instead of actually calling it.
1312 ///
1313 /// \param E - The expression to examine.
1314 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1315 /// with no arguments, this parameter is set to the type returned by such a
1316 /// call; otherwise, it is set to an empty QualType.
1317 /// \param OverloadSet - If the expression is an overloaded function
1318 /// name, this parameter is populated with the decls of the various
1319 /// overloads.
1320 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1321 UnresolvedSetImpl &NonTemplateOverloads);
1322
1323 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1324 typedef OpaquePtr<TemplateName> TemplateTy;
1325 typedef OpaquePtr<QualType> TypeTy;
1326
1327 OpenCLOptions OpenCLFeatures;
1328 FPOptions CurFPFeatures;
1329
1330 const LangOptions &LangOpts;
1331 Preprocessor &PP;
1332 ASTContext &Context;
1333 ASTConsumer &Consumer;
1334 DiagnosticsEngine &Diags;
1335 SourceManager &SourceMgr;
1336 api_notes::APINotesManager APINotes;
1337
1338 std::unique_ptr<APINotesSelectorDiagnosticState> APINotesSelectorDiagnostics;
1339
1340 /// A RAII object to enter scope of a compound statement.
1341 class CompoundScopeRAII {
1342 public:
1343 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1344 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1345 }
1346
1347 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1348 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1349 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1350
1351 private:
1352 Sema &S;
1353 };
1354
1355 /// An RAII helper that pops function a function scope on exit.
1356 struct FunctionScopeRAII {
1357 Sema &S;
1358 bool Active;
1359 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1360 ~FunctionScopeRAII() {
1361 if (Active)
1362 S.PopFunctionScopeInfo();
1363 }
1364 void disable() { Active = false; }
1365 };
1366
1367 sema::FunctionScopeInfo *getCurFunction() const {
1368 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1369 }
1370
1371 /// Worker object for performing CFG-based warnings.
1372 sema::AnalysisBasedWarnings AnalysisWarnings;
1373 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1374
1375 /// Callback to the parser to parse templated functions when needed.
1376 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1377 LateTemplateParserCB *LateTemplateParser;
1378 void *OpaqueParser;
1379
1380 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1381 LateTemplateParser = LTP;
1382 OpaqueParser = P;
1383 }
1384
1385 /// Callback to the parser to parse a type expressed as a string.
1386 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1387 ParseTypeFromStringCallback;
1388
1389 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1390 /// This is used as part of a hack to omit that class from ADL results.
1391 DeclarationName VAListTagName;
1392
1393 /// Is the last error level diagnostic immediate. This is used to determined
1394 /// whether the next info diagnostic should be immediate.
1395 bool IsLastErrorImmediate = true;
1396
1397 /// Track if we're currently analyzing overflow behavior types in assignment
1398 /// context.
1399 bool InOverflowBehaviorAssignmentContext = false;
1400
1401 class DelayedDiagnostics;
1402
1403 class DelayedDiagnosticsState {
1404 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1405 friend class Sema::DelayedDiagnostics;
1406 };
1407 typedef DelayedDiagnosticsState ParsingDeclState;
1408 typedef DelayedDiagnosticsState ProcessingContextState;
1409
1410 /// A class which encapsulates the logic for delaying diagnostics
1411 /// during parsing and other processing.
1412 class DelayedDiagnostics {
1413 /// The current pool of diagnostics into which delayed
1414 /// diagnostics should go.
1415 sema::DelayedDiagnosticPool *CurPool = nullptr;
1416
1417 public:
1418 DelayedDiagnostics() = default;
1419
1420 /// Adds a delayed diagnostic.
1421 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1422
1423 /// Determines whether diagnostics should be delayed.
1424 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1425
1426 /// Returns the current delayed-diagnostics pool.
1427 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1428
1429 /// Enter a new scope. Access and deprecation diagnostics will be
1430 /// collected in this pool.
1431 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1432 DelayedDiagnosticsState state;
1433 state.SavedPool = CurPool;
1434 CurPool = &pool;
1435 return state;
1436 }
1437
1438 /// Leave a delayed-diagnostic state that was previously pushed.
1439 /// Do not emit any of the diagnostics. This is performed as part
1440 /// of the bookkeeping of popping a pool "properly".
1441 void popWithoutEmitting(DelayedDiagnosticsState state) {
1442 CurPool = state.SavedPool;
1443 }
1444
1445 /// Enter a new scope where access and deprecation diagnostics are
1446 /// not delayed.
1447 DelayedDiagnosticsState pushUndelayed() {
1448 DelayedDiagnosticsState state;
1449 state.SavedPool = CurPool;
1450 CurPool = nullptr;
1451 return state;
1452 }
1453
1454 /// Undo a previous pushUndelayed().
1455 void popUndelayed(DelayedDiagnosticsState state) {
1456 assert(CurPool == nullptr);
1457 CurPool = state.SavedPool;
1458 }
1459 } DelayedDiagnostics;
1460
1461 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1462 return DelayedDiagnostics.push(pool);
1463 }
1464
1465 /// Diagnostics that are emitted only if we discover that the given function
1466 /// must be codegen'ed. Because handling these correctly adds overhead to
1467 /// compilation, this is currently only used for offload languages like CUDA,
1468 /// OpenMP, and SYCL.
1469 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1470
1471 /// An inverse call graph, mapping known-emitted functions to their
1472 /// known-emitted callers (plus the location of the call). It is populated
1473 /// while emitting deferred diagnostics and is used to print call stack notes
1474 /// for all offload languages.
1475 ///
1476 /// Functions that we can tell a priori must be emitted aren't added to this
1477 /// map. A function may have multiple callers that force it into device
1478 /// context, so we store all of them to produce complete diagnostics.
1479 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<const FunctionDecl>,
1480 /* Callers = */ llvm::SmallVector<FunctionDeclAndLoc, 1>>
1481 DeviceKnownEmittedFns;
1482
1483 /// CurContext - This is the current declaration context of parsing.
1484 DeclContext *CurContext;
1485
1486 SemaAMDGPU &AMDGPU() {
1487 assert(AMDGPUPtr);
1488 return *AMDGPUPtr;
1489 }
1490
1491 SemaARM &ARM() {
1492 assert(ARMPtr);
1493 return *ARMPtr;
1494 }
1495
1496 SemaAVR &AVR() {
1497 assert(AVRPtr);
1498 return *AVRPtr;
1499 }
1500
1501 SemaBPF &BPF() {
1502 assert(BPFPtr);
1503 return *BPFPtr;
1504 }
1505
1506 SemaCodeCompletion &CodeCompletion() {
1507 assert(CodeCompletionPtr);
1508 return *CodeCompletionPtr;
1509 }
1510
1511 SemaCUDA &CUDA() {
1512 assert(CUDAPtr);
1513 return *CUDAPtr;
1514 }
1515
1516 SemaDirectX &DirectX() {
1517 assert(DirectXPtr);
1518 return *DirectXPtr;
1519 }
1520
1521 SemaHLSL &HLSL() {
1522 assert(HLSLPtr);
1523 return *HLSLPtr;
1524 }
1525
1526 SemaHexagon &Hexagon() {
1527 assert(HexagonPtr);
1528 return *HexagonPtr;
1529 }
1530
1531 SemaLoongArch &LoongArch() {
1532 assert(LoongArchPtr);
1533 return *LoongArchPtr;
1534 }
1535
1536 SemaM68k &M68k() {
1537 assert(M68kPtr);
1538 return *M68kPtr;
1539 }
1540
1541 SemaMIPS &MIPS() {
1542 assert(MIPSPtr);
1543 return *MIPSPtr;
1544 }
1545
1546 SemaMSP430 &MSP430() {
1547 assert(MSP430Ptr);
1548 return *MSP430Ptr;
1549 }
1550
1551 SemaNVPTX &NVPTX() {
1552 assert(NVPTXPtr);
1553 return *NVPTXPtr;
1554 }
1555
1556 SemaObjC &ObjC() {
1557 assert(ObjCPtr);
1558 return *ObjCPtr;
1559 }
1560
1561 SemaOpenACC &OpenACC() {
1562 assert(OpenACCPtr);
1563 return *OpenACCPtr;
1564 }
1565
1566 SemaOpenCL &OpenCL() {
1567 assert(OpenCLPtr);
1568 return *OpenCLPtr;
1569 }
1570
1571 SemaOpenMP &OpenMP() {
1572 assert(OpenMPPtr && "SemaOpenMP is dead");
1573 return *OpenMPPtr;
1574 }
1575
1576 SemaPPC &PPC() {
1577 assert(PPCPtr);
1578 return *PPCPtr;
1579 }
1580
1581 SemaPseudoObject &PseudoObject() {
1582 assert(PseudoObjectPtr);
1583 return *PseudoObjectPtr;
1584 }
1585
1586 SemaRISCV &RISCV() {
1587 assert(RISCVPtr);
1588 return *RISCVPtr;
1589 }
1590
1591 SemaSPIRV &SPIRV() {
1592 assert(SPIRVPtr);
1593 return *SPIRVPtr;
1594 }
1595
1596 SemaSYCL &SYCL() {
1597 assert(SYCLPtr);
1598 return *SYCLPtr;
1599 }
1600
1601 SemaSwift &Swift() {
1602 assert(SwiftPtr);
1603 return *SwiftPtr;
1604 }
1605
1606 SemaSystemZ &SystemZ() {
1607 assert(SystemZPtr);
1608 return *SystemZPtr;
1609 }
1610
1611 SemaWasm &Wasm() {
1612 assert(WasmPtr);
1613 return *WasmPtr;
1614 }
1615
1616 SemaX86 &X86() {
1617 assert(X86Ptr);
1618 return *X86Ptr;
1619 }
1620
1621 /// Source of additional semantic information.
1622 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1623
1624protected:
1625 friend class Parser;
1626 friend class InitializationSequence;
1627 friend class ASTReader;
1628 friend class ASTDeclReader;
1629 friend class ASTWriter;
1630
1631private:
1632 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1633 bool WarnedDarwinSDKInfoMissing = false;
1634
1635 StackExhaustionHandler StackHandler;
1636
1637 Sema(const Sema &) = delete;
1638 void operator=(const Sema &) = delete;
1639
1640 /// The handler for the FileChanged preprocessor events.
1641 ///
1642 /// Used for diagnostics that implement custom semantic analysis for #include
1643 /// directives, like -Wpragma-pack.
1644 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1645
1646 /// The parser's current scope.
1647 ///
1648 /// The parser maintains this state here.
1649 Scope *CurScope;
1650
1651 mutable IdentifierInfo *Ident_super;
1652
1653 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1654 std::unique_ptr<SemaARM> ARMPtr;
1655 std::unique_ptr<SemaAVR> AVRPtr;
1656 std::unique_ptr<SemaBPF> BPFPtr;
1657 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1658 std::unique_ptr<SemaCUDA> CUDAPtr;
1659 std::unique_ptr<SemaDirectX> DirectXPtr;
1660 std::unique_ptr<SemaHLSL> HLSLPtr;
1661 std::unique_ptr<SemaHexagon> HexagonPtr;
1662 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1663 std::unique_ptr<SemaM68k> M68kPtr;
1664 std::unique_ptr<SemaMIPS> MIPSPtr;
1665 std::unique_ptr<SemaMSP430> MSP430Ptr;
1666 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1667 std::unique_ptr<SemaObjC> ObjCPtr;
1668 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1669 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1670 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1671 std::unique_ptr<SemaPPC> PPCPtr;
1672 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1673 std::unique_ptr<SemaRISCV> RISCVPtr;
1674 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1675 std::unique_ptr<SemaSYCL> SYCLPtr;
1676 std::unique_ptr<SemaSwift> SwiftPtr;
1677 std::unique_ptr<SemaSystemZ> SystemZPtr;
1678 std::unique_ptr<SemaWasm> WasmPtr;
1679 std::unique_ptr<SemaX86> X86Ptr;
1680
1681 ///@}
1682
1683 //
1684 //
1685 // -------------------------------------------------------------------------
1686 //
1687 //
1688
1689 /// \name API Notes
1690 /// Implementations are in SemaAPINotes.cpp
1691 ///@{
1692
1693public:
1694 /// Map any API notes provided for this declaration to attributes on the
1695 /// declaration.
1696 ///
1697 /// Triggered by declaration-attribute processing.
1698 void ProcessAPINotes(Decl *D);
1699 /// Apply the 'Nullability:' annotation to the specified declaration
1700 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1701 /// Apply the 'Type:' annotation to the specified declaration
1702 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1703
1704 /// Diagnose exact API notes selectors that were not matched by any
1705 /// declaration processed in this translation unit.
1706 void DiagnoseUnusedAPINotesSelectors();
1707
1708 /// Whether APINotes should be gathered for all applicable Swift language
1709 /// versions, without being applied. Leaving clients of the current module
1710 /// to select and apply the correct version.
1711 bool captureSwiftVersionIndependentAPINotes() {
1712 return APINotes.captureVersionIndependentSwift();
1713 }
1714 ///@}
1715
1716 //
1717 //
1718 // -------------------------------------------------------------------------
1719 //
1720 //
1721
1722 /// \name C++ Access Control
1723 /// Implementations are in SemaAccess.cpp
1724 ///@{
1725
1726public:
1727 enum AccessResult {
1728 AR_accessible,
1729 AR_inaccessible,
1730 AR_dependent,
1731 AR_delayed
1732 };
1733
1734 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1735 /// Returns true on error (when the previous member decl access specifier
1736 /// is different from the new member decl access specifier).
1737 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1738 NamedDecl *PrevMemberDecl,
1739 AccessSpecifier LexicalAS);
1740
1741 /// Perform access-control checking on a previously-unresolved member
1742 /// access which has now been resolved to a member.
1743 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1744 DeclAccessPair FoundDecl);
1745 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1746 DeclAccessPair FoundDecl);
1747
1748 /// Checks access to an overloaded operator new or delete.
1749 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1750 SourceRange PlacementRange,
1751 CXXRecordDecl *NamingClass,
1752 DeclAccessPair FoundDecl,
1753 bool Diagnose = true);
1754
1755 /// Checks access to a constructor.
1756 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1757 DeclAccessPair FoundDecl,
1758 const InitializedEntity &Entity,
1759 bool IsCopyBindingRefToTemp = false);
1760
1761 /// Checks access to a constructor.
1762 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1763 DeclAccessPair FoundDecl,
1764 const InitializedEntity &Entity,
1765 const PartialDiagnostic &PDiag);
1766 AccessResult CheckDestructorAccess(SourceLocation Loc,
1767 CXXDestructorDecl *Dtor,
1768 const PartialDiagnostic &PDiag,
1769 QualType objectType = QualType());
1770
1771 /// Checks access to the target of a friend declaration.
1772 AccessResult CheckFriendAccess(NamedDecl *D);
1773
1774 /// Checks access to a member.
1775 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1776 CXXRecordDecl *NamingClass,
1777 DeclAccessPair Found);
1778
1779 /// Checks implicit access to a member in a structured binding.
1780 AccessResult
1781 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1782 CXXRecordDecl *DecomposedClass,
1783 DeclAccessPair Field);
1784 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1785 const SourceRange &,
1786 DeclAccessPair FoundDecl);
1787
1788 /// Checks access to an overloaded member operator, including
1789 /// conversion operators.
1790 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1791 Expr *ArgExpr,
1792 DeclAccessPair FoundDecl);
1793 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1794 ArrayRef<Expr *> ArgExprs,
1795 DeclAccessPair FoundDecl);
1796 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1797 DeclAccessPair FoundDecl);
1798
1799 /// Checks access for a hierarchy conversion.
1800 ///
1801 /// \param ForceCheck true if this check should be performed even if access
1802 /// control is disabled; some things rely on this for semantics
1803 /// \param ForceUnprivileged true if this check should proceed as if the
1804 /// context had no special privileges
1805 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1806 QualType Derived, const CXXBasePath &Path,
1807 unsigned DiagID, bool ForceCheck = false,
1808 bool ForceUnprivileged = false);
1809
1810 AccessResult CheckBaseClassAccess(
1811 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1812 const CXXBasePath &Path, unsigned DiagID,
1813 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1814 bool ForceCheck = false, bool ForceUnprivileged = false);
1815
1816 /// Checks access to all the declarations in the given result set.
1817 void CheckLookupAccess(const LookupResult &R);
1818
1819 /// Checks access to Target from the given class. The check will take access
1820 /// specifiers into account, but no member access expressions and such.
1821 ///
1822 /// \param Target the declaration to check if it can be accessed
1823 /// \param NamingClass the class in which the lookup was started.
1824 /// \param BaseType type of the left side of member access expression.
1825 /// \p BaseType and \p NamingClass are used for C++ access control.
1826 /// Depending on the lookup case, they should be set to the following:
1827 /// - lhs.target (member access without a qualifier):
1828 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1829 /// - lhs.X::target (member access with a qualifier):
1830 /// BaseType is the type of 'lhs', NamingClass is 'X'
1831 /// - X::target (qualified lookup without member access):
1832 /// BaseType is null, NamingClass is 'X'.
1833 /// - target (unqualified lookup).
1834 /// BaseType is null, NamingClass is the parent class of 'target'.
1835 /// \return true if the Target is accessible from the Class, false otherwise.
1836 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1837 QualType BaseType);
1838
1839 /// Is the given member accessible for the purposes of deciding whether to
1840 /// define a special member function as deleted?
1841 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1842 DeclAccessPair Found, QualType ObjectType,
1843 SourceLocation Loc,
1844 const PartialDiagnostic &Diag);
1845 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1846 DeclAccessPair Found,
1847 QualType ObjectType) {
1848 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1849 Loc: SourceLocation(), Diag: PDiag());
1850 }
1851
1852 void HandleDependentAccessCheck(
1853 const DependentDiagnostic &DD,
1854 const MultiLevelTemplateArgumentList &TemplateArgs);
1855 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1856
1857 ///@}
1858
1859 //
1860 //
1861 // -------------------------------------------------------------------------
1862 //
1863 //
1864
1865 /// \name Attributes
1866 /// Implementations are in SemaAttr.cpp
1867 ///@{
1868
1869public:
1870 /// Controls member pointer representation format under the MS ABI.
1871 LangOptions::PragmaMSPointersToMembersKind
1872 MSPointerToMemberRepresentationMethod;
1873
1874 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1875
1876 /// Source location for newly created implicit MSInheritanceAttrs
1877 SourceLocation ImplicitMSInheritanceAttrLoc;
1878
1879 struct PragmaClangSection {
1880 std::string SectionName;
1881 bool Valid = false;
1882 SourceLocation PragmaLocation;
1883 };
1884
1885 PragmaClangSection PragmaClangBSSSection;
1886 PragmaClangSection PragmaClangDataSection;
1887 PragmaClangSection PragmaClangRodataSection;
1888 PragmaClangSection PragmaClangRelroSection;
1889 PragmaClangSection PragmaClangTextSection;
1890
1891 enum PragmaMsStackAction {
1892 PSK_Reset = 0x0, // #pragma ()
1893 PSK_Set = 0x1, // #pragma (value)
1894 PSK_Push = 0x2, // #pragma (push[, id])
1895 PSK_Pop = 0x4, // #pragma (pop[, id])
1896 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1897 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1898 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1899 };
1900
1901 struct PragmaPackInfo {
1902 PragmaMsStackAction Action;
1903 StringRef SlotLabel;
1904 Token Alignment;
1905 };
1906
1907 // #pragma pack and align.
1908 class AlignPackInfo {
1909 public:
1910 // `Native` represents default align mode, which may vary based on the
1911 // platform.
1912 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1913
1914 // #pragma pack info constructor
1915 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1916 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1917 assert(Num == PackNumber && "The pack number has been truncated.");
1918 }
1919
1920 // #pragma align info constructor
1921 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1922 : PackAttr(false), AlignMode(M),
1923 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1924
1925 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1926
1927 AlignPackInfo() : AlignPackInfo(Native, false) {}
1928
1929 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1930 // integer encoding for it. This should only be passed to
1931 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1932 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1933 std::uint32_t Encoding{};
1934 if (Info.IsXLStack())
1935 Encoding |= IsXLMask;
1936
1937 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1938
1939 if (Info.IsPackAttr())
1940 Encoding |= PackAttrMask;
1941
1942 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1943
1944 return Encoding;
1945 }
1946
1947 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1948 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1949 AlignPackInfo::Mode M =
1950 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1951 int PackNumber = (Encoding & PackNumMask) >> 4;
1952
1953 if (Encoding & PackAttrMask)
1954 return AlignPackInfo(M, PackNumber, IsXL);
1955
1956 return AlignPackInfo(M, IsXL);
1957 }
1958
1959 bool IsPackAttr() const { return PackAttr; }
1960
1961 bool IsAlignAttr() const { return !PackAttr; }
1962
1963 Mode getAlignMode() const { return AlignMode; }
1964
1965 unsigned getPackNumber() const { return PackNumber; }
1966
1967 bool IsPackSet() const {
1968 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1969 // attriute on a decl.
1970 return PackNumber != UninitPackVal && PackNumber != 0;
1971 }
1972
1973 bool IsXLStack() const { return XLStack; }
1974
1975 bool operator==(const AlignPackInfo &Info) const {
1976 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1977 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1978 args: Info.XLStack);
1979 }
1980
1981 bool operator!=(const AlignPackInfo &Info) const {
1982 return !(*this == Info);
1983 }
1984
1985 private:
1986 /// \brief True if this is a pragma pack attribute,
1987 /// not a pragma align attribute.
1988 bool PackAttr;
1989
1990 /// \brief The alignment mode that is in effect.
1991 Mode AlignMode;
1992
1993 /// \brief The pack number of the stack.
1994 unsigned char PackNumber;
1995
1996 /// \brief True if it is a XL #pragma align/pack stack.
1997 bool XLStack;
1998
1999 /// \brief Uninitialized pack value.
2000 static constexpr unsigned char UninitPackVal = -1;
2001
2002 // Masks to encode and decode an AlignPackInfo.
2003 static constexpr uint32_t IsXLMask{0x0000'0001};
2004 static constexpr uint32_t AlignModeMask{0x0000'0006};
2005 static constexpr uint32_t PackAttrMask{0x00000'0008};
2006 static constexpr uint32_t PackNumMask{0x0000'01F0};
2007 };
2008
2009 template <typename ValueType> struct PragmaStack {
2010 struct Slot {
2011 llvm::StringRef StackSlotLabel;
2012 ValueType Value;
2013 SourceLocation PragmaLocation;
2014 SourceLocation PragmaPushLocation;
2015 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
2016 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
2017 : StackSlotLabel(StackSlotLabel), Value(Value),
2018 PragmaLocation(PragmaLocation),
2019 PragmaPushLocation(PragmaPushLocation) {}
2020 };
2021
2022 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
2023 llvm::StringRef StackSlotLabel, ValueType Value) {
2024 if (Action == PSK_Reset) {
2025 CurrentValue = DefaultValue;
2026 CurrentPragmaLocation = PragmaLocation;
2027 return;
2028 }
2029 if (Action & PSK_Push)
2030 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
2031 PragmaLocation);
2032 else if (Action & PSK_Pop) {
2033 if (!StackSlotLabel.empty()) {
2034 // If we've got a label, try to find it and jump there.
2035 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
2036 return x.StackSlotLabel == StackSlotLabel;
2037 });
2038 // If we found the label so pop from there.
2039 if (I != Stack.rend()) {
2040 CurrentValue = I->Value;
2041 CurrentPragmaLocation = I->PragmaLocation;
2042 Stack.erase(std::prev(I.base()), Stack.end());
2043 }
2044 } else if (!Stack.empty()) {
2045 // We do not have a label, just pop the last entry.
2046 CurrentValue = Stack.back().Value;
2047 CurrentPragmaLocation = Stack.back().PragmaLocation;
2048 Stack.pop_back();
2049 }
2050 }
2051 if (Action & PSK_Set) {
2052 CurrentValue = Value;
2053 CurrentPragmaLocation = PragmaLocation;
2054 }
2055 }
2056
2057 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2058 // method body to restore the stacks on exit, so it works like this:
2059 //
2060 // struct S {
2061 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2062 // void Method {}
2063 // #pragma <name>(pop, InternalPragmaSlot)
2064 // };
2065 //
2066 // It works even with #pragma vtordisp, although MSVC doesn't support
2067 // #pragma vtordisp(push [, id], n)
2068 // syntax.
2069 //
2070 // Push / pop a named sentinel slot.
2071 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2072 assert((Action == PSK_Push || Action == PSK_Pop) &&
2073 "Can only push / pop #pragma stack sentinels!");
2074 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2075 }
2076
2077 // Constructors.
2078 explicit PragmaStack(const ValueType &Default)
2079 : DefaultValue(Default), CurrentValue(Default) {}
2080
2081 bool hasValue() const { return CurrentValue != DefaultValue; }
2082
2083 SmallVector<Slot, 2> Stack;
2084 ValueType DefaultValue; // Value used for PSK_Reset action.
2085 ValueType CurrentValue;
2086 SourceLocation CurrentPragmaLocation;
2087 };
2088 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2089 // we shouldn't do so if they're in a module).
2090
2091 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2092 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2093 ///
2094 /// 0: Suppress all vtordisps
2095 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2096 /// structors
2097 /// 2: Always insert vtordisps to support RTTI on partially constructed
2098 /// objects
2099 PragmaStack<MSVtorDispMode> VtorDispStack;
2100 PragmaStack<AlignPackInfo> AlignPackStack;
2101 // The current #pragma align/pack values and locations at each #include.
2102 struct AlignPackIncludeState {
2103 AlignPackInfo CurrentValue;
2104 SourceLocation CurrentPragmaLocation;
2105 bool HasNonDefaultValue, ShouldWarnOnInclude;
2106 };
2107 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2108 // Segment #pragmas.
2109 PragmaStack<StringLiteral *> DataSegStack;
2110 PragmaStack<StringLiteral *> BSSSegStack;
2111 PragmaStack<StringLiteral *> ConstSegStack;
2112 PragmaStack<StringLiteral *> CodeSegStack;
2113
2114 // #pragma strict_gs_check.
2115 PragmaStack<bool> StrictGuardStackCheckStack;
2116
2117 // This stack tracks the current state of Sema.CurFPFeatures.
2118 PragmaStack<FPOptionsOverride> FpPragmaStack;
2119 FPOptionsOverride CurFPFeatureOverrides() {
2120 FPOptionsOverride result;
2121 if (!FpPragmaStack.hasValue()) {
2122 result = FPOptionsOverride();
2123 } else {
2124 result = FpPragmaStack.CurrentValue;
2125 }
2126 return result;
2127 }
2128
2129 enum PragmaSectionKind {
2130 PSK_DataSeg,
2131 PSK_BSSSeg,
2132 PSK_ConstSeg,
2133 PSK_CodeSeg,
2134 };
2135
2136 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2137 // Actions should be performed only if we enter / exit a C++ method body.
2138 class PragmaStackSentinelRAII {
2139 public:
2140 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2141 ~PragmaStackSentinelRAII();
2142 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2143 PragmaStackSentinelRAII &
2144 operator=(const PragmaStackSentinelRAII &) = delete;
2145
2146 private:
2147 Sema &S;
2148 StringRef SlotLabel;
2149 bool ShouldAct;
2150 };
2151
2152 /// Used for #pragma init_seg.
2153 struct InitSegPragmaState {
2154 SourceLocation PragmaLocation;
2155 StringLiteral *Segment = nullptr;
2156 FunctionDecl *Func = nullptr;
2157 };
2158 InitSegPragmaState CurInitSeg;
2159
2160 /// Sections used with #pragma alloc_text.
2161 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2162
2163 /// VisContext - Manages the stack for \#pragma GCC visibility.
2164 void *VisContext; // Really a "PragmaVisStack*"
2165
2166 /// This an attribute introduced by \#pragma clang attribute.
2167 struct PragmaAttributeEntry {
2168 SourceLocation Loc;
2169 ParsedAttr *Attribute;
2170 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2171 bool IsUsed;
2172 };
2173
2174 /// A push'd group of PragmaAttributeEntries.
2175 struct PragmaAttributeGroup {
2176 /// The location of the push attribute.
2177 SourceLocation Loc;
2178 /// The namespace of this push group.
2179 const IdentifierInfo *Namespace;
2180 SmallVector<PragmaAttributeEntry, 2> Entries;
2181 };
2182
2183 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2184
2185 /// The declaration that is currently receiving an attribute from the
2186 /// #pragma attribute stack.
2187 const Decl *PragmaAttributeCurrentTargetDecl;
2188
2189 /// This represents the last location of a "#pragma clang optimize off"
2190 /// directive if such a directive has not been closed by an "on" yet. If
2191 /// optimizations are currently "on", this is set to an invalid location.
2192 SourceLocation OptimizeOffPragmaLocation;
2193
2194 /// Get the location for the currently active "\#pragma clang optimize
2195 /// off". If this location is invalid, then the state of the pragma is "on".
2196 SourceLocation getOptimizeOffPragmaLocation() const {
2197 return OptimizeOffPragmaLocation;
2198 }
2199
2200 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2201 /// whether the optimizations in the list passed to the pragma should be
2202 /// turned off or on. This boolean is true by default because command line
2203 /// options are honored when `#pragma optimize("", on)`.
2204 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2205 bool MSPragmaOptimizeIsOn = true;
2206
2207 /// Set of no-builtin functions listed by \#pragma function.
2208 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2209
2210 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2211 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2212 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2213
2214 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2215 void AddMsStructLayoutForRecord(RecordDecl *RD);
2216
2217 /// Add gsl::Pointer attribute to std::container::iterator
2218 /// \param ND The declaration that introduces the name
2219 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2220 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2221
2222 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2223 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2224
2225 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2226 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2227
2228 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2229 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2230
2231 /// Add [[gsl::Pointer]] attributes for std:: types.
2232 void inferGslPointerAttribute(TypedefNameDecl *TD);
2233
2234 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2235 StringRef ParamName);
2236 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2237 // can be the name of a function parameter, we need to parse the function
2238 // declaration and rest of the parameters before processesing 'X'. Therefore
2239 // do this lazily instead of processing while parsing the annotation itself.
2240 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2241
2242 /// Add _Nullable attributes for std:: types.
2243 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2244
2245 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2246 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2247 PragmaClangSectionAction Action,
2248 PragmaClangSectionKind SecKind,
2249 StringRef SecName);
2250
2251 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2252 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2253 SourceLocation PragmaLoc);
2254
2255 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2256 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2257 StringRef SlotLabel, Expr *Alignment);
2258
2259 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2260 /// (unless they are value dependent or type dependent). Returns false
2261 /// and emits a diagnostic if one or more of the arguments could not be
2262 /// folded into a constant.
2263 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2264 MutableArrayRef<Expr *> Args);
2265
2266 enum class PragmaAlignPackDiagnoseKind {
2267 NonDefaultStateAtInclude,
2268 ChangedStateAtExit
2269 };
2270
2271 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2272 SourceLocation IncludeLoc);
2273 void DiagnoseUnterminatedPragmaAlignPack();
2274
2275 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2276 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2277
2278 /// ActOnPragmaMSComment - Called on well formed
2279 /// \#pragma comment(kind, "arg").
2280 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2281 StringRef Arg);
2282
2283 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2284 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2285 StringRef Value);
2286
2287 /// Are precise floating point semantics currently enabled?
2288 bool isPreciseFPEnabled() {
2289 return !CurFPFeatures.getAllowFPReassociate() &&
2290 !CurFPFeatures.getNoSignedZero() &&
2291 !CurFPFeatures.getAllowReciprocal() &&
2292 !CurFPFeatures.getAllowApproxFunc();
2293 }
2294
2295 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2296 LangOptions::FPEvalMethodKind Value);
2297
2298 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2299 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2300 PragmaFloatControlKind Value);
2301
2302 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2303 /// pointers_to_members(representation method[, general purpose
2304 /// representation]).
2305 void ActOnPragmaMSPointersToMembers(
2306 LangOptions::PragmaMSPointersToMembersKind Kind,
2307 SourceLocation PragmaLoc);
2308
2309 /// Called on well formed \#pragma vtordisp().
2310 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2311 SourceLocation PragmaLoc, MSVtorDispMode Value);
2312
2313 bool UnifySection(StringRef SectionName, int SectionFlags,
2314 NamedDecl *TheDecl);
2315 bool UnifySection(StringRef SectionName, int SectionFlags,
2316 SourceLocation PragmaSectionLocation);
2317
2318 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2319 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2320 PragmaMsStackAction Action,
2321 llvm::StringRef StackSlotLabel,
2322 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2323
2324 /// Called on well formed \#pragma section().
2325 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2326 StringLiteral *SegmentName);
2327
2328 /// Called on well-formed \#pragma init_seg().
2329 /// If a function name is provided (", func-name"), it is passed via Func.
2330 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2331 StringLiteral *SegmentName,
2332 IdentifierLoc *Func = nullptr);
2333
2334 /// Called on well-formed \#pragma alloc_text().
2335 void ActOnPragmaMSAllocText(
2336 SourceLocation PragmaLocation, StringRef Section,
2337 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2338 &Functions);
2339
2340 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2341 /// strict_gs_check.
2342 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2343 PragmaMsStackAction Action,
2344 bool Value);
2345
2346 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2347 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2348 SourceLocation PragmaLoc);
2349
2350 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2351 SourceLocation PragmaLoc,
2352 attr::ParsedSubjectMatchRuleSet Rules);
2353 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2354 const IdentifierInfo *Namespace);
2355
2356 /// Called on well-formed '\#pragma clang attribute pop'.
2357 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2358 const IdentifierInfo *Namespace);
2359
2360 /// Adds the attributes that have been specified using the
2361 /// '\#pragma clang attribute push' directives to the given declaration.
2362 void AddPragmaAttributes(Scope *S, Decl *D);
2363
2364 using InstantiationContextDiagFuncRef =
2365 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2366 auto getDefaultDiagFunc() {
2367 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2368 // This bypasses a lot of the filters in the diag engine, as it's
2369 // to be used to attach notes to diagnostics which have already
2370 // been filtered through.
2371 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2372 PD.Emit(DB: Builder);
2373 };
2374 }
2375
2376 void PrintPragmaAttributeInstantiationPoint(
2377 InstantiationContextDiagFuncRef DiagFunc);
2378 void PrintPragmaAttributeInstantiationPoint() {
2379 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2380 }
2381
2382 void DiagnoseUnterminatedPragmaAttribute();
2383
2384 /// Called on well formed \#pragma clang optimize.
2385 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2386
2387 /// #pragma optimize("[optimization-list]", on | off).
2388 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2389
2390 /// Call on well formed \#pragma function.
2391 void
2392 ActOnPragmaMSFunction(SourceLocation Loc,
2393 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2394
2395 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2396 SourceLocation NameLoc,
2397 Scope *curScope);
2398
2399 /// Information from a C++ #pragma export, for a symbol that we
2400 /// haven't seen the declaration for yet.
2401 struct PendingPragmaInfo {
2402 SourceLocation NameLoc;
2403 bool Used;
2404 };
2405
2406 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2407
2408 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2409 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2410 Scope *curScope);
2411
2412 /// Only called on function definitions; if there is a pragma in scope
2413 /// with the effect of a range-based optnone, consider marking the function
2414 /// with attribute optnone.
2415 void AddRangeBasedOptnone(FunctionDecl *FD);
2416
2417 /// Only called on function definitions; if there is a `#pragma alloc_text`
2418 /// that decides which code section the function should be in, add
2419 /// attribute section to the function.
2420 void AddSectionMSAllocText(FunctionDecl *FD);
2421
2422 /// Adds the 'optnone' attribute to the function declaration if there
2423 /// are no conflicts; Loc represents the location causing the 'optnone'
2424 /// attribute to be added (usually because of a pragma).
2425 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2426
2427 /// Only called on function definitions; if there is a MSVC #pragma optimize
2428 /// in scope, consider changing the function's attributes based on the
2429 /// optimization list passed to the pragma.
2430 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2431
2432 /// Only called on function definitions; if there is a pragma in scope
2433 /// with the effect of a range-based no_builtin, consider marking the function
2434 /// with attribute no_builtin.
2435 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2436
2437 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2438 /// add an appropriate visibility attribute.
2439 void AddPushedVisibilityAttribute(Decl *RD);
2440
2441 /// FreeVisContext - Deallocate and null out VisContext.
2442 void FreeVisContext();
2443
2444 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2445 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2446 SourceLocation PragmaLoc);
2447
2448 /// ActOnPragmaFPContract - Called on well formed
2449 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2450 /// \#pragma clang fp contract
2451 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2452
2453 /// Called on well formed
2454 /// \#pragma clang fp reassociate
2455 /// or
2456 /// \#pragma clang fp reciprocal
2457 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2458 bool IsEnabled);
2459
2460 /// ActOnPragmaFenvAccess - Called on well formed
2461 /// \#pragma STDC FENV_ACCESS
2462 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2463
2464 /// ActOnPragmaCXLimitedRange - Called on well formed
2465 /// \#pragma STDC CX_LIMITED_RANGE
2466 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2467 LangOptions::ComplexRangeKind Range);
2468
2469 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2470 void ActOnPragmaFPExceptions(SourceLocation Loc,
2471 LangOptions::FPExceptionModeKind);
2472
2473 /// Called to set constant rounding mode for floating point operations.
2474 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2475
2476 /// Called to set exception behavior for floating point operations.
2477 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2478
2479 /// PushNamespaceVisibilityAttr - Note that we've entered a
2480 /// namespace with a visibility attribute.
2481 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2482 SourceLocation Loc);
2483
2484 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2485 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2486 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2487
2488 /// Handles semantic checking for features that are common to all attributes,
2489 /// such as checking whether a parameter was properly specified, or the
2490 /// correct number of arguments were passed, etc. Returns true if the
2491 /// attribute has been diagnosed.
2492 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2493 bool SkipArgCountCheck = false);
2494 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2495 bool SkipArgCountCheck = false);
2496 bool checkCommonAttributeFeatures(QualType T, const ParsedAttr &A,
2497 bool SkipArgCountCheck = false);
2498
2499 ///@}
2500
2501 //
2502 //
2503 // -------------------------------------------------------------------------
2504 //
2505 //
2506
2507 /// \name Availability Attribute Handling
2508 /// Implementations are in SemaAvailability.cpp
2509 ///@{
2510
2511public:
2512 /// Issue any -Wunguarded-availability warnings in \c FD
2513 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2514
2515 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2516
2517 /// Retrieve the current function, if any, that should be analyzed for
2518 /// potential availability violations.
2519 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2520
2521 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2522 const ObjCInterfaceDecl *UnknownObjCClass,
2523 bool ObjCPropertyAccess,
2524 bool AvoidPartialAvailabilityChecks,
2525 ObjCInterfaceDecl *ClassReceiver);
2526
2527 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2528
2529 std::pair<AvailabilityResult, const NamedDecl *>
2530 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2531 ObjCInterfaceDecl *ClassReceiver);
2532 ///@}
2533
2534 //
2535 //
2536 // -------------------------------------------------------------------------
2537 //
2538 //
2539
2540 /// \name Bounds Safety
2541 /// Implementations are in SemaBoundsSafety.cpp
2542 ///@{
2543public:
2544 struct BoundsAttrFlags {
2545 bool CountInBytes = false;
2546 bool OrNull = false;
2547 bool IsEndedBy = false;
2548
2549 /// Return the flags for a bounds attribute of kind \p K.
2550 static BoundsAttrFlags get(AttributeCommonInfo::Kind K);
2551 };
2552 static BoundsAttributedType::BoundsAttrKind
2553 getBoundsAttrKind(const BoundsAttrFlags &);
2554
2555 /// Check the type shape for counted_by, sized_by and their _or_null variants.
2556 /// The caller checks declaration context, count expressions, flexible array
2557 /// member eligibility and nesting.
2558 ///
2559 /// \p Flags selects the attribute variant. For void pointers, counted_by is
2560 /// treated as a byte count outside the -fbounds-safety attribute model. Set
2561 /// \c Flags.CountInBytes in this case if \p UpdateFlags is true.
2562 /// \p AttrSpelling, \p AllowRedecl and \p AttrArg are reserved for that model
2563 /// (see LangOptions::hasBoundsSafetyAttributes).
2564 ///
2565 /// \returns false after diagnosing an attribute that must be dropped. Returns
2566 /// true if the shape is valid, after the warning for an array of structs with
2567 /// flexible array members, and, under the -fbounds-safety attribute model,
2568 /// after an error on a pointer, with \c Flags.CountInBytes set so that type
2569 /// construction can recover.
2570 bool ValidateBoundsAttrTypeShape(QualType Ty, SourceLocation AttrLoc,
2571 SourceRange AttrRange,
2572 BoundsAttrFlags &Flags,
2573 StringRef AttrSpelling = {},
2574 bool AllowRedecl = false,
2575 Expr *AttrArg = nullptr,
2576 bool UpdateFlags = true);
2577
2578 /// Check a counted_by-family attribute in type position and initialize
2579 /// \p Flags from \p AttrKind. \p PointerNestLevel counts the pointer, array
2580 /// and function declarator chunks enclosing the attribute.
2581 ///
2582 /// \returns false after diagnosing an attribute that must be dropped (see
2583 /// ValidateBoundsAttrTypeShape).
2584 bool ValidateBoundsAttrTypeForTypePosition(
2585 QualType Ty, AttributeCommonInfo::Kind AttrKind, SourceLocation AttrLoc,
2586 SourceRange AttrRange, unsigned PointerNestLevel, BoundsAttrFlags &Flags);
2587
2588 /// Check if applying the specified attribute variant from the "counted by"
2589 /// family of attributes to FieldDecl \p FD is semantically valid. If
2590 /// semantically invalid diagnostics will be emitted explaining the problems.
2591 ///
2592 /// \param FD The FieldDecl to apply the attribute to
2593 /// \param E The count expression on the attribute
2594 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2595 /// attributes. If the false the attribute is from
2596 /// "counted_by" family of attributes.
2597 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2598 /// of attributes. If false the attribute does not have the
2599 /// suffix.
2600 ///
2601 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2602 /// \p CountInBytes and \p OrNull both being true indicates the
2603 /// `counted_by_or_null` attribute.
2604 ///
2605 /// \returns false iff semantically valid.
2606 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2607 bool OrNull);
2608
2609 /// Late-parsed bounds types dropped while their declarator was built. The
2610 /// attribute has already been diagnosed and its node is no longer part of
2611 /// any type, so the completion pass must skip it rather than parse its
2612 /// argument and complete it.
2613 llvm::SmallPtrSet<const BoundsAttributedType *, 1>
2614 RejectedLateParsedBoundsTypes;
2615
2616 void markLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy) {
2617 RejectedLateParsedBoundsTypes.insert(Ptr: BATy);
2618 }
2619
2620 bool isLateParsedBoundsTypeRejected(const BoundsAttributedType *BATy) const {
2621 return RejectedLateParsedBoundsTypes.contains(Ptr: BATy);
2622 }
2623
2624 /// Validate the late-parsed type attribute \p LA and wrap \p QT in a
2625 /// CountAttributedType with no count yet, recorded on \p LA for later
2626 /// completion. Returns false if \p LA is invalid.
2627 bool ProcessLateParsedTypeAttr(LateParsedTypeAttrInfo &LA, QualType &QT);
2628
2629 /// Supply the parsed argument of a late-parsed bounds attribute to the type
2630 /// built for it by ProcessLateParsedTypeAttr, and run the checks that need
2631 /// the owning declaration. \p FD is the field the type belongs to. Returns
2632 /// false if the attribute was rejected.
2633 bool ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy,
2634 FieldDecl *FD, Expr *Arg);
2635
2636 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2637 /// `__counted_by_or_null` pointer type \param LHSTy.
2638 ///
2639 /// \param LHSTy The type being assigned to. Checks will only be performed if
2640 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2641 /// \param RHSExpr The expression being assigned from.
2642 /// \param Action The type assignment being performed
2643 /// \param Loc The SourceLocation to use for error diagnostics
2644 /// \param Assignee The ValueDecl being assigned. This is used to compute
2645 /// the name of the assignee. If the assignee isn't known this can
2646 /// be set to nullptr.
2647 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2648 /// Assignee to compute the name of the assignee use the fully
2649 /// qualified name, otherwise use the unqualified name.
2650 ///
2651 /// \returns True iff no diagnostic where emitted, false otherwise.
2652 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2653 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2654 SourceLocation Loc, const ValueDecl *Assignee,
2655 bool ShowFullyQualifiedAssigneeName);
2656
2657 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2658 /// pointer.
2659 ///
2660 /// \param Entity The entity being initialized
2661 /// \param Kind The kind of initialization being performed
2662 /// \param Action The type assignment being performed
2663 /// \param LHSTy The type being assigned to. Checks will only be performed if
2664 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2665 /// \param RHSExpr The expression being used for initialization.
2666 ///
2667 /// \returns True iff no diagnostic where emitted, false otherwise.
2668 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2669 const InitializationKind &Kind,
2670 AssignmentAction Action,
2671 QualType LHSType, Expr *RHSExpr);
2672
2673 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2674 /// or counted_by_or_null pointers in \param E.
2675 ///
2676 /// \param E the expression to check
2677 ///
2678 /// \returns True iff no diagnostic where emitted, false otherwise.
2679 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2680 ///@}
2681
2682 //
2683 //
2684 // -------------------------------------------------------------------------
2685 //
2686 //
2687
2688 /// \name Casts
2689 /// Implementations are in SemaCast.cpp
2690 ///@{
2691
2692public:
2693 static bool isCast(CheckedConversionKind CCK) {
2694 return CCK == CheckedConversionKind::CStyleCast ||
2695 CCK == CheckedConversionKind::FunctionalCast ||
2696 CCK == CheckedConversionKind::OtherCast;
2697 }
2698
2699 /// ActOnCXXNamedCast - Parse
2700 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2701 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2702 SourceLocation LAngleBracketLoc, Declarator &D,
2703 SourceLocation RAngleBracketLoc,
2704 SourceLocation LParenLoc, Expr *E,
2705 SourceLocation RParenLoc);
2706
2707 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2708 TypeSourceInfo *Ty, Expr *E,
2709 SourceRange AngleBrackets, SourceRange Parens);
2710
2711 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2712 ExprResult Operand,
2713 SourceLocation RParenLoc);
2714
2715 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2716 Expr *Operand, SourceLocation RParenLoc);
2717
2718 // Checks that reinterpret casts don't have undefined behavior.
2719 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2720 bool IsDereference, SourceRange Range);
2721
2722 // Checks that the vector type should be initialized from a scalar
2723 // by splatting the value rather than populating a single element.
2724 // This is the case for AltiVecVector types as well as with
2725 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2726 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2727
2728 // Checks if the -faltivec-src-compat=gcc option is specified.
2729 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2730 // treated the same way as they are when trying to initialize
2731 // these vectors on gcc (an error is emitted).
2732 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2733 QualType SrcTy);
2734
2735 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2736 SourceLocation RParenLoc, Expr *Op);
2737
2738 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2739 SourceLocation LParenLoc,
2740 Expr *CastExpr,
2741 SourceLocation RParenLoc);
2742
2743 ///@}
2744
2745 //
2746 //
2747 // -------------------------------------------------------------------------
2748 //
2749 //
2750
2751 /// \name Extra Semantic Checking
2752 /// Implementations are in SemaChecking.cpp
2753 ///@{
2754
2755public:
2756 /// Used to change context to isConstantEvaluated without pushing a heavy
2757 /// ExpressionEvaluationContextRecord object.
2758 bool isConstantEvaluatedOverride = false;
2759
2760 bool isConstantEvaluatedContext() const {
2761 return currentEvaluationContext().isConstantEvaluated() ||
2762 isConstantEvaluatedOverride;
2763 }
2764
2765 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2766 unsigned ByteNo) const;
2767
2768 enum FormatArgumentPassingKind {
2769 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2770 FAPK_Variadic, // values to format are passed as variadic arguments
2771 FAPK_VAList, // values to format are passed in a va_list
2772 FAPK_Elsewhere, // values to format are not passed to this function
2773 };
2774
2775 // Used to grab the relevant information from a FormatAttr and a
2776 // FunctionDeclaration.
2777 struct FormatStringInfo {
2778 unsigned FormatIdx;
2779 unsigned FirstDataArg;
2780 FormatArgumentPassingKind ArgPassingKind;
2781 };
2782
2783 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2784 /// populate the FormatStringInfo parameter with the attribute's correct
2785 /// format_idx and firstDataArg. Returns true when the format fits the
2786 /// function and the FormatStringInfo has been populated.
2787 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2788 unsigned FirstArg, FormatStringInfo *FSI);
2789 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2790 bool HasImplicitThisParam, bool IsVariadic,
2791 FormatStringInfo *FSI);
2792
2793 // Used by C++ template instantiation.
2794 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2795
2796 /// ConvertVectorExpr - Handle __builtin_convertvector
2797 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2798 SourceLocation BuiltinLoc,
2799 SourceLocation RParenLoc);
2800
2801 static StringRef GetFormatStringTypeName(FormatStringType FST);
2802 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2803 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2804 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2805
2806 bool FormatStringHasSArg(const StringLiteral *FExpr);
2807
2808 /// Check for comparisons of floating-point values using == and !=. Issue a
2809 /// warning if the comparison is not likely to do what the programmer
2810 /// intended.
2811 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2812 const Expr *RHS, BinaryOperatorKind Opcode);
2813
2814 /// Register a magic integral constant to be used as a type tag.
2815 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2816 uint64_t MagicValue, QualType Type,
2817 bool LayoutCompatible, bool MustBeNull);
2818
2819 struct TypeTagData {
2820 TypeTagData() {}
2821
2822 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2823 : Type(Type), LayoutCompatible(LayoutCompatible),
2824 MustBeNull(MustBeNull) {}
2825
2826 QualType Type;
2827
2828 /// If true, \c Type should be compared with other expression's types for
2829 /// layout-compatibility.
2830 LLVM_PREFERRED_TYPE(bool)
2831 unsigned LayoutCompatible : 1;
2832 LLVM_PREFERRED_TYPE(bool)
2833 unsigned MustBeNull : 1;
2834 };
2835
2836 /// A pair of ArgumentKind identifier and magic value. This uniquely
2837 /// identifies the magic value.
2838 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2839
2840 /// Diagnoses the current set of gathered accesses. This happens at the end of
2841 /// each expression evaluation context. Diagnostics are emitted only for
2842 /// accesses gathered in the current evaluation context.
2843 void DiagnoseMisalignedMembers();
2844
2845 /// This function checks if the expression is in the sef of potentially
2846 /// misaligned members and it is converted to some pointer type T with lower
2847 /// or equal alignment requirements. If so it removes it. This is used when
2848 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2849 /// void*).
2850 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2851
2852 /// Returns true if `From` is a function or pointer to a function with the
2853 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2854 /// function without this attribute.
2855 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2856
2857 /// This function calls Action when it determines that E designates a
2858 /// misaligned member due to the packed attribute. This is used to emit
2859 /// local diagnostics like in reference binding.
2860 void RefersToMemberWithReducedAlignment(
2861 Expr *E,
2862 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2863 Action);
2864
2865 enum class AtomicArgumentOrder { API, AST };
2866 ExprResult
2867 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2868 SourceLocation RParenLoc, MultiExprArg Args,
2869 AtomicExpr::AtomicOp Op,
2870 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2871
2872 /// Check to see if a given expression could have '.c_str()' called on it.
2873 bool hasCStrMethod(const Expr *E);
2874
2875 /// Diagnose pointers that are always non-null.
2876 /// \param E the expression containing the pointer
2877 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2878 /// compared to a null pointer
2879 /// \param IsEqual True when the comparison is equal to a null pointer
2880 /// \param Range Extra SourceRange to highlight in the diagnostic
2881 void DiagnoseAlwaysNonNullPointer(Expr *E,
2882 Expr::NullPointerConstantKind NullType,
2883 bool IsEqual, SourceRange Range);
2884
2885 /// CheckParmsForFunctionDef - Check that the parameters of the given
2886 /// function are appropriate for the definition of a function. This
2887 /// takes care of any checks that cannot be performed on the
2888 /// declaration itself, e.g., that the types of each of the function
2889 /// parameters are complete.
2890 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2891 bool CheckParameterNames);
2892
2893 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2894 /// pointer cast increases the alignment requirements.
2895 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2896
2897 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2898 /// to weak/__unsafe_unretained type.
2899 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2900
2901 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2902 /// to weak/__unsafe_unretained expression.
2903 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2904
2905 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2906 /// statement as a \p Body, and it is located on the same line.
2907 ///
2908 /// This helps prevent bugs due to typos, such as:
2909 /// if (condition);
2910 /// do_stuff();
2911 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2912 unsigned DiagID);
2913
2914 /// Warn if a for/while loop statement \p S, which is followed by
2915 /// \p PossibleBody, has a suspicious null statement as a body.
2916 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2917
2918 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2919 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2920 SourceLocation OpLoc);
2921
2922 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2923 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2924 const TypeSourceInfo *Derived);
2925
2926 /// CheckFunctionCall - Check a direct function call for various correctness
2927 /// and safety properties not strictly enforced by the C type system.
2928 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2929 const FunctionProtoType *Proto);
2930
2931 enum class EltwiseBuiltinArgTyRestriction {
2932 None,
2933 FloatTy,
2934 IntegerTy,
2935 SignedIntOrFloatTy,
2936 };
2937
2938 /// \param FPOnly restricts the arguments to floating-point types.
2939 std::optional<QualType>
2940 BuiltinVectorMath(CallExpr *TheCall,
2941 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2942 EltwiseBuiltinArgTyRestriction::None);
2943 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2944
2945 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2946 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2947
2948 /// Handles the checks for format strings, non-POD arguments to vararg
2949 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2950 /// attributes and AArch64 SME attributes.
2951 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2952 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2953 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2954 VariadicCallType CallType);
2955
2956 /// Verify that two format strings (as understood by attribute(format) and
2957 /// attribute(format_matches) are compatible. If they are incompatible,
2958 /// diagnostics are emitted with the assumption that \c
2959 /// AuthoritativeFormatString is correct and
2960 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2961 /// diagnostics will point to it and a note will refer to \c
2962 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2963 bool
2964 CheckFormatStringsCompatible(FormatStringType FST,
2965 const StringLiteral *AuthoritativeFormatString,
2966 const StringLiteral *TestedFormatString,
2967 const Expr *FunctionCallArg = nullptr);
2968
2969 /// Verify that one format string (as understood by attribute(format)) is
2970 /// self-consistent; for instance, that it doesn't have multiple positional
2971 /// arguments referring to the same argument in incompatible ways. Diagnose
2972 /// if it isn't.
2973 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2974
2975 /// \brief Enforce the bounds of a TCB
2976 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2977 /// directly calls other functions in the same TCB as marked by the
2978 /// enforce_tcb and enforce_tcb_leaf attributes.
2979 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2980 const NamedDecl *Callee);
2981
2982 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2983
2984 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2985 /// TheCall is a constant expression.
2986 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2987 llvm::APSInt &Result);
2988
2989 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2990 /// TheCall is a constant expression in the range [Low, High].
2991 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2992 int High, bool RangeIsError = true);
2993
2994 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2995 /// TheCall is a constant expression is a multiple of Num..
2996 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2997 unsigned Multiple);
2998
2999 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
3000 /// constant expression representing a power of 2.
3001 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
3002
3003 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
3004 /// a constant expression representing an arbitrary byte value shifted left by
3005 /// a multiple of 8 bits.
3006 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
3007 unsigned ArgBits);
3008
3009 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
3010 /// TheCall is a constant expression representing either a shifted byte value,
3011 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
3012 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
3013 /// Arm MVE intrinsics.
3014 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
3015 unsigned ArgBits);
3016
3017 /// Checks that a call expression's argument count is at least the desired
3018 /// number. This is useful when doing custom type-checking on a variadic
3019 /// function. Returns true on error.
3020 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
3021
3022 /// Checks that a call expression's argument count is at most the desired
3023 /// number. This is useful when doing custom type-checking on a variadic
3024 /// function. Returns true on error.
3025 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
3026
3027 /// Checks that a call expression's argument count is in the desired range.
3028 /// This is useful when doing custom type-checking on a variadic function.
3029 /// Returns true on error.
3030 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
3031 unsigned MaxArgCount);
3032
3033 /// Checks that a call expression's argument count is the desired number.
3034 /// This is useful when doing custom type-checking. Returns true on error.
3035 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
3036
3037 bool convertArgumentToType(Expr *&Value, QualType Ty);
3038
3039 /// Returns true if the argument consists of one contiguous run of 1s with any
3040 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
3041 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3042 /// since all 1s are not contiguous.
3043 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
3044
3045 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
3046 bool *ICContext = nullptr,
3047 bool IsListInit = false);
3048
3049 /// Check for overflow behavior type related implicit conversion diagnostics.
3050 /// Returns true if OBT-related diagnostic was issued, false otherwise.
3051 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
3052 SourceLocation CC);
3053
3054 bool
3055 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
3056 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3057 EltwiseBuiltinArgTyRestriction::FloatTy);
3058 bool PrepareBuiltinElementwiseMathOneArgCall(
3059 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
3060 EltwiseBuiltinArgTyRestriction::None);
3061
3062private:
3063 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3064 const ArraySubscriptExpr *ASE = nullptr,
3065 bool AllowOnePastEnd = true, bool IndexNegated = false);
3066 void CheckArrayAccess(const Expr *E);
3067
3068 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3069 const FunctionProtoType *Proto);
3070
3071 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3072 /// such as function pointers returned from functions.
3073 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
3074
3075 /// CheckConstructorCall - Check a constructor call for correctness and safety
3076 /// properties not enforced by the C type system.
3077 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
3078 ArrayRef<const Expr *> Args,
3079 const FunctionProtoType *Proto, SourceLocation Loc);
3080
3081 /// Warn if a pointer or reference argument passed to a function points to an
3082 /// object that is less aligned than the parameter. This can happen when
3083 /// creating a typedef with a lower alignment than the original type and then
3084 /// calling functions defined in terms of the original type.
3085 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3086 StringRef ParamName, QualType ArgTy, QualType ParamTy);
3087
3088 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
3089
3090 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3091 CallExpr *TheCall);
3092
3093 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3094 CallExpr *TheCall);
3095
3096 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
3097
3098 /// Argument-value fortify checks for libc functions that are not builtins,
3099 /// dispatched by name (e.g. umask). Diagnostics belong to -Wfortify-source.
3100 void checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall);
3101
3102 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
3103 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
3104 /// on failure; return false on success.
3105 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
3106 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
3107
3108 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3109 /// friends. This is declared to take (...), so we have to check everything.
3110 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
3111
3112 /// BuiltinSemaBuiltinFPClassification - Handle functions like
3113 /// __builtin_isnan and friends. This is declared to take (...), so we have
3114 /// to check everything.
3115 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
3116 unsigned BuiltinID);
3117
3118 /// Perform semantic analysis for a call to __builtin_complex.
3119 bool BuiltinComplex(CallExpr *TheCall);
3120 bool BuiltinOSLogFormat(CallExpr *TheCall);
3121
3122 /// BuiltinPrefetch - Handle __builtin_prefetch.
3123 /// This is declared to take (const void*, ...) and can take two
3124 /// optional constant int args.
3125 bool BuiltinPrefetch(CallExpr *TheCall);
3126
3127 /// Handle __builtin_alloca_with_align. This is declared
3128 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3129 /// than 8.
3130 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3131
3132 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3133 bool BuiltinArithmeticFence(CallExpr *TheCall);
3134
3135 /// BuiltinAssume - Handle __assume (MS Extension).
3136 /// __assume does not evaluate its arguments, and should warn if its argument
3137 /// has side effects.
3138 bool BuiltinAssume(CallExpr *TheCall);
3139
3140 /// Handle __builtin_assume_aligned. This is declared
3141 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3142 bool BuiltinAssumeAligned(CallExpr *TheCall);
3143
3144 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3145 /// This checks that the target supports __builtin_longjmp and
3146 /// that val is a constant 1.
3147 bool BuiltinLongjmp(CallExpr *TheCall);
3148
3149 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3150 /// This checks that the target supports __builtin_setjmp.
3151 bool BuiltinSetjmp(CallExpr *TheCall);
3152
3153 /// We have a call to a function like __sync_fetch_and_add, which is an
3154 /// overloaded function based on the pointer type of its first argument.
3155 /// The main BuildCallExpr routines have already promoted the types of
3156 /// arguments because all of these calls are prototyped as void(...).
3157 ///
3158 /// This function goes through and does final semantic checking for these
3159 /// builtins, as well as generating any warnings.
3160 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3161
3162 /// BuiltinNontemporalOverloaded - We have a call to
3163 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3164 /// overloaded function based on the pointer type of its last argument.
3165 ///
3166 /// This function goes through and does final semantic checking for these
3167 /// builtins.
3168 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3169 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3170 AtomicExpr::AtomicOp Op);
3171
3172 /// \param FPOnly restricts the arguments to floating-point types.
3173 bool BuiltinElementwiseMath(CallExpr *TheCall,
3174 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3175 EltwiseBuiltinArgTyRestriction::None);
3176 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3177
3178 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3179
3180 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3181 BuiltinCountedByRefKind K);
3182 bool BuiltinCountedByRef(CallExpr *TheCall);
3183
3184 // Matrix builtin handling.
3185 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3186 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3187 ExprResult CallResult);
3188 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3189 ExprResult CallResult);
3190
3191 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3192 /// functions) for correct use of format strings.
3193 /// Returns true if a format string has been fully checked.
3194 bool CheckFormatArguments(const FormatAttr *Format,
3195 ArrayRef<const Expr *> Args, bool IsCXXMember,
3196 VariadicCallType CallType, SourceLocation Loc,
3197 SourceRange Range,
3198 llvm::SmallBitVector &CheckedVarArgs);
3199 bool CheckFormatString(const FormatMatchesAttr *Format,
3200 ArrayRef<const Expr *> Args, bool IsCXXMember,
3201 VariadicCallType CallType, SourceLocation Loc,
3202 SourceRange Range,
3203 llvm::SmallBitVector &CheckedVarArgs);
3204 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3205 FormatArgumentPassingKind FAPK,
3206 StringLiteral *ReferenceFormatString,
3207 unsigned format_idx, unsigned firstDataArg,
3208 FormatStringType Type, VariadicCallType CallType,
3209 SourceLocation Loc, SourceRange range,
3210 llvm::SmallBitVector &CheckedVarArgs);
3211
3212 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3213
3214 /// Warn when using the wrong abs() function.
3215 void CheckAbsoluteValueFunction(const CallExpr *Call,
3216 const FunctionDecl *FDecl);
3217
3218 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3219
3220 /// Check for dangerous or invalid arguments to memset().
3221 ///
3222 /// This issues warnings on known problematic, dangerous or unspecified
3223 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3224 /// function calls.
3225 ///
3226 /// \param Call The call expression to diagnose.
3227 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3228 IdentifierInfo *FnName);
3229
3230 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3231 IdentifierInfo *FnName);
3232 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3233 // be the size of the source, instead of the destination.
3234 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3235
3236 // Warn on anti-patterns as the 'size' argument to strncat.
3237 // The correct size argument should look like following:
3238 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3239 void CheckStrncatArguments(const CallExpr *Call,
3240 const IdentifierInfo *FnName);
3241
3242 /// Alerts the user that they are attempting to free a non-malloc'd object.
3243 void CheckFreeArguments(const CallExpr *E);
3244
3245 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3246 SourceLocation ReturnLoc, bool isObjCMethod = false,
3247 const AttrVec *Attrs = nullptr,
3248 const FunctionDecl *FD = nullptr);
3249
3250 /// Diagnoses "dangerous" implicit conversions within the given
3251 /// expression (which is a full expression). Implements -Wconversion
3252 /// and -Wsign-compare.
3253 ///
3254 /// \param CC the "context" location of the implicit conversion, i.e.
3255 /// the most location of the syntactic entity requiring the implicit
3256 /// conversion
3257 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3258
3259 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3260 /// Input argument E is a logical expression.
3261 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3262
3263 /// Diagnose when expression is an integer constant expression and its
3264 /// evaluation results in integer overflow
3265 void CheckForIntOverflow(const Expr *E);
3266 void CheckUnsequencedOperations(const Expr *E);
3267
3268 /// Perform semantic checks on a completed expression. This will either
3269 /// be a full-expression or a default argument expression.
3270 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3271 bool IsConstexpr = false);
3272
3273 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3274 Expr *Init);
3275
3276 /// A map from magic value to type information.
3277 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3278 TypeTagForDatatypeMagicValues;
3279
3280 /// Peform checks on a call of a function with argument_with_type_tag
3281 /// or pointer_with_type_tag attributes.
3282 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3283 const ArrayRef<const Expr *> ExprArgs,
3284 SourceLocation CallSiteLoc);
3285
3286 /// Check if we are taking the address of a packed field
3287 /// as this may be a problem if the pointer value is dereferenced.
3288 void CheckAddressOfPackedMember(Expr *rhs);
3289
3290 /// Helper class that collects misaligned member designations and
3291 /// their location info for delayed diagnostics.
3292 struct MisalignedMember {
3293 Expr *E;
3294 RecordDecl *RD;
3295 ValueDecl *MD;
3296 CharUnits Alignment;
3297
3298 MisalignedMember() : E(), RD(), MD() {}
3299 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3300 CharUnits Alignment)
3301 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3302 explicit MisalignedMember(Expr *E)
3303 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3304
3305 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3306 };
3307
3308 /// Adds an expression to the set of gathered misaligned members.
3309 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3310 CharUnits Alignment);
3311 ///@}
3312
3313 //
3314 //
3315 // -------------------------------------------------------------------------
3316 //
3317 //
3318
3319 /// \name C++ Coroutines
3320 /// Implementations are in SemaCoroutine.cpp
3321 ///@{
3322
3323public:
3324 /// The C++ "std::coroutine_traits" template, which is defined in
3325 /// \<coroutine_traits>
3326 ClassTemplateDecl *StdCoroutineTraitsCache;
3327
3328 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3329 StringRef Keyword);
3330 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3331 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3332 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3333
3334 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3335 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3336 UnresolvedLookupExpr *Lookup);
3337 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3338 Expr *Awaiter, bool IsImplicit = false);
3339 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3340 UnresolvedLookupExpr *Lookup);
3341 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3342 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3343 bool IsImplicit = false);
3344 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3345 bool buildCoroutineParameterMoves(SourceLocation Loc);
3346 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3347 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3348
3349 // As a clang extension, enforces that a non-coroutine function must be marked
3350 // with [[clang::coro_wrapper]] if it returns a type marked with
3351 // [[clang::coro_return_type]].
3352 // Expects that FD is not a coroutine.
3353 void CheckCoroutineWrapper(FunctionDecl *FD);
3354 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3355 /// namespace. The namespace found is recorded in Namespace.
3356 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3357 SourceLocation FuncLoc);
3358 /// Check that the expression co_await promise.final_suspend() shall not be
3359 /// potentially-throwing.
3360 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3361
3362 ///@}
3363
3364 //
3365 //
3366 // -------------------------------------------------------------------------
3367 //
3368 //
3369
3370 /// \name C++ Scope Specifiers
3371 /// Implementations are in SemaCXXScopeSpec.cpp
3372 ///@{
3373
3374public:
3375 // Marks SS invalid if it represents an incomplete type.
3376 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3377 // Complete an enum decl, maybe without a scope spec.
3378 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3379 CXXScopeSpec *SS = nullptr);
3380
3381 /// Compute the DeclContext that is associated with the given type.
3382 ///
3383 /// \param T the type for which we are attempting to find a DeclContext.
3384 ///
3385 /// \returns the declaration context represented by the type T,
3386 /// or NULL if the declaration context cannot be computed (e.g., because it is
3387 /// dependent and not the current instantiation).
3388 DeclContext *computeDeclContext(QualType T);
3389
3390 /// Compute the DeclContext that is associated with the given
3391 /// scope specifier.
3392 ///
3393 /// \param SS the C++ scope specifier as it appears in the source
3394 ///
3395 /// \param EnteringContext when true, we will be entering the context of
3396 /// this scope specifier, so we can retrieve the declaration context of a
3397 /// class template or class template partial specialization even if it is
3398 /// not the current instantiation.
3399 ///
3400 /// \returns the declaration context represented by the scope specifier @p SS,
3401 /// or NULL if the declaration context cannot be computed (e.g., because it is
3402 /// dependent and not the current instantiation).
3403 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3404 bool EnteringContext = false);
3405 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3406
3407 /// If the given nested name specifier refers to the current
3408 /// instantiation, return the declaration that corresponds to that
3409 /// current instantiation (C++0x [temp.dep.type]p1).
3410 ///
3411 /// \param NNS a dependent nested name specifier.
3412 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3413
3414 /// The parser has parsed a global nested-name-specifier '::'.
3415 ///
3416 /// \param CCLoc The location of the '::'.
3417 ///
3418 /// \param SS The nested-name-specifier, which will be updated in-place
3419 /// to reflect the parsed nested-name-specifier.
3420 ///
3421 /// \returns true if an error occurred, false otherwise.
3422 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3423
3424 /// The parser has parsed a '__super' nested-name-specifier.
3425 ///
3426 /// \param SuperLoc The location of the '__super' keyword.
3427 ///
3428 /// \param ColonColonLoc The location of the '::'.
3429 ///
3430 /// \param SS The nested-name-specifier, which will be updated in-place
3431 /// to reflect the parsed nested-name-specifier.
3432 ///
3433 /// \returns true if an error occurred, false otherwise.
3434 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3435 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3436
3437 /// Determines whether the given declaration is an valid acceptable
3438 /// result for name lookup of a nested-name-specifier.
3439 /// \param SD Declaration checked for nested-name-specifier.
3440 /// \param IsExtension If not null and the declaration is accepted as an
3441 /// extension, the pointed variable is assigned true.
3442 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3443 bool *CanCorrect = nullptr);
3444
3445 /// If the given nested-name-specifier begins with a bare identifier
3446 /// (e.g., Base::), perform name lookup for that identifier as a
3447 /// nested-name-specifier within the given scope, and return the result of
3448 /// that name lookup.
3449 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3450
3451 /// Keeps information about an identifier in a nested-name-spec.
3452 ///
3453 struct NestedNameSpecInfo {
3454 /// The type of the object, if we're parsing nested-name-specifier in
3455 /// a member access expression.
3456 ParsedType ObjectType;
3457
3458 /// The identifier preceding the '::'.
3459 IdentifierInfo *Identifier;
3460
3461 /// The location of the identifier.
3462 SourceLocation IdentifierLoc;
3463
3464 /// The location of the '::'.
3465 SourceLocation CCLoc;
3466
3467 /// Creates info object for the most typical case.
3468 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3469 SourceLocation ColonColonLoc,
3470 ParsedType ObjectType = ParsedType())
3471 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3472 CCLoc(ColonColonLoc) {}
3473
3474 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3475 SourceLocation ColonColonLoc, QualType ObjectType)
3476 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3477 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3478 };
3479
3480 /// Build a new nested-name-specifier for "identifier::", as described
3481 /// by ActOnCXXNestedNameSpecifier.
3482 ///
3483 /// \param S Scope in which the nested-name-specifier occurs.
3484 /// \param IdInfo Parser information about an identifier in the
3485 /// nested-name-spec.
3486 /// \param EnteringContext If true, enter the context specified by the
3487 /// nested-name-specifier.
3488 /// \param SS Optional nested name specifier preceding the identifier.
3489 /// \param ScopeLookupResult Provides the result of name lookup within the
3490 /// scope of the nested-name-specifier that was computed at template
3491 /// definition time.
3492 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3493 /// error recovery and what kind of recovery is performed.
3494 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3495 /// are allowed. The bool value pointed by this parameter is set to
3496 /// 'true' if the identifier is treated as if it was followed by ':',
3497 /// not '::'.
3498 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3499 ///
3500 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3501 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3502 /// the result of name lookup within the scope of the nested-name-specifier
3503 /// that was computed at template definition time.
3504 ///
3505 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3506 /// recovery. This means that it should not emit diagnostics, it should
3507 /// just return true on failure. It also means it should only return a valid
3508 /// scope if it *knows* that the result is correct. It should not return in a
3509 /// dependent context, for example. Nor will it extend \p SS with the scope
3510 /// specifier.
3511 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3512 bool EnteringContext, CXXScopeSpec &SS,
3513 NamedDecl *ScopeLookupResult,
3514 bool ErrorRecoveryLookup,
3515 bool *IsCorrectedToColon = nullptr,
3516 bool OnlyNamespace = false);
3517
3518 /// The parser has parsed a nested-name-specifier 'identifier::'.
3519 ///
3520 /// \param S The scope in which this nested-name-specifier occurs.
3521 ///
3522 /// \param IdInfo Parser information about an identifier in the
3523 /// nested-name-spec.
3524 ///
3525 /// \param EnteringContext Whether we're entering the context nominated by
3526 /// this nested-name-specifier.
3527 ///
3528 /// \param SS The nested-name-specifier, which is both an input
3529 /// parameter (the nested-name-specifier before this type) and an
3530 /// output parameter (containing the full nested-name-specifier,
3531 /// including this new type).
3532 ///
3533 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3534 /// are allowed. The bool value pointed by this parameter is set to 'true'
3535 /// if the identifier is treated as if it was followed by ':', not '::'.
3536 ///
3537 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3538 ///
3539 /// \returns true if an error occurred, false otherwise.
3540 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3541 bool EnteringContext, CXXScopeSpec &SS,
3542 bool *IsCorrectedToColon = nullptr,
3543 bool OnlyNamespace = false);
3544
3545 /// The parser has parsed a nested-name-specifier
3546 /// 'template[opt] template-name < template-args >::'.
3547 ///
3548 /// \param S The scope in which this nested-name-specifier occurs.
3549 ///
3550 /// \param SS The nested-name-specifier, which is both an input
3551 /// parameter (the nested-name-specifier before this type) and an
3552 /// output parameter (containing the full nested-name-specifier,
3553 /// including this new type).
3554 ///
3555 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3556 /// \param TemplateName the template name.
3557 /// \param TemplateNameLoc The location of the template name.
3558 /// \param LAngleLoc The location of the opening angle bracket ('<').
3559 /// \param TemplateArgs The template arguments.
3560 /// \param RAngleLoc The location of the closing angle bracket ('>').
3561 /// \param CCLoc The location of the '::'.
3562 ///
3563 /// \param EnteringContext Whether we're entering the context of the
3564 /// nested-name-specifier.
3565 ///
3566 ///
3567 /// \returns true if an error occurred, false otherwise.
3568 bool ActOnCXXNestedNameSpecifier(
3569 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3570 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3571 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3572 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3573
3574 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3575 SourceLocation ColonColonLoc);
3576
3577 ParsedType ActOnCXXNestedNameSpecifierIndexedPack(
3578 CXXScopeSpec &SS, const DeclSpec &DS, TypeSourceInfo *PatternLoc,
3579 SourceLocation ColonColonLoc, QualType Type);
3580
3581 /// IsInvalidUnlessNestedName - This method is used for error recovery
3582 /// purposes to determine whether the specified identifier is only valid as
3583 /// a nested name specifier, for example a namespace name. It is
3584 /// conservatively correct to always return false from this method.
3585 ///
3586 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3587 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3588 NestedNameSpecInfo &IdInfo,
3589 bool EnteringContext);
3590
3591 /// Given a C++ nested-name-specifier, produce an annotation value
3592 /// that the parser can use later to reconstruct the given
3593 /// nested-name-specifier.
3594 ///
3595 /// \param SS A nested-name-specifier.
3596 ///
3597 /// \returns A pointer containing all of the information in the
3598 /// nested-name-specifier \p SS.
3599 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3600
3601 /// Given an annotation pointer for a nested-name-specifier, restore
3602 /// the nested-name-specifier structure.
3603 ///
3604 /// \param Annotation The annotation pointer, produced by
3605 /// \c SaveNestedNameSpecifierAnnotation().
3606 ///
3607 /// \param AnnotationRange The source range corresponding to the annotation.
3608 ///
3609 /// \param SS The nested-name-specifier that will be updated with the contents
3610 /// of the annotation pointer.
3611 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3612 SourceRange AnnotationRange,
3613 CXXScopeSpec &SS);
3614
3615 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3616
3617 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3618 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3619 /// After this method is called, according to [C++ 3.4.3p3], names should be
3620 /// looked up in the declarator-id's scope, until the declarator is parsed and
3621 /// ActOnCXXExitDeclaratorScope is called.
3622 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3623 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3624
3625 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3626 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3627 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3628 /// Used to indicate that names should revert to being looked up in the
3629 /// defining scope.
3630 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3631
3632 ///@}
3633
3634 //
3635 //
3636 // -------------------------------------------------------------------------
3637 //
3638 //
3639
3640 /// \name Declarations
3641 /// Implementations are in SemaDecl.cpp
3642 ///@{
3643
3644public:
3645 IdentifierResolver IdResolver;
3646
3647 /// The index of the first InventedParameterInfo that refers to the current
3648 /// context.
3649 unsigned InventedParameterInfosStart = 0;
3650
3651 /// A RAII object to temporarily push a declaration context.
3652 class ContextRAII {
3653 private:
3654 Sema &S;
3655 DeclContext *SavedContext;
3656 ProcessingContextState SavedContextState;
3657 QualType SavedCXXThisTypeOverride;
3658 unsigned SavedFunctionScopesStart;
3659 unsigned SavedInventedParameterInfosStart;
3660
3661 public:
3662 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3663 : S(S), SavedContext(S.CurContext),
3664 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3665 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3666 SavedFunctionScopesStart(S.FunctionScopesStart),
3667 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3668 assert(ContextToPush && "pushing null context");
3669 S.CurContext = ContextToPush;
3670 if (NewThisContext)
3671 S.CXXThisTypeOverride = QualType();
3672 // Any saved FunctionScopes do not refer to this context.
3673 S.FunctionScopesStart = S.FunctionScopes.size();
3674 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3675 }
3676
3677 void pop() {
3678 if (!SavedContext)
3679 return;
3680 S.CurContext = SavedContext;
3681 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3682 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3683 S.FunctionScopesStart = SavedFunctionScopesStart;
3684 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3685 SavedContext = nullptr;
3686 }
3687
3688 ~ContextRAII() { pop(); }
3689 ContextRAII(const ContextRAII &) = delete;
3690 ContextRAII &operator=(const ContextRAII &) = delete;
3691 };
3692
3693 void DiagnoseInvalidJumps(Stmt *Body);
3694
3695 /// The function definitions which were renamed as part of typo-correction
3696 /// to match their respective declarations. We want to keep track of them
3697 /// to ensure that we don't emit a "redefinition" error if we encounter a
3698 /// correctly named definition after the renamed definition.
3699 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3700
3701 /// A cache of the flags available in enumerations with the flag_enum
3702 /// attribute.
3703 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3704
3705 /// A cache of enumerator values for enums checked by -Wassign-enum.
3706 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3707 AssignEnumCache;
3708
3709 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3710 /// declared. Rare. May alias another identifier, declared or undeclared.
3711 ///
3712 /// For aliases, the target identifier is used as a key for eventual
3713 /// processing when the target is declared. For the single-identifier form,
3714 /// the sole identifier is used as the key. Each entry is a `SetVector`
3715 /// (ordered by parse order) of aliases (identified by the alias name) in case
3716 /// of multiple aliases to the same undeclared identifier.
3717 llvm::MapVector<
3718 IdentifierInfo *,
3719 llvm::SetVector<
3720 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3721 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3722 WeakUndeclaredIdentifiers;
3723
3724 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3725 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3726 /// to define functions that occur in multiple standards to call the version
3727 /// in the currently selected standard.
3728 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3729 ExtnameUndeclaredIdentifiers;
3730
3731 /// Set containing all typedefs that are likely unused.
3732 llvm::SmallPtrSet<const TypedefNameDecl *, 4>
3733 UnusedLocalTypedefNameCandidates;
3734
3735 /// Store UnusedLocalTypedefNameCandidates in \p Sorted in a deterministic
3736 /// order.
3737 void getSortedUnusedLocalTypedefNameCandidates(
3738 SmallVectorImpl<const TypedefNameDecl *> &Sorted) const;
3739
3740 typedef LazyVector<const DeclaratorDecl *,
3741 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3742 UnusedFileScopedDeclsType;
3743
3744 /// The set of file scoped decls seen so far that have not been used
3745 /// and must warn if not used. Only contains the first declaration.
3746 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3747
3748 typedef LazyVector<VarDecl *, &ExternalSemaSource::ReadTentativeDefinitions,
3749 2, 2>
3750 TentativeDefinitionsType;
3751
3752 /// All the tentative definitions encountered in the TU.
3753 TentativeDefinitionsType TentativeDefinitions;
3754
3755 /// All the external declarations encoutered and used in the TU.
3756 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3757
3758 /// Generally null except when we temporarily switch decl contexts,
3759 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3760 DeclContext *OriginalLexicalContext;
3761
3762 /// Is the module scope we are in a C++ Header Unit?
3763 bool currentModuleIsHeaderUnit() const {
3764 return ModuleScopes.empty() ? false
3765 : ModuleScopes.back().Module->isHeaderUnit();
3766 }
3767
3768 /// Get the module owning an entity.
3769 Module *getOwningModule(const Decl *Entity) {
3770 return Entity->getOwningModule();
3771 }
3772
3773 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3774
3775 enum class DiagCtorKind { None, Implicit, Typename };
3776 /// Returns the TypeDeclType for the given type declaration,
3777 /// as ASTContext::getTypeDeclType would, but
3778 /// performs the required semantic checks for name lookup of said entity.
3779 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3780 SourceLocation NameLoc);
3781
3782 /// If the identifier refers to a type name within this scope,
3783 /// return the declaration of that type.
3784 ///
3785 /// This routine performs ordinary name lookup of the identifier II
3786 /// within the given scope, with optional C++ scope specifier SS, to
3787 /// determine whether the name refers to a type. If so, returns an
3788 /// opaque pointer (actually a QualType) corresponding to that
3789 /// type. Otherwise, returns NULL.
3790 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3791 Scope *S, CXXScopeSpec *SS = nullptr,
3792 bool isClassName = false, bool HasTrailingDot = false,
3793 ParsedType ObjectType = nullptr,
3794 bool IsCtorOrDtorName = false,
3795 bool WantNontrivialTypeSourceInfo = false,
3796 bool IsClassTemplateDeductionContext = true,
3797 ImplicitTypenameContext AllowImplicitTypename =
3798 ImplicitTypenameContext::No,
3799 IdentifierInfo **CorrectedII = nullptr);
3800
3801 /// isTagName() - This method is called *for error recovery purposes only*
3802 /// to determine if the specified name is a valid tag name ("struct foo"). If
3803 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3804 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3805 /// diagnose cases in C where the user forgot to specify the tag.
3806 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3807
3808 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3809 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3810 /// then downgrade the missing typename error to a warning.
3811 /// This is needed for MSVC compatibility; Example:
3812 /// @code
3813 /// template<class T> class A {
3814 /// public:
3815 /// typedef int TYPE;
3816 /// };
3817 /// template<class T> class B : public A<T> {
3818 /// public:
3819 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3820 /// };
3821 /// @endcode
3822 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3823 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3824 Scope *S, CXXScopeSpec *SS,
3825 ParsedType &SuggestedType,
3826 bool IsTemplateName = false);
3827
3828 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3829 /// type name has failed in a dependent context. In these situations, we
3830 /// automatically form a DependentTypeName that will retry lookup in a related
3831 /// scope during instantiation.
3832 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3833 SourceLocation NameLoc,
3834 bool IsTemplateTypeArg);
3835
3836 class NameClassification {
3837 NameClassificationKind Kind;
3838 union {
3839 ExprResult Expr;
3840 NamedDecl *NonTypeDecl;
3841 TemplateName Template;
3842 ParsedType Type;
3843 };
3844
3845 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3846
3847 public:
3848 NameClassification(ParsedType Type)
3849 : Kind(NameClassificationKind::Type), Type(Type) {}
3850
3851 NameClassification(const IdentifierInfo *Keyword)
3852 : Kind(NameClassificationKind::Keyword) {}
3853
3854 static NameClassification Error() {
3855 return NameClassification(NameClassificationKind::Error);
3856 }
3857
3858 static NameClassification Unknown() {
3859 return NameClassification(NameClassificationKind::Unknown);
3860 }
3861
3862 static NameClassification OverloadSet(ExprResult E) {
3863 NameClassification Result(NameClassificationKind::OverloadSet);
3864 Result.Expr = E;
3865 return Result;
3866 }
3867
3868 static NameClassification NonType(NamedDecl *D) {
3869 NameClassification Result(NameClassificationKind::NonType);
3870 Result.NonTypeDecl = D;
3871 return Result;
3872 }
3873
3874 static NameClassification UndeclaredNonType() {
3875 return NameClassification(NameClassificationKind::UndeclaredNonType);
3876 }
3877
3878 static NameClassification DependentNonType() {
3879 return NameClassification(NameClassificationKind::DependentNonType);
3880 }
3881
3882 static NameClassification TypeTemplate(TemplateName Name) {
3883 NameClassification Result(NameClassificationKind::TypeTemplate);
3884 Result.Template = Name;
3885 return Result;
3886 }
3887
3888 static NameClassification VarTemplate(TemplateName Name) {
3889 NameClassification Result(NameClassificationKind::VarTemplate);
3890 Result.Template = Name;
3891 return Result;
3892 }
3893
3894 static NameClassification FunctionTemplate(TemplateName Name) {
3895 NameClassification Result(NameClassificationKind::FunctionTemplate);
3896 Result.Template = Name;
3897 return Result;
3898 }
3899
3900 static NameClassification Concept(TemplateName Name) {
3901 NameClassification Result(NameClassificationKind::Concept);
3902 Result.Template = Name;
3903 return Result;
3904 }
3905
3906 static NameClassification UndeclaredTemplate(TemplateName Name) {
3907 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3908 Result.Template = Name;
3909 return Result;
3910 }
3911
3912 NameClassificationKind getKind() const { return Kind; }
3913
3914 ExprResult getExpression() const {
3915 assert(Kind == NameClassificationKind::OverloadSet);
3916 return Expr;
3917 }
3918
3919 ParsedType getType() const {
3920 assert(Kind == NameClassificationKind::Type);
3921 return Type;
3922 }
3923
3924 NamedDecl *getNonTypeDecl() const {
3925 assert(Kind == NameClassificationKind::NonType);
3926 return NonTypeDecl;
3927 }
3928
3929 TemplateName getTemplateName() const {
3930 assert(Kind == NameClassificationKind::TypeTemplate ||
3931 Kind == NameClassificationKind::FunctionTemplate ||
3932 Kind == NameClassificationKind::VarTemplate ||
3933 Kind == NameClassificationKind::Concept ||
3934 Kind == NameClassificationKind::UndeclaredTemplate);
3935 return Template;
3936 }
3937
3938 TemplateNameKind getTemplateNameKind() const {
3939 switch (Kind) {
3940 case NameClassificationKind::TypeTemplate:
3941 return TNK_Type_template;
3942 case NameClassificationKind::FunctionTemplate:
3943 return TNK_Function_template;
3944 case NameClassificationKind::VarTemplate:
3945 return TNK_Var_template;
3946 case NameClassificationKind::Concept:
3947 return TNK_Concept_template;
3948 case NameClassificationKind::UndeclaredTemplate:
3949 return TNK_Undeclared_template;
3950 default:
3951 llvm_unreachable("unsupported name classification.");
3952 }
3953 }
3954 };
3955
3956 /// Perform name lookup on the given name, classifying it based on
3957 /// the results of name lookup and the following token.
3958 ///
3959 /// This routine is used by the parser to resolve identifiers and help direct
3960 /// parsing. When the identifier cannot be found, this routine will attempt
3961 /// to correct the typo and classify based on the resulting name.
3962 ///
3963 /// \param S The scope in which we're performing name lookup.
3964 ///
3965 /// \param SS The nested-name-specifier that precedes the name.
3966 ///
3967 /// \param Name The identifier. If typo correction finds an alternative name,
3968 /// this pointer parameter will be updated accordingly.
3969 ///
3970 /// \param NameLoc The location of the identifier.
3971 ///
3972 /// \param NextToken The token following the identifier. Used to help
3973 /// disambiguate the name.
3974 ///
3975 /// \param CCC The correction callback, if typo correction is desired.
3976 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3977 IdentifierInfo *&Name, SourceLocation NameLoc,
3978 const Token &NextToken,
3979 CorrectionCandidateCallback *CCC = nullptr);
3980
3981 /// Act on the result of classifying a name as an undeclared (ADL-only)
3982 /// non-type declaration.
3983 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3984 SourceLocation NameLoc);
3985 /// Act on the result of classifying a name as an undeclared member of a
3986 /// dependent base class.
3987 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3988 IdentifierInfo *Name,
3989 SourceLocation NameLoc,
3990 bool IsAddressOfOperand);
3991 /// Act on the result of classifying a name as a specific non-type
3992 /// declaration.
3993 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3994 NamedDecl *Found,
3995 SourceLocation NameLoc,
3996 const Token &NextToken);
3997 /// Act on the result of classifying a name as an overload set.
3998 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3999
4000 /// Describes the detailed kind of a template name. Used in diagnostics.
4001 enum class TemplateNameKindForDiagnostics {
4002 ClassTemplate,
4003 FunctionTemplate,
4004 VarTemplate,
4005 AliasTemplate,
4006 TemplateTemplateParam,
4007 Concept,
4008 DependentTemplate
4009 };
4010 TemplateNameKindForDiagnostics
4011 getTemplateNameKindForDiagnostics(TemplateName Name);
4012
4013 /// Determine whether it's plausible that E was intended to be a
4014 /// template-name.
4015 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
4016 if (!getLangOpts().CPlusPlus || E.isInvalid())
4017 return false;
4018 Dependent = false;
4019 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
4020 return !DRE->hasExplicitTemplateArgs();
4021 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
4022 return !ME->hasExplicitTemplateArgs();
4023 Dependent = true;
4024 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
4025 return !DSDRE->hasExplicitTemplateArgs();
4026 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
4027 return !DSME->hasExplicitTemplateArgs();
4028 // Any additional cases recognized here should also be handled by
4029 // diagnoseExprIntendedAsTemplateName.
4030 return false;
4031 }
4032
4033 void warnOnReservedIdentifier(const NamedDecl *D);
4034 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
4035
4036 void ProcessPragmaExport(DeclaratorDecl *newDecl);
4037
4038 Decl *ActOnDeclarator(Scope *S, Declarator &D);
4039
4040 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
4041 MultiTemplateParamsArg TemplateParameterLists);
4042
4043 /// Attempt to fold a variable-sized type to a constant-sized type, returning
4044 /// true if we were successful.
4045 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
4046 SourceLocation Loc,
4047 unsigned FailedFoldDiagID);
4048
4049 /// Register the given locally-scoped extern "C" declaration so
4050 /// that it can be found later for redeclarations. We include any extern "C"
4051 /// declaration that is not visible in the translation unit here, not just
4052 /// function-scope declarations.
4053 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
4054
4055 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4056 /// If T is the name of a class, then each of the following shall have a
4057 /// name different from T:
4058 /// - every static data member of class T;
4059 /// - every member function of class T
4060 /// - every member of class T that is itself a type;
4061 /// \returns true if the declaration name violates these rules.
4062 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
4063
4064 /// Diagnose a declaration whose declarator-id has the given
4065 /// nested-name-specifier.
4066 ///
4067 /// \param SS The nested-name-specifier of the declarator-id.
4068 ///
4069 /// \param DC The declaration context to which the nested-name-specifier
4070 /// resolves.
4071 ///
4072 /// \param Name The name of the entity being declared.
4073 ///
4074 /// \param Loc The location of the name of the entity being declared.
4075 ///
4076 /// \param IsMemberSpecialization Whether we are declaring a member
4077 /// specialization.
4078 ///
4079 /// \param TemplateId The template-id, if any.
4080 ///
4081 /// \returns true if we cannot safely recover from this error, false
4082 /// otherwise.
4083 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4084 DeclarationName Name, SourceLocation Loc,
4085 TemplateIdAnnotation *TemplateId,
4086 bool IsMemberSpecialization);
4087
4088 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
4089
4090 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
4091
4092 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
4093 unsigned &IntVal);
4094
4095 /// Diagnose function specifiers on a declaration of an identifier that
4096 /// does not identify a function.
4097 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
4098
4099 /// Return the declaration shadowed by the given typedef \p D, or null
4100 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4101 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
4102 const LookupResult &R);
4103
4104 /// Return the declaration shadowed by the given variable \p D, or null
4105 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4106 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
4107
4108 /// Return the declaration shadowed by the given variable \p D, or null
4109 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
4110 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
4111 const LookupResult &R);
4112 /// Diagnose variable or built-in function shadowing. Implements
4113 /// -Wshadow.
4114 ///
4115 /// This method is called whenever a VarDecl is added to a "useful"
4116 /// scope.
4117 ///
4118 /// \param ShadowedDecl the declaration that is shadowed by the given variable
4119 /// \param R the lookup of the name
4120 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
4121 const LookupResult &R);
4122
4123 /// Check -Wshadow without the advantage of a previous lookup.
4124 void CheckShadow(Scope *S, VarDecl *D);
4125
4126 /// Warn if 'E', which is an expression that is about to be modified, refers
4127 /// to a shadowing declaration.
4128 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
4129
4130 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4131 /// when these variables are captured by the lambda.
4132 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4133
4134 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4135 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4136 TypedefNameDecl *NewTD);
4137 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4138 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4139 TypeSourceInfo *TInfo,
4140 LookupResult &Previous);
4141
4142 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4143 /// declares a typedef-name, either using the 'typedef' type specifier or via
4144 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4145 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4146 LookupResult &Previous, bool &Redeclaration);
4147 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4148 TypeSourceInfo *TInfo,
4149 LookupResult &Previous,
4150 MultiTemplateParamsArg TemplateParamLists,
4151 bool &AddToScope,
4152 ArrayRef<BindingDecl *> Bindings = {});
4153
4154private:
4155 // Perform a check on an AsmLabel to verify its consistency and emit
4156 // diagnostics in case of an error.
4157 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4158 TypeSourceInfo *TInfo, VarDecl *);
4159
4160public:
4161 /// Perform semantic checking on a newly-created variable
4162 /// declaration.
4163 ///
4164 /// This routine performs all of the type-checking required for a
4165 /// variable declaration once it has been built. It is used both to
4166 /// check variables after they have been parsed and their declarators
4167 /// have been translated into a declaration, and to check variables
4168 /// that have been instantiated from a template.
4169 ///
4170 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4171 ///
4172 /// Returns true if the variable declaration is a redeclaration.
4173 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4174 void CheckVariableDeclarationType(VarDecl *NewVD);
4175 void CheckCompleteVariableDeclaration(VarDecl *VD);
4176
4177 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4178 TypeSourceInfo *TInfo,
4179 LookupResult &Previous,
4180 MultiTemplateParamsArg TemplateParamLists,
4181 bool &AddToScope);
4182
4183 /// Attach the ABI tag a standard calling convention variant requires, as an
4184 /// implicit abi_tag attribute. Call this once the function type is final.
4185 void addImplicitCallingConvAbiTag(FunctionDecl *FD);
4186
4187 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4188 /// and if so, check that it's a valid override and remember it.
4189 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4190
4191 /// Perform semantic checking of a new function declaration.
4192 ///
4193 /// Performs semantic analysis of the new function declaration
4194 /// NewFD. This routine performs all semantic checking that does not
4195 /// require the actual declarator involved in the declaration, and is
4196 /// used both for the declaration of functions as they are parsed
4197 /// (called via ActOnDeclarator) and for the declaration of functions
4198 /// that have been instantiated via C++ template instantiation (called
4199 /// via InstantiateDecl).
4200 ///
4201 /// \param IsMemberSpecialization whether this new function declaration is
4202 /// a member specialization (that replaces any definition provided by the
4203 /// previous declaration).
4204 ///
4205 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4206 ///
4207 /// \returns true if the function declaration is a redeclaration.
4208 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4209 LookupResult &Previous,
4210 bool IsMemberSpecialization, bool DeclIsDefn);
4211
4212 /// Checks if the new declaration declared in dependent context must be
4213 /// put in the same redeclaration chain as the specified declaration.
4214 ///
4215 /// \param D Declaration that is checked.
4216 /// \param PrevDecl Previous declaration found with proper lookup method for
4217 /// the same declaration name.
4218 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4219 /// belongs to.
4220 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4221
4222 /// Determines if we can perform a correct type check for \p D as a
4223 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4224 /// best-effort check.
4225 ///
4226 /// \param NewD The new declaration.
4227 /// \param OldD The old declaration.
4228 /// \param NewT The portion of the type of the new declaration to check.
4229 /// \param OldT The portion of the type of the old declaration to check.
4230 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4231 QualType NewT, QualType OldT);
4232 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4233 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4234
4235 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4236 /// containing class. Otherwise it will return implicit SectionAttr if the
4237 /// function is a definition and there is an active value on CodeSegStack
4238 /// (from the current #pragma code-seg value).
4239 ///
4240 /// \param FD Function being declared.
4241 /// \param IsDefinition Whether it is a definition or just a declaration.
4242 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4243 /// nullptr if no attribute should be added.
4244 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4245 bool IsDefinition);
4246
4247 /// Common checks for a parameter-declaration that should apply to both
4248 /// function parameters and non-type template parameters.
4249 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4250
4251 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4252 /// to introduce parameters into function prototype scope.
4253 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4254 SourceLocation ExplicitThisLoc = {});
4255
4256 /// Synthesizes a variable for a parameter arising from a
4257 /// typedef.
4258 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4259 QualType T);
4260 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4261 SourceLocation NameLoc,
4262 const IdentifierInfo *Name, QualType T,
4263 TypeSourceInfo *TSInfo, StorageClass SC);
4264
4265 /// Emit diagnostics if the initializer or any of its explicit or
4266 /// implicitly-generated subexpressions require copying or
4267 /// default-initializing a type that is or contains a C union type that is
4268 /// non-trivial to copy or default-initialize.
4269 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4270
4271 // These flags are passed to checkNonTrivialCUnion.
4272 enum NonTrivialCUnionKind {
4273 NTCUK_Init = 0x1,
4274 NTCUK_Destruct = 0x2,
4275 NTCUK_Copy = 0x4,
4276 };
4277
4278 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4279 /// a non-trivial C union is used in an invalid context.
4280 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4281 NonTrivialCUnionContext UseContext,
4282 unsigned NonTrivialKind);
4283
4284 /// Certain globally-unique variables might be accidentally duplicated if
4285 /// built into multiple shared libraries with hidden visibility. This can
4286 /// cause problems if the variable is mutable, its initialization is
4287 /// effectful, or its address is taken.
4288 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4289 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4290
4291 /// AddInitializerToDecl - Adds the initializer Init to the
4292 /// declaration dcl. If DirectInit is true, this is C++ direct
4293 /// initialization rather than copy initialization.
4294 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4295 void ActOnUninitializedDecl(Decl *dcl);
4296
4297 /// ActOnInitializerError - Given that there was an error parsing an
4298 /// initializer for the given declaration, try to at least re-establish
4299 /// invariants such as whether a variable's type is either dependent or
4300 /// complete.
4301 void ActOnInitializerError(Decl *Dcl);
4302
4303 void ActOnCXXForRangeDecl(Decl *D, bool InExpansionStmt);
4304 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4305 IdentifierInfo *Ident,
4306 ParsedAttributes &Attrs);
4307
4308 /// Check if VD needs to be dllexport/dllimport due to being in a
4309 /// dllexport/import function.
4310 void CheckStaticLocalForDllExport(VarDecl *VD);
4311 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4312
4313 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4314 /// any semantic actions necessary after any initializer has been attached.
4315 void FinalizeDeclaration(Decl *D);
4316 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4317 ArrayRef<Decl *> Group);
4318
4319 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4320 /// group, performing any necessary semantic checking.
4321 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4322
4323 /// Should be called on all declarations that might have attached
4324 /// documentation comments.
4325 void ActOnDocumentableDecl(Decl *D);
4326 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4327
4328 enum class FnBodyKind {
4329 /// C++26 [dcl.fct.def.general]p1
4330 /// function-body:
4331 /// ctor-initializer[opt] compound-statement
4332 /// function-try-block
4333 Other,
4334 /// = default ;
4335 Default,
4336 /// deleted-function-body
4337 ///
4338 /// deleted-function-body:
4339 /// = delete ;
4340 /// = delete ( unevaluated-string ) ;
4341 Delete
4342 };
4343
4344 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4345 SourceLocation LocAfterDecls);
4346 void CheckForFunctionRedefinition(
4347 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4348 SkipBodyInfo *SkipBody = nullptr);
4349 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4350 MultiTemplateParamsArg TemplateParamLists,
4351 SkipBodyInfo *SkipBody = nullptr,
4352 FnBodyKind BodyKind = FnBodyKind::Other);
4353 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4354 SkipBodyInfo *SkipBody = nullptr,
4355 FnBodyKind BodyKind = FnBodyKind::Other);
4356 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4357
4358 /// Determine whether we can delay parsing the body of a function or
4359 /// function template until it is used, assuming we don't care about emitting
4360 /// code for that function.
4361 ///
4362 /// This will be \c false if we may need the body of the function in the
4363 /// middle of parsing an expression (where it's impractical to switch to
4364 /// parsing a different function), for instance, if it's constexpr in C++11
4365 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4366 bool canDelayFunctionBody(const Declarator &D);
4367
4368 /// Determine whether we can skip parsing the body of a function
4369 /// definition, assuming we don't care about analyzing its body or emitting
4370 /// code for that function.
4371 ///
4372 /// This will be \c false only if we may need the body of the function in
4373 /// order to parse the rest of the program (for instance, if it is
4374 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4375 bool canSkipFunctionBody(Decl *D);
4376
4377 /// Given the set of return statements within a function body,
4378 /// compute the variables that are subject to the named return value
4379 /// optimization.
4380 ///
4381 /// Each of the variables that is subject to the named return value
4382 /// optimization will be marked as NRVO variables in the AST, and any
4383 /// return statement that has a marked NRVO variable as its NRVO candidate can
4384 /// use the named return value optimization.
4385 ///
4386 /// This function applies a very simplistic algorithm for NRVO: if every
4387 /// return statement in the scope of a variable has the same NRVO candidate,
4388 /// that candidate is an NRVO variable.
4389 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4390
4391 /// Performs semantic analysis at the end of a function body.
4392 ///
4393 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4394 /// releasing the associated \p FunctionScopeInfo. This is useful when
4395 /// building e.g. LambdaExprs.
4396 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4397 bool IsInstantiation = false,
4398 bool RetainFunctionScopeInfo = false);
4399 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4400 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4401
4402 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4403 /// attribute for which parsing is delayed.
4404 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4405
4406 /// Diagnose any unused parameters in the given sequence of
4407 /// ParmVarDecl pointers.
4408 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4409
4410 /// Diagnose whether the size of parameters or return value of a
4411 /// function or obj-c method definition is pass-by-value and larger than a
4412 /// specified threshold.
4413 void
4414 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4415 QualType ReturnTy, NamedDecl *D);
4416
4417 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4418 SourceLocation RParenLoc);
4419
4420 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4421 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4422
4423 void ActOnPopScope(SourceLocation Loc, Scope *S);
4424
4425 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4426 /// no declarator (e.g. "struct foo;") is parsed.
4427 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4428 const ParsedAttributesView &DeclAttrs,
4429 RecordDecl *&AnonRecord);
4430
4431 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4432 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4433 /// parameters to cope with template friend declarations.
4434 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4435 const ParsedAttributesView &DeclAttrs,
4436 MultiTemplateParamsArg TemplateParams,
4437 bool IsExplicitInstantiation,
4438 RecordDecl *&AnonRecord,
4439 SourceLocation EllipsisLoc = {});
4440
4441 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4442 /// anonymous structure or union. Anonymous unions are a C++ feature
4443 /// (C++ [class.union]) and a C11 feature; anonymous structures
4444 /// are a C11 feature and GNU C++ extension.
4445 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4446 RecordDecl *Record,
4447 const PrintingPolicy &Policy);
4448
4449 /// Called once it is known whether
4450 /// a tag declaration is an anonymous union or struct.
4451 void ActOnDefinedDeclarationSpecifier(Decl *D);
4452
4453 /// Emit diagnostic warnings for placeholder members.
4454 /// We can only do that after the class is fully constructed,
4455 /// as anonymous union/structs can insert placeholders
4456 /// in their parent scope (which might be a Record).
4457 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4458
4459 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4460 /// Microsoft C anonymous structure.
4461 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4462 /// Example:
4463 ///
4464 /// struct A { int a; };
4465 /// struct B { struct A; int b; };
4466 ///
4467 /// void foo() {
4468 /// B var;
4469 /// var.a = 3;
4470 /// }
4471 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4472 RecordDecl *Record);
4473
4474 /// Given a non-tag type declaration, returns an enum useful for indicating
4475 /// what kind of non-tag type this is.
4476 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4477
4478 /// Determine whether a tag with a given kind is acceptable
4479 /// as a redeclaration of the given tag declaration.
4480 ///
4481 /// \returns true if the new tag kind is acceptable, false otherwise.
4482 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4483 bool isDefinition, SourceLocation NewTagLoc,
4484 const IdentifierInfo *Name);
4485
4486 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4487 /// former case, Name will be non-null. In the later case, Name will be null.
4488 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4489 /// a reference/declaration/definition of a tag.
4490 ///
4491 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4492 /// trailing-type-specifier) other than one in an alias-declaration.
4493 ///
4494 /// \param SkipBody If non-null, will be set to indicate if the caller should
4495 /// skip the definition of this tag and treat it as if it were a declaration.
4496 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4497 SourceLocation KWLoc, CXXScopeSpec &SS,
4498 IdentifierInfo *Name, SourceLocation NameLoc,
4499 const ParsedAttributesView &Attr, AccessSpecifier AS,
4500 SourceLocation ModulePrivateLoc,
4501 MultiTemplateParamsArg TemplateParameterLists,
4502 bool &OwnedDecl, bool &IsDependent,
4503 SourceLocation ScopedEnumKWLoc,
4504 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4505 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4506 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4507
4508 /// ActOnField - Each field of a C struct/union is passed into this in order
4509 /// to create a FieldDecl object for it.
4510 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4511 Declarator &D, Expr *BitfieldWidth);
4512
4513 /// HandleField - Analyze a field of a C struct or a C++ data member.
4514 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4515 Declarator &D, Expr *BitfieldWidth,
4516 InClassInitStyle InitStyle, AccessSpecifier AS);
4517
4518 /// Build a new FieldDecl and check its well-formedness.
4519 ///
4520 /// This routine builds a new FieldDecl given the fields name, type,
4521 /// record, etc. \p PrevDecl should refer to any previous declaration
4522 /// with the same name and in the same scope as the field to be
4523 /// created.
4524 ///
4525 /// \returns a new FieldDecl.
4526 ///
4527 /// \todo The Declarator argument is a hack. It will be removed once
4528 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4529 TypeSourceInfo *TInfo, RecordDecl *Record,
4530 SourceLocation Loc, bool Mutable,
4531 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4532 SourceLocation TSSL, AccessSpecifier AS,
4533 NamedDecl *PrevDecl, Declarator *D = nullptr);
4534
4535 bool CheckNontrivialField(FieldDecl *FD);
4536
4537 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4538 /// class and class extensions. For every class \@interface and class
4539 /// extension \@interface, if the last ivar is a bitfield of any type,
4540 /// then add an implicit `char :0` ivar to the end of that interface.
4541 void ActOnLastBitfield(SourceLocation DeclStart,
4542 SmallVectorImpl<Decl *> &AllIvarDecls);
4543
4544 // This is used for both record definitions and ObjC interface declarations.
4545 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4546 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4547 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4548
4549 /// ActOnTagStartDefinition - Invoked when we have entered the
4550 /// scope of a tag's definition (e.g., for an enumeration, class,
4551 /// struct, or union).
4552 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4553
4554 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4555 /// Differently from C++, actually parse the body and reject / error out
4556 /// in case of a structural mismatch.
4557 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4558
4559 typedef void *SkippedDefinitionContext;
4560
4561 /// Invoked when we enter a tag definition that we're skipping.
4562 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4563
4564 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4565 /// C++ record definition's base-specifiers clause and are starting its
4566 /// member declarations.
4567 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4568 SourceLocation FinalLoc,
4569 bool IsFinalSpelledSealed,
4570 bool IsAbstract,
4571 SourceLocation LBraceLoc);
4572
4573 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4574 /// the definition of a tag (enumeration, class, struct, or union).
4575 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4576 SourceRange BraceRange);
4577
4578 ASTContext::CXXRecordDeclRelocationInfo
4579 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4580
4581 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4582
4583 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4584 /// error parsing the definition of a tag.
4585 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4586
4587 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4588 EnumConstantDecl *LastEnumConst,
4589 SourceLocation IdLoc, IdentifierInfo *Id,
4590 Expr *val);
4591
4592 /// Check that this is a valid underlying type for an enum declaration.
4593 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4594
4595 /// Check whether this is a valid redeclaration of a previous enumeration.
4596 /// \return true if the redeclaration was invalid.
4597 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4598 QualType EnumUnderlyingTy, bool IsFixed,
4599 const EnumDecl *Prev);
4600
4601 /// Determine whether the body of an anonymous enumeration should be skipped.
4602 /// \param II The name of the first enumerator.
4603 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4604 SourceLocation IILoc);
4605
4606 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4607 SourceLocation IdLoc, IdentifierInfo *Id,
4608 const ParsedAttributesView &Attrs,
4609 SourceLocation EqualLoc, Expr *Val,
4610 SkipBodyInfo *SkipBody = nullptr);
4611 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4612 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4613 const ParsedAttributesView &Attr);
4614
4615 /// Set the current declaration context until it gets popped.
4616 void PushDeclContext(Scope *S, DeclContext *DC);
4617 void PopDeclContext();
4618
4619 /// EnterDeclaratorContext - Used when we must lookup names in the context
4620 /// of a declarator's nested name specifier.
4621 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4622 void ExitDeclaratorContext(Scope *S);
4623
4624 /// Enter a template parameter scope, after it's been associated with a
4625 /// particular DeclContext. Causes lookup within the scope to chain through
4626 /// enclosing contexts in the correct order.
4627 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4628
4629 /// Push the parameters of D, which must be a function, into scope.
4630 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4631
4632 /// Add \p Params to scope, so a late-parsed attribute can name them.
4633 void ActOnReenterFunctionPrototypeParams(Scope *S,
4634 ArrayRef<ParmVarDecl *> Params);
4635 /// Undo the above, for when \p S outlives the attribute so no scope pop
4636 /// removes them.
4637 void ActOnExitFunctionPrototypeParams(Scope *S,
4638 ArrayRef<ParmVarDecl *> Params);
4639 void ActOnExitFunctionContext();
4640
4641 /// Add this decl to the scope shadowed decl chains.
4642 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4643
4644 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4645 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4646 /// true if 'D' belongs to the given declaration context.
4647 ///
4648 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4649 /// enclosing namespace set of the context, rather than contained
4650 /// directly within it.
4651 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4652 bool AllowInlineNamespace = false) const;
4653
4654 /// Determine whether a tag-like declaration found by lookup can be
4655 /// redeclared in the given scope. If lookup found a using-shadow, also
4656 /// consider the scope of the declaration named by the using-shadow.
4657 bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx,
4658 Scope *S = nullptr,
4659 bool AllowInlineNamespace = false) const;
4660
4661 /// Finds the scope corresponding to the given decl context, if it
4662 /// happens to be an enclosing scope. Otherwise return NULL.
4663 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4664
4665 /// Subroutines of ActOnDeclarator().
4666 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4667 TypeSourceInfo *TInfo);
4668 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4669
4670 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4671 void mergeDeclAttributes(
4672 NamedDecl *New, Decl *Old,
4673 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4674
4675 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4676 /// requires the type to be deduced.
4677 void CheckAttributesOnDeducedType(Decl *D);
4678
4679 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4680 /// same name and scope as a previous declaration 'Old'. Figure out
4681 /// how to resolve this situation, merging decls or emitting
4682 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4683 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4684 LookupResult &OldDecls);
4685
4686 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4687 /// definition visible.
4688 /// This method performs any necessary cleanup on the parser state to discard
4689 /// child nodes from newly parsed decl we are retiring.
4690 void CleanupMergedEnum(Scope *S, Decl *New);
4691
4692 /// MergeFunctionDecl - We just parsed a function 'New' from
4693 /// declarator D which has the same name and scope as a previous
4694 /// declaration 'Old'. Figure out how to resolve this situation,
4695 /// merging decls or emitting diagnostics as appropriate.
4696 ///
4697 /// In C++, New and Old must be declarations that are not
4698 /// overloaded. Use IsOverload to determine whether New and Old are
4699 /// overloaded, and to select the Old declaration that New should be
4700 /// merged with.
4701 ///
4702 /// Returns true if there was an error, false otherwise.
4703 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4704 bool MergeTypeWithOld, bool NewDeclIsDefn);
4705
4706 /// Completes the merge of two function declarations that are
4707 /// known to be compatible.
4708 ///
4709 /// This routine handles the merging of attributes and other
4710 /// properties of function declarations from the old declaration to
4711 /// the new declaration, once we know that New is in fact a
4712 /// redeclaration of Old.
4713 ///
4714 /// \returns false
4715 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4716 Scope *S, bool MergeTypeWithOld);
4717 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4718
4719 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4720 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4721 /// situation, merging decls or emitting diagnostics as appropriate.
4722 ///
4723 /// Tentative definition rules (C99 6.9.2p2) are checked by
4724 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4725 /// definitions here, since the initializer hasn't been attached.
4726 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4727
4728 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4729 /// scope as a previous declaration 'Old'. Figure out how to merge their
4730 /// types, emitting diagnostics as appropriate.
4731 ///
4732 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4733 /// back to here in AddInitializerToDecl. We can't check them before the
4734 /// initializer is attached.
4735 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4736
4737 /// We've just determined that \p Old and \p New both appear to be definitions
4738 /// of the same variable. Either diagnose or fix the problem.
4739 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4740 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4741
4742 /// Filters out lookup results that don't fall within the given scope
4743 /// as determined by isDeclInScope.
4744 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4745 bool ConsiderLinkage, bool AllowInlineNamespace);
4746
4747 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4748 /// have compatible owning modules.
4749 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4750
4751 /// [module.interface]p6:
4752 /// A redeclaration of an entity X is implicitly exported if X was introduced
4753 /// by an exported declaration; otherwise it shall not be exported.
4754 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4755
4756 /// A wrapper function for checking the semantic restrictions of
4757 /// a redeclaration within a module.
4758 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4759
4760 /// Check the redefinition in C++20 Modules.
4761 ///
4762 /// [basic.def.odr]p14:
4763 /// For any definable item D with definitions in multiple translation units,
4764 /// - if D is a non-inline non-templated function or variable, or
4765 /// - if the definitions in different translation units do not satisfy the
4766 /// following requirements,
4767 /// the program is ill-formed; a diagnostic is required only if the
4768 /// definable item is attached to a named module and a prior definition is
4769 /// reachable at the point where a later definition occurs.
4770 /// - Each such definition shall not be attached to a named module
4771 /// ([module.unit]).
4772 /// - Each such definition shall consist of the same sequence of tokens, ...
4773 /// ...
4774 ///
4775 /// Return true if the redefinition is not allowed. Return false otherwise.
4776 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4777
4778 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4779
4780 /// If it's a file scoped decl that must warn if not used, keep track
4781 /// of it.
4782 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4783
4784 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4785 DiagReceiverTy;
4786
4787 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4788 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4789 DiagReceiverTy DiagReceiver);
4790 void DiagnoseUnusedDecl(const NamedDecl *ND);
4791
4792 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4793 /// unless they are marked attr(unused).
4794 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4795
4796 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4797 /// variable.
4798 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4799
4800 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4801 /// from S, where a non-field would be declared. This routine copes
4802 /// with the difference between C and C++ scoping rules in structs and
4803 /// unions. For example, the following code is well-formed in C but
4804 /// ill-formed in C++:
4805 /// @code
4806 /// struct S6 {
4807 /// enum { BAR } e;
4808 /// };
4809 ///
4810 /// void test_S6() {
4811 /// struct S6 a;
4812 /// a.e = BAR;
4813 /// }
4814 /// @endcode
4815 /// For the declaration of BAR, this routine will return a different
4816 /// scope. The scope S will be the scope of the unnamed enumeration
4817 /// within S6. In C++, this routine will return the scope associated
4818 /// with S6, because the enumeration's scope is a transparent
4819 /// context but structures can contain non-field names. In C, this
4820 /// routine will return the translation unit scope, since the
4821 /// enumeration's scope is a transparent context and structures cannot
4822 /// contain non-field names.
4823 Scope *getNonFieldDeclScope(Scope *S);
4824
4825 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4826 SourceLocation Loc);
4827
4828 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4829 /// file scope. lazily create a decl for it. ForRedeclaration is true
4830 /// if we're creating this built-in in anticipation of redeclaring the
4831 /// built-in.
4832 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4833 bool ForRedeclaration, SourceLocation Loc);
4834
4835 /// Get the outermost AttributedType node that sets a calling convention.
4836 /// Valid types should not have multiple attributes with different CCs.
4837 const AttributedType *getCallingConvAttributedType(QualType T) const;
4838
4839 /// GetNameForDeclarator - Determine the full declaration name for the
4840 /// given Declarator.
4841 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4842
4843 /// Retrieves the declaration name from a parsed unqualified-id.
4844 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4845
4846 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4847 /// we are currently parsing the initializer.
4848 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4849
4850 /// Look for a locally scoped extern "C" declaration by the given name.
4851 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4852
4853 void deduceOpenCLAddressSpace(VarDecl *decl);
4854
4855 /// Adjust the \c DeclContext for a function or variable that might be a
4856 /// function-local external declaration.
4857 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4858
4859 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4860
4861 /// Checks if the variant/multiversion functions are compatible.
4862 bool areMultiversionVariantFunctionsCompatible(
4863 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4864 const PartialDiagnostic &NoProtoDiagID,
4865 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4866 const PartialDiagnosticAt &NoSupportDiagIDAt,
4867 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4868 bool ConstexprSupported, bool CLinkageMayDiffer);
4869
4870 /// type checking declaration initializers (C99 6.7.8)
4871 bool CheckForConstantInitializer(
4872 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4873
4874 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4875 QualType Type, TypeSourceInfo *TSI,
4876 SourceRange Range, bool DirectInit,
4877 Expr *Init);
4878
4879 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4880 Expr *Init);
4881
4882 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4883
4884 // Heuristically tells if the function is `get_return_object` member of a
4885 // coroutine promise_type by matching the function name.
4886 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4887 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4888
4889 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4890 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4891 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4892 Scope *S);
4893
4894 /// If this function is a C++ replaceable global allocation function
4895 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4896 /// adds any function attributes that we know a priori based on the standard.
4897 ///
4898 /// We need to check for duplicate attributes both here and where user-written
4899 /// attributes are applied to declarations.
4900 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4901 FunctionDecl *FD);
4902
4903 /// Adds any function attributes that we know a priori based on
4904 /// the declaration of this function.
4905 ///
4906 /// These attributes can apply both to implicitly-declared builtins
4907 /// (like __builtin___printf_chk) or to library-declared functions
4908 /// like NSLog or printf.
4909 ///
4910 /// We need to check for duplicate attributes both here and where user-written
4911 /// attributes are applied to declarations.
4912 void AddKnownFunctionAttributes(FunctionDecl *FD);
4913
4914 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4915 /// the correct width, and that the field type is valid.
4916 /// Returns false on success.
4917 ExprResult VerifyBitField(SourceLocation FieldLoc,
4918 const IdentifierInfo *FieldName, QualType FieldTy,
4919 bool IsMsStruct, Expr *BitWidth);
4920
4921 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4922 /// enum. If AllowMask is true, then we also allow the complement of a valid
4923 /// value, to be used as a mask.
4924 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4925 bool AllowMask) const;
4926
4927 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4928 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4929 SourceLocation WeakNameLoc);
4930
4931 /// ActOnPragmaRedefineExtname - Called on well formed
4932 /// \#pragma redefine_extname oldname newname.
4933 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4934 IdentifierInfo *AliasName,
4935 SourceLocation PragmaLoc,
4936 SourceLocation WeakNameLoc,
4937 SourceLocation AliasNameLoc);
4938
4939 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4940 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4941 SourceLocation PragmaLoc,
4942 SourceLocation WeakNameLoc,
4943 SourceLocation AliasNameLoc);
4944
4945 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4946 enum class FunctionEmissionStatus {
4947 Emitted,
4948 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4949 OMPDiscarded, // Discarded due to OpenMP hostness
4950 TemplateDiscarded, // Discarded due to uninstantiated templates
4951 Unknown,
4952 };
4953 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4954 bool Final = false);
4955
4956 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4957 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4958
4959 /// Function or variable declarations to be checked for whether the deferred
4960 /// diagnostics should be emitted.
4961 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4962
4963private:
4964 /// Map of current shadowing declarations to shadowed declarations. Warn if
4965 /// it looks like the user is trying to modify the shadowing declaration.
4966 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4967
4968 // We need this to handle
4969 //
4970 // typedef struct {
4971 // void *foo() { return 0; }
4972 // } A;
4973 //
4974 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4975 // for example. If 'A', foo will have external linkage. If we have '*A',
4976 // foo will have no linkage. Since we can't know until we get to the end
4977 // of the typedef, this function finds out if D might have non-external
4978 // linkage. Callers should verify at the end of the TU if it D has external
4979 // linkage or not.
4980 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4981
4982#include "clang/Sema/AttrIsTypeDependent.inc"
4983
4984 ///@}
4985
4986 //
4987 //
4988 // -------------------------------------------------------------------------
4989 //
4990 //
4991
4992 /// \name Declaration Attribute Handling
4993 /// Implementations are in SemaDeclAttr.cpp
4994 ///@{
4995
4996public:
4997 /// Describes the kind of priority given to an availability attribute.
4998 ///
4999 /// The sum of priorities deteremines the final priority of the attribute.
5000 /// The final priority determines how the attribute will be merged.
5001 /// An attribute with a lower priority will always remove higher priority
5002 /// attributes for the specified platform when it is being applied. An
5003 /// attribute with a higher priority will not be applied if the declaration
5004 /// already has an availability attribute with a lower priority for the
5005 /// specified platform. The final prirority values are not expected to match
5006 /// the values in this enumeration, but instead should be treated as a plain
5007 /// integer value. This enumeration just names the priority weights that are
5008 /// used to calculate that final vaue.
5009 enum AvailabilityPriority : int {
5010 /// The availability attribute was specified explicitly next to the
5011 /// declaration.
5012 AP_Explicit = 0,
5013
5014 /// The availability attribute was applied using '#pragma clang attribute'.
5015 AP_PragmaClangAttribute = 1,
5016
5017 /// The availability attribute for a specific platform was inferred from
5018 /// an availability attribute for another platform.
5019 AP_InferredFromOtherPlatform = 2,
5020
5021 /// The availability attribute was inferred from an 'anyAppleOS'
5022 /// availability attribute.
5023 AP_InferredFromAnyAppleOS = 3,
5024
5025 /// The availability attribute was inferred from an 'anyAppleOS'
5026 /// availability attribute that was applied using '#pragma clang attribute'.
5027 /// This has the lowest priority.
5028 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
5029 };
5030
5031 /// Describes the reason a calling convention specification was ignored, used
5032 /// for diagnostics.
5033 enum class CallingConventionIgnoredReason {
5034 ForThisTarget = 0,
5035 VariadicFunction,
5036 ConstructorDestructor,
5037 BuiltinFunction
5038 };
5039
5040 /// A helper function to provide Attribute Location for the Attr types
5041 /// AND the ParsedAttr.
5042 template <typename AttrInfo>
5043 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
5044 getAttrLoc(const AttrInfo &AL) {
5045 return AL.getLocation();
5046 }
5047 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
5048
5049 /// If Expr is a valid integer constant, get the value of the integer
5050 /// expression and return success or failure. May output an error.
5051 ///
5052 /// Negative argument is implicitly converted to unsigned, unless
5053 /// \p StrictlyUnsigned is true.
5054 template <typename AttrInfo>
5055 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
5056 unsigned Idx = UINT_MAX,
5057 bool StrictlyUnsigned = false) {
5058 std::optional<llvm::APSInt> I = llvm::APSInt(32);
5059 if (Expr->isTypeDependent() ||
5060 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
5061 if (Idx != UINT_MAX)
5062 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5063 << &AI << Idx << AANT_ArgumentIntegerConstant
5064 << Expr->getSourceRange();
5065 else
5066 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
5067 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
5068 return false;
5069 }
5070
5071 if (!I->isIntN(N: 32)) {
5072 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
5073 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
5074 return false;
5075 }
5076
5077 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
5078 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
5079 << &AI << /*non-negative*/ 1;
5080 return false;
5081 }
5082
5083 Val = (uint32_t)I->getZExtValue();
5084 return true;
5085 }
5086
5087 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
5088 /// \#pragma weak during processing of other Decls.
5089 /// I couldn't figure out a clean way to generate these in-line, so
5090 /// we store them here and handle separately -- which is a hack.
5091 /// It would be best to refactor this.
5092 SmallVector<Decl *, 2> WeakTopLevelDecl;
5093
5094 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
5095 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
5096
5097 typedef LazyVector<TypedefNameDecl *, &ExternalSemaSource::ReadExtVectorDecls,
5098 2, 2>
5099 ExtVectorDeclsType;
5100
5101 /// ExtVectorDecls - This is a list all the extended vector types. This allows
5102 /// us to associate a raw vector type with one of the ext_vector type names.
5103 /// This is only necessary for issuing pretty diagnostics.
5104 ExtVectorDeclsType ExtVectorDecls;
5105
5106 /// Check if the argument \p E is a ASCII string literal. If not emit an error
5107 /// and return false, otherwise set \p Str to the value of the string literal
5108 /// and return true.
5109 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
5110 const Expr *E, StringRef &Str,
5111 SourceLocation *ArgLocation = nullptr);
5112
5113 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
5114 /// If not emit an error and return false. If the argument is an identifier it
5115 /// will emit an error with a fixit hint and treat it as if it was a string
5116 /// literal.
5117 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
5118 StringRef &Str,
5119 SourceLocation *ArgLocation = nullptr);
5120
5121 /// Determine if type T is a valid subject for a nonnull and similar
5122 /// attributes. Dependent types are considered valid so they can be checked
5123 /// during instantiation time. By default, we look through references (the
5124 /// behavior used by nonnull), but if the second parameter is true, then we
5125 /// treat a reference type as valid.
5126 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
5127
5128 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
5129 /// declaration.
5130 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5131 Expr *OE);
5132
5133 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
5134 /// declaration.
5135 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
5136 Expr *ParamExpr);
5137
5138 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
5139 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
5140
5141 AvailabilityAttr *
5142 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
5143 const IdentifierInfo *Platform, bool Implicit,
5144 VersionTuple Introduced, VersionTuple Deprecated,
5145 VersionTuple Obsoleted, bool IsUnavailable,
5146 StringRef Message, bool IsStrict, StringRef Replacement,
5147 AvailabilityMergeKind AMK, int Priority,
5148 const IdentifierInfo *IIEnvironment,
5149 const IdentifierInfo *InferredPlatformII = nullptr);
5150
5151 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5152 NamedDecl *D, const AttributeCommonInfo &CI,
5153 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5154 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5155 StringRef Message, bool IsStrict, StringRef Replacement,
5156 AvailabilityMergeKind AMK, int Priority,
5157 const IdentifierInfo *IIEnvironment,
5158 const IdentifierInfo *InferredPlatformII);
5159
5160 TypeVisibilityAttr *
5161 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5162 TypeVisibilityAttr::VisibilityType Vis);
5163 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5164 VisibilityAttr::VisibilityType Vis);
5165 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5166 VisibilityAttr::VisibilityType Type);
5167 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5168 StringRef Name);
5169
5170 /// Used to implement to perform semantic checking on
5171 /// attribute((section("foo"))) specifiers.
5172 ///
5173 /// In this case, "foo" is passed in to be checked. If the section
5174 /// specifier is invalid, return an Error that indicates the problem.
5175 ///
5176 /// This is a simple quality of implementation feature to catch errors
5177 /// and give good diagnostics in cases when the assembler or code generator
5178 /// would otherwise reject the section specifier.
5179 llvm::Error isValidSectionSpecifier(StringRef Str);
5180 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5181 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5182 StringRef Name);
5183
5184 // Check for things we'd like to warn about. Multiversioning issues are
5185 // handled later in the process, once we know how many exist.
5186 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5187
5188 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5189 StringRef NewUserDiagnostic);
5190 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5191 const IdentifierInfo *Format, int FormatIdx,
5192 int FirstArg);
5193 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5194 const AttributeCommonInfo &CI,
5195 const IdentifierInfo *Format,
5196 int FormatIdx,
5197 StringLiteral *FormatStr);
5198 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5199 const AttributeCommonInfo &CI,
5200 const IdentifierInfo *ModularImplFn,
5201 StringRef ImplName,
5202 MutableArrayRef<StringRef> Aspects);
5203
5204 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5205 const AttributeCommonInfo &CI);
5206
5207 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5208 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5209 bool IsPackExpansion);
5210 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5211 bool IsPackExpansion);
5212
5213 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5214 /// declaration.
5215 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5216
5217 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5218 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5219 MutableArrayRef<Expr *> Args);
5220 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5221
5222 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5223 bool BestCase,
5224 MSInheritanceModel SemanticSpelling);
5225
5226 void CheckAlignasUnderalignment(Decl *D);
5227
5228 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5229 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5230 const IdentifierInfo *Name, bool InInstantiation = false);
5231 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5232 const AttributeCommonInfo &CI,
5233 const IdentifierInfo *Ident);
5234 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5235 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5236 const AttributeCommonInfo &CI);
5237 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5238 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5239 const InternalLinkageAttr &AL);
5240
5241 /// Check validaty of calling convention attribute \p attr. If \p FD
5242 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5243 /// target. Otherwise, it is specified by \p CFT.
5244 bool CheckCallingConvAttr(
5245 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5246 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5247
5248 /// Checks a regparm attribute, returning true if it is ill-formed and
5249 /// otherwise setting numParams to the appropriate value.
5250 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5251
5252 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5253 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5254 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5255 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5256 Expr *MaxThreads,
5257 Expr *MinBlocks, Expr *MaxBlocks,
5258 bool IgnoreArch = false);
5259
5260 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5261 /// declaration.
5262 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5263 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5264
5265 /// Add a cluster_dims attribute to a particular declaration.
5266 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5267 Expr *X, Expr *Y, Expr *Z);
5268 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5269 Expr *Y, Expr *Z);
5270 /// Add a no_cluster attribute to a particular declaration.
5271 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5272
5273 enum class RetainOwnershipKind { NS, CF, OS };
5274
5275 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5276 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5277
5278 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5279
5280 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5281 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5282 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5283 const AttributeCommonInfo &CI,
5284 bool BestCase,
5285 MSInheritanceModel Model);
5286
5287 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5288 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5289 const EnforceTCBLeafAttr &AL);
5290
5291 /// Helper for delayed processing TransparentUnion or
5292 /// BPFPreserveAccessIndexAttr attribute.
5293 void ProcessDeclAttributeDelayed(Decl *D,
5294 const ParsedAttributesView &AttrList);
5295
5296 // Options for ProcessDeclAttributeList().
5297 struct ProcessDeclAttributeOptions {
5298 ProcessDeclAttributeOptions()
5299 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5300
5301 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5302 ProcessDeclAttributeOptions Result = *this;
5303 Result.IncludeCXX11Attributes = Val;
5304 return Result;
5305 }
5306
5307 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5308 ProcessDeclAttributeOptions Result = *this;
5309 Result.IgnoreTypeAttributes = Val;
5310 return Result;
5311 }
5312
5313 // Should C++11 attributes be processed?
5314 bool IncludeCXX11Attributes;
5315
5316 // Should any type attributes encountered be ignored?
5317 // If this option is false, a diagnostic will be emitted for any type
5318 // attributes of a kind that does not "slide" from the declaration to
5319 // the decl-specifier-seq.
5320 bool IgnoreTypeAttributes;
5321 };
5322
5323 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5324 /// attribute list to the specified decl, ignoring any type attributes.
5325 void ProcessDeclAttributeList(Scope *S, Decl *D,
5326 const ParsedAttributesView &AttrList,
5327 const ProcessDeclAttributeOptions &Options =
5328 ProcessDeclAttributeOptions());
5329
5330 /// Annotation attributes are the only attributes allowed after an access
5331 /// specifier.
5332 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5333 const ParsedAttributesView &AttrList);
5334
5335 /// checkUnusedDeclAttributes - Given a declarator which is not being
5336 /// used to build a declaration, complain about any decl attributes
5337 /// which might be lying around on it.
5338 void checkUnusedDeclAttributes(Declarator &D);
5339
5340 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5341
5342 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5343 /// \#pragma weak needs a non-definition decl and source may not have one.
5344 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5345 SourceLocation Loc);
5346
5347 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5348 /// applied to it, possibly with an alias.
5349 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5350
5351 void ProcessPragmaWeak(Scope *S, Decl *D);
5352 // Decl attributes - this routine is the top level dispatcher.
5353 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5354
5355 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5356
5357 /// Given a set of delayed diagnostics, re-emit them as if they had
5358 /// been delayed in the current context instead of in the given pool.
5359 /// Essentially, this just moves them to the current pool.
5360 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5361
5362 /// Check that the type is a plain record with one field being a pointer
5363 /// type and the other field being an integer. This matches the common
5364 /// implementation of std::span or sized_allocation_t in P0901R11.
5365 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5366
5367 /// Check if IdxExpr is a valid parameter index for a function or
5368 /// instance method D. May output an error.
5369 ///
5370 /// \returns true if IdxExpr is a valid index.
5371 template <typename AttrInfo>
5372 bool checkFunctionOrMethodParameterIndex(
5373 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5374 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5375 bool CanIndexVariadicArguments = false) {
5376 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5377
5378 // In C++ the implicit 'this' function parameter also counts.
5379 // Parameters are counted from one.
5380 bool HP = hasFunctionProto(D);
5381 bool IV = HP && isFunctionOrMethodVariadic(D);
5382 unsigned NumParams =
5383 HP ? getFunctionOrMethodNumParams(D, /*IncludeThis=*/IncludeThis: true) : 0;
5384
5385 std::optional<llvm::APSInt> IdxInt;
5386 if (IdxExpr->isTypeDependent() ||
5387 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5388 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5389 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5390 << IdxExpr->getSourceRange();
5391 return false;
5392 }
5393
5394 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5395 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5396 if (IdxSource < 1 || IdxSource == Limit ||
5397 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5398 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5399 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5400 return false;
5401 }
5402 if (hasImplicitObjectParameter(D) && !CanIndexImplicitThis) {
5403 if (IdxSource == 1) {
5404 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5405 << &AI << IdxExpr->getSourceRange();
5406 return false;
5407 }
5408 }
5409
5410 Idx = ParamIdx(IdxSource, D);
5411 return true;
5412 }
5413
5414 ///@}
5415
5416 //
5417 //
5418 // -------------------------------------------------------------------------
5419 //
5420 //
5421
5422 /// \name C++ Declarations
5423 /// Implementations are in SemaDeclCXX.cpp
5424 ///@{
5425
5426public:
5427 void CheckDelegatingCtorCycles();
5428
5429 /// Called before parsing a function declarator belonging to a function
5430 /// declaration.
5431 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5432 unsigned TemplateParameterDepth);
5433
5434 /// Called after parsing a function declarator belonging to a function
5435 /// declaration.
5436 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5437
5438 // Act on C++ namespaces
5439 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5440 SourceLocation NamespaceLoc,
5441 SourceLocation IdentLoc, IdentifierInfo *Ident,
5442 SourceLocation LBrace,
5443 const ParsedAttributesView &AttrList,
5444 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5445
5446 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5447 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5448 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5449
5450 NamespaceDecl *getStdNamespace() const;
5451
5452 /// Retrieve the special "std" namespace, which may require us to
5453 /// implicitly define the namespace.
5454 NamespaceDecl *getOrCreateStdNamespace();
5455
5456 CXXRecordDecl *getStdBadAlloc() const;
5457 EnumDecl *getStdAlignValT() const;
5458
5459 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5460 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5461 QualType AllocType, SourceLocation);
5462
5463 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5464 const IdentifierInfo *MemberOrBase);
5465
5466 enum class ComparisonCategoryUsage {
5467 /// The '<=>' operator was used in an expression and a builtin operator
5468 /// was selected.
5469 OperatorInExpression,
5470 /// A defaulted 'operator<=>' needed the comparison category. This
5471 /// typically only applies to 'std::strong_ordering', due to the implicit
5472 /// fallback return value.
5473 DefaultedOperator,
5474 /// A builtin needed 'std::strong_ordering' (eg. '__builtin_type_order').
5475 Builtin,
5476 };
5477
5478 /// Lookup the specified comparison category types in the standard
5479 /// library, an check the VarDecls possibly returned by the operator<=>
5480 /// builtins for that type.
5481 ///
5482 /// \return The type of the comparison category type corresponding to the
5483 /// specified Kind, or a null type if an error occurs
5484 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5485 SourceLocation Loc,
5486 ComparisonCategoryUsage Usage);
5487
5488 /// Tests whether Ty is an instance of std::initializer_list and, if
5489 /// it is and Element is not NULL, assigns the element type to Element.
5490 bool isStdInitializerList(QualType Ty, QualType *Element);
5491
5492 /// Tests whether Ty is an instance of std::type_identity and, if
5493 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5494 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5495 /// incorrectly structured despite having the correct name, the faulty Decl
5496 /// will be assigned to MalformedDecl.
5497 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5498 const Decl **MalformedDecl = nullptr);
5499
5500 /// Looks for the std::initializer_list template and instantiates it
5501 /// with Element, or emits an error if it's not found.
5502 ///
5503 /// \returns The instantiated template, or null on error.
5504 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5505
5506 /// Looks for the std::type_identity template and instantiates it
5507 /// with Type, or returns a null type if type_identity has not been declared
5508 ///
5509 /// \returns The instantiated template, or null if std::type_identity is not
5510 /// declared
5511 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5512
5513 /// Determine whether Ctor is an initializer-list constructor, as
5514 /// defined in [dcl.init.list]p2.
5515 bool isInitListConstructor(const FunctionDecl *Ctor);
5516
5517 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5518 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5519 SourceLocation IdentLoc,
5520 IdentifierInfo *NamespcName,
5521 const ParsedAttributesView &AttrList);
5522
5523 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5524
5525 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5526 SourceLocation AliasLoc, IdentifierInfo *Alias,
5527 CXXScopeSpec &SS, SourceLocation IdentLoc,
5528 IdentifierInfo *Ident);
5529
5530 /// Remove decls we can't actually see from a lookup being used to declare
5531 /// shadow using decls.
5532 ///
5533 /// \param S - The scope of the potential shadow decl
5534 /// \param Previous - The lookup of a potential shadow decl's name.
5535 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5536
5537 /// Hides a using shadow declaration. This is required by the current
5538 /// using-decl implementation when a resolvable using declaration in a
5539 /// class is followed by a declaration which would hide or override
5540 /// one or more of the using decl's targets; for example:
5541 ///
5542 /// struct Base { void foo(int); };
5543 /// struct Derived : Base {
5544 /// using Base::foo;
5545 /// void foo(int);
5546 /// };
5547 ///
5548 /// The governing language is C++03 [namespace.udecl]p12:
5549 ///
5550 /// When a using-declaration brings names from a base class into a
5551 /// derived class scope, member functions in the derived class
5552 /// override and/or hide member functions with the same name and
5553 /// parameter types in a base class (rather than conflicting).
5554 ///
5555 /// There are two ways to implement this:
5556 /// (1) optimistically create shadow decls when they're not hidden
5557 /// by existing declarations, or
5558 /// (2) don't create any shadow decls (or at least don't make them
5559 /// visible) until we've fully parsed/instantiated the class.
5560 /// The problem with (1) is that we might have to retroactively remove
5561 /// a shadow decl, which requires several O(n) operations because the
5562 /// decl structures are (very reasonably) not designed for removal.
5563 /// (2) avoids this but is very fiddly and phase-dependent.
5564 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5565
5566 /// Determines whether to create a using shadow decl for a particular
5567 /// decl, given the set of decls existing prior to this using lookup.
5568 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5569 const LookupResult &PreviousDecls,
5570 UsingShadowDecl *&PrevShadow);
5571
5572 /// Builds a shadow declaration corresponding to a 'using' declaration.
5573 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5574 NamedDecl *Target,
5575 UsingShadowDecl *PrevDecl);
5576
5577 /// Checks that the given using declaration is not an invalid
5578 /// redeclaration. Note that this is checking only for the using decl
5579 /// itself, not for any ill-formedness among the UsingShadowDecls.
5580 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5581 bool HasTypenameKeyword,
5582 const CXXScopeSpec &SS,
5583 SourceLocation NameLoc,
5584 const LookupResult &Previous);
5585
5586 /// Checks that the given nested-name qualifier used in a using decl
5587 /// in the current context is appropriately related to the current
5588 /// scope. If an error is found, diagnoses it and returns true.
5589 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5590 /// the result of that lookup. UD is likewise nullptr, except when we have an
5591 /// already-populated UsingDecl whose shadow decls contain the same
5592 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5593 /// scope).
5594 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5595 const CXXScopeSpec &SS,
5596 const DeclarationNameInfo &NameInfo,
5597 SourceLocation NameLoc,
5598 const LookupResult *R = nullptr,
5599 const UsingDecl *UD = nullptr);
5600
5601 /// Builds a using declaration.
5602 ///
5603 /// \param IsInstantiation - Whether this call arises from an
5604 /// instantiation of an unresolved using declaration. We treat
5605 /// the lookup differently for these declarations.
5606 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5607 SourceLocation UsingLoc,
5608 bool HasTypenameKeyword,
5609 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5610 DeclarationNameInfo NameInfo,
5611 SourceLocation EllipsisLoc,
5612 const ParsedAttributesView &AttrList,
5613 bool IsInstantiation, bool IsUsingIfExists);
5614 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5615 SourceLocation UsingLoc,
5616 SourceLocation EnumLoc,
5617 SourceLocation NameLoc,
5618 TypeSourceInfo *EnumType, EnumDecl *ED);
5619 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5620 ArrayRef<NamedDecl *> Expansions);
5621
5622 /// Additional checks for a using declaration referring to a constructor name.
5623 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5624
5625 /// Given a derived-class using shadow declaration for a constructor and the
5626 /// correspnding base class constructor, find or create the implicit
5627 /// synthesized derived class constructor to use for this initialization.
5628 CXXConstructorDecl *
5629 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5630 ConstructorUsingShadowDecl *DerivedShadow);
5631
5632 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5633 SourceLocation UsingLoc,
5634 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5635 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5636 const ParsedAttributesView &AttrList);
5637 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5638 SourceLocation UsingLoc,
5639 SourceLocation EnumLoc, SourceRange TyLoc,
5640 const IdentifierInfo &II, ParsedType Ty,
5641 const CXXScopeSpec &SS);
5642 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5643 MultiTemplateParamsArg TemplateParams,
5644 SourceLocation UsingLoc, UnqualifiedId &Name,
5645 const ParsedAttributesView &AttrList,
5646 TypeResult Type, Decl *DeclFromDeclSpec);
5647
5648 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5649 /// including handling of its default argument expressions.
5650 ///
5651 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5652 ExprResult BuildCXXConstructExpr(
5653 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5654 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5655 bool HadMultipleCandidates, bool IsListInitialization,
5656 bool IsStdInitListInitialization, bool RequiresZeroInit,
5657 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5658
5659 /// Build a CXXConstructExpr whose constructor has already been resolved if
5660 /// it denotes an inherited constructor.
5661 ExprResult BuildCXXConstructExpr(
5662 SourceLocation ConstructLoc, QualType DeclInitType,
5663 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5664 bool HadMultipleCandidates, bool IsListInitialization,
5665 bool IsStdInitListInitialization, bool RequiresZeroInit,
5666 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5667
5668 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5669 // the constructor can be elidable?
5670 ExprResult BuildCXXConstructExpr(
5671 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5672 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5673 bool HadMultipleCandidates, bool IsListInitialization,
5674 bool IsStdInitListInitialization, bool RequiresZeroInit,
5675 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5676
5677 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5678 SourceLocation InitLoc);
5679 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD,
5680 const InitializedEntity &Entity,
5681 Expr *InitExpr,
5682 SourceLocation InitLoc);
5683
5684 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5685 /// constructed variable.
5686 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5687
5688 /// Helper class that collects exception specifications for
5689 /// implicitly-declared special member functions.
5690 class ImplicitExceptionSpecification {
5691 // Pointer to allow copying
5692 Sema *Self;
5693 // We order exception specifications thus:
5694 // noexcept is the most restrictive, but is only used in C++11.
5695 // throw() comes next.
5696 // Then a throw(collected exceptions)
5697 // Finally no specification, which is expressed as noexcept(false).
5698 // throw(...) is used instead if any called function uses it.
5699 ExceptionSpecificationType ComputedEST;
5700 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5701 SmallVector<QualType, 4> Exceptions;
5702
5703 void ClearExceptions() {
5704 ExceptionsSeen.clear();
5705 Exceptions.clear();
5706 }
5707
5708 public:
5709 explicit ImplicitExceptionSpecification(Sema &Self)
5710 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5711 if (!Self.getLangOpts().CPlusPlus11)
5712 ComputedEST = EST_DynamicNone;
5713 }
5714
5715 /// Get the computed exception specification type.
5716 ExceptionSpecificationType getExceptionSpecType() const {
5717 assert(!isComputedNoexcept(ComputedEST) &&
5718 "noexcept(expr) should not be a possible result");
5719 return ComputedEST;
5720 }
5721
5722 /// The number of exceptions in the exception specification.
5723 unsigned size() const { return Exceptions.size(); }
5724
5725 /// The set of exceptions in the exception specification.
5726 const QualType *data() const { return Exceptions.data(); }
5727
5728 /// Integrate another called method into the collected data.
5729 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5730
5731 /// Integrate an invoked expression into the collected data.
5732 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5733
5734 /// Integrate an invoked statement into the collected data.
5735 void CalledStmt(Stmt *S);
5736
5737 /// Overwrite an EPI's exception specification with this
5738 /// computed exception specification.
5739 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5740 FunctionProtoType::ExceptionSpecInfo ESI;
5741 ESI.Type = getExceptionSpecType();
5742 if (ESI.Type == EST_Dynamic) {
5743 ESI.Exceptions = Exceptions;
5744 } else if (ESI.Type == EST_None) {
5745 /// C++11 [except.spec]p14:
5746 /// The exception-specification is noexcept(false) if the set of
5747 /// potential exceptions of the special member function contains "any"
5748 ESI.Type = EST_NoexceptFalse;
5749 ESI.NoexceptExpr =
5750 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5751 }
5752 return ESI;
5753 }
5754 };
5755
5756 /// Evaluate the implicit exception specification for a defaulted
5757 /// special member function.
5758 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5759
5760 /// Check the given exception-specification and update the
5761 /// exception specification information with the results.
5762 void checkExceptionSpecification(bool IsTopLevel,
5763 ExceptionSpecificationType EST,
5764 ArrayRef<ParsedType> DynamicExceptions,
5765 ArrayRef<SourceRange> DynamicExceptionRanges,
5766 Expr *NoexceptExpr,
5767 SmallVectorImpl<QualType> &Exceptions,
5768 FunctionProtoType::ExceptionSpecInfo &ESI);
5769
5770 /// Add an exception-specification to the given member or friend function
5771 /// (or function template). The exception-specification was parsed
5772 /// after the function itself was declared.
5773 void actOnDelayedExceptionSpecification(
5774 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5775 ArrayRef<ParsedType> DynamicExceptions,
5776 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5777
5778 class InheritedConstructorInfo;
5779
5780 /// Determine if a special member function should have a deleted
5781 /// definition when it is defaulted.
5782 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5783 InheritedConstructorInfo *ICI = nullptr,
5784 bool Diagnose = false);
5785
5786 /// Produce notes explaining why a defaulted function was defined as deleted.
5787 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5788
5789 /// Declare the implicit default constructor for the given class.
5790 ///
5791 /// \param ClassDecl The class declaration into which the implicit
5792 /// default constructor will be added.
5793 ///
5794 /// \returns The implicitly-declared default constructor.
5795 CXXConstructorDecl *
5796 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5797
5798 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5799 /// defining this constructor as the default constructor.
5800 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5801 CXXConstructorDecl *Constructor);
5802
5803 /// Declare the implicit destructor for the given class.
5804 ///
5805 /// \param ClassDecl The class declaration into which the implicit
5806 /// destructor will be added.
5807 ///
5808 /// \returns The implicitly-declared destructor.
5809 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5810
5811 /// DefineImplicitDestructor - Checks for feasibility of
5812 /// defining this destructor as the default destructor.
5813 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5814 CXXDestructorDecl *Destructor);
5815
5816 /// Build an exception spec for destructors that don't have one.
5817 ///
5818 /// C++11 says that user-defined destructors with no exception spec get one
5819 /// that looks as if the destructor was implicitly declared.
5820 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5821
5822 /// Define the specified inheriting constructor.
5823 void DefineInheritingConstructor(SourceLocation UseLoc,
5824 CXXConstructorDecl *Constructor);
5825
5826 /// Declare the implicit copy constructor for the given class.
5827 ///
5828 /// \param ClassDecl The class declaration into which the implicit
5829 /// copy constructor will be added.
5830 ///
5831 /// \returns The implicitly-declared copy constructor.
5832 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5833
5834 /// DefineImplicitCopyConstructor - Checks for feasibility of
5835 /// defining this constructor as the copy constructor.
5836 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5837 CXXConstructorDecl *Constructor);
5838
5839 /// Declare the implicit move constructor for the given class.
5840 ///
5841 /// \param ClassDecl The Class declaration into which the implicit
5842 /// move constructor will be added.
5843 ///
5844 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5845 /// declared.
5846 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5847
5848 /// DefineImplicitMoveConstructor - Checks for feasibility of
5849 /// defining this constructor as the move constructor.
5850 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5851 CXXConstructorDecl *Constructor);
5852
5853 /// Declare the implicit copy assignment operator for the given class.
5854 ///
5855 /// \param ClassDecl The class declaration into which the implicit
5856 /// copy assignment operator will be added.
5857 ///
5858 /// \returns The implicitly-declared copy assignment operator.
5859 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5860
5861 /// Defines an implicitly-declared copy assignment operator.
5862 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5863 CXXMethodDecl *MethodDecl);
5864
5865 /// Declare the implicit move assignment operator for the given class.
5866 ///
5867 /// \param ClassDecl The Class declaration into which the implicit
5868 /// move assignment operator will be added.
5869 ///
5870 /// \returns The implicitly-declared move assignment operator, or NULL if it
5871 /// wasn't declared.
5872 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5873
5874 /// Defines an implicitly-declared move assignment operator.
5875 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5876 CXXMethodDecl *MethodDecl);
5877
5878 /// Check a completed declaration of an implicit special member.
5879 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5880
5881 /// Determine whether the given function is an implicitly-deleted
5882 /// special member function.
5883 bool isImplicitlyDeleted(FunctionDecl *FD);
5884
5885 /// Check whether 'this' shows up in the type of a static member
5886 /// function after the (naturally empty) cv-qualifier-seq would be.
5887 ///
5888 /// \returns true if an error occurred.
5889 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5890
5891 /// Whether this' shows up in the exception specification of a static
5892 /// member function.
5893 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5894
5895 /// Check whether 'this' shows up in the attributes of the given
5896 /// static member function.
5897 ///
5898 /// \returns true if an error occurred.
5899 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5900
5901 bool CheckImmediateEscalatingFunctionDefinition(
5902 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5903
5904 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5905
5906 /// Given a constructor and the set of arguments provided for the
5907 /// constructor, convert the arguments and add any required default arguments
5908 /// to form a proper call to this constructor.
5909 ///
5910 /// \returns true if an error occurred, false otherwise.
5911 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5912 QualType DeclInitType, MultiExprArg ArgsPtr,
5913 SourceLocation Loc,
5914 SmallVectorImpl<Expr *> &ConvertedArgs,
5915 bool AllowExplicit = false,
5916 bool IsListInitialization = false);
5917
5918 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5919 /// initializer for the declaration 'Dcl'.
5920 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5921 /// static data member of class X, names should be looked up in the scope of
5922 /// class X.
5923 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5924
5925 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5926 /// initializer for the declaration 'Dcl'.
5927 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5928
5929 /// Define the "body" of the conversion from a lambda object to a
5930 /// function pointer.
5931 ///
5932 /// This routine doesn't actually define a sensible body; rather, it fills
5933 /// in the initialization expression needed to copy the lambda object into
5934 /// the block, and IR generation actually generates the real body of the
5935 /// block pointer conversion.
5936 void
5937 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5938 CXXConversionDecl *Conv);
5939
5940 /// Define the "body" of the conversion from a lambda object to a
5941 /// block pointer.
5942 ///
5943 /// This routine doesn't actually define a sensible body; rather, it fills
5944 /// in the initialization expression needed to copy the lambda object into
5945 /// the block, and IR generation actually generates the real body of the
5946 /// block pointer conversion.
5947 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5948 CXXConversionDecl *Conv);
5949
5950 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5951 /// linkage specification, including the language and (if present)
5952 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5953 /// language string literal. LBraceLoc, if valid, provides the location of
5954 /// the '{' brace. Otherwise, this linkage specification does not
5955 /// have any braces.
5956 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5957 Expr *LangStr, SourceLocation LBraceLoc);
5958
5959 /// ActOnFinishLinkageSpecification - Complete the definition of
5960 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5961 /// valid, it's the position of the closing '}' brace in a linkage
5962 /// specification that uses braces.
5963 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5964 SourceLocation RBraceLoc);
5965
5966 //===--------------------------------------------------------------------===//
5967 // C++ Classes
5968 //
5969
5970 /// Get the class that is directly named by the current context. This is the
5971 /// class for which an unqualified-id in this scope could name a constructor
5972 /// or destructor.
5973 ///
5974 /// If the scope specifier denotes a class, this will be that class.
5975 /// If the scope specifier is empty, this will be the class whose
5976 /// member-specification we are currently within. Otherwise, there
5977 /// is no such class.
5978 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5979
5980 /// isCurrentClassName - Determine whether the identifier II is the
5981 /// name of the class type currently being defined. In the case of
5982 /// nested classes, this will only return true if II is the name of
5983 /// the innermost class.
5984 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5985 const CXXScopeSpec *SS = nullptr);
5986
5987 /// Determine whether the identifier II is a typo for the name of
5988 /// the class type currently being defined. If so, update it to the identifier
5989 /// that should have been used.
5990 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5991
5992 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5993 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5994 SourceLocation ColonLoc,
5995 const ParsedAttributesView &Attrs);
5996
5997 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5998 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5999 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
6000 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
6001 /// present (but parsing it has been deferred).
6002 NamedDecl *
6003 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
6004 MultiTemplateParamsArg TemplateParameterLists,
6005 Expr *BitfieldWidth, const VirtSpecifiers &VS,
6006 InClassInitStyle InitStyle);
6007
6008 /// Enter a new C++ default initializer scope. After calling this, the
6009 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
6010 /// parsing or instantiating the initializer failed.
6011 void ActOnStartCXXInClassMemberInitializer();
6012
6013 /// This is invoked after parsing an in-class initializer for a
6014 /// non-static C++ class member, and after instantiating an in-class
6015 /// initializer in a class template. Such actions are deferred until the class
6016 /// is complete.
6017 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
6018 SourceLocation EqualLoc,
6019 ExprResult Init);
6020
6021 /// Handle a C++ member initializer using parentheses syntax.
6022 MemInitResult
6023 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
6024 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
6025 const DeclSpec &DS, SourceLocation IdLoc,
6026 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
6027 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
6028
6029 /// Handle a C++ member initializer using braced-init-list syntax.
6030 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
6031 CXXScopeSpec &SS,
6032 IdentifierInfo *MemberOrBase,
6033 ParsedType TemplateTypeTy,
6034 const DeclSpec &DS, SourceLocation IdLoc,
6035 Expr *InitList, SourceLocation EllipsisLoc);
6036
6037 /// Handle a C++ member initializer.
6038 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
6039 CXXScopeSpec &SS,
6040 IdentifierInfo *MemberOrBase,
6041 ParsedType TemplateTypeTy,
6042 const DeclSpec &DS, SourceLocation IdLoc,
6043 Expr *Init, SourceLocation EllipsisLoc);
6044
6045 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
6046 SourceLocation IdLoc);
6047
6048 MemInitResult BuildBaseInitializer(QualType BaseType,
6049 TypeSourceInfo *BaseTInfo, Expr *Init,
6050 CXXRecordDecl *ClassDecl,
6051 SourceLocation EllipsisLoc);
6052
6053 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
6054 CXXRecordDecl *ClassDecl);
6055
6056 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
6057 CXXCtorInitializer *Initializer);
6058
6059 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
6060 ArrayRef<CXXCtorInitializer *> Initializers = {});
6061
6062 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
6063 /// mark all the non-trivial destructors of its members and bases as
6064 /// referenced.
6065 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
6066 CXXRecordDecl *Record);
6067
6068 /// Mark destructors of virtual bases of this class referenced. In the Itanium
6069 /// C++ ABI, this is done when emitting a destructor for any non-abstract
6070 /// class. In the Microsoft C++ ABI, this is done any time a class's
6071 /// destructor is referenced.
6072 void MarkVirtualBaseDestructorsReferenced(
6073 SourceLocation Location, CXXRecordDecl *ClassDecl,
6074 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
6075 nullptr);
6076
6077 /// Do semantic checks to allow the complete destructor variant to be emitted
6078 /// when the destructor is defined in another translation unit. In the Itanium
6079 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
6080 /// can be emitted in separate TUs. To emit the complete variant, run a subset
6081 /// of the checks performed when emitting a regular destructor.
6082 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
6083 CXXDestructorDecl *Dtor);
6084
6085 /// The list of classes whose vtables have been used within
6086 /// this translation unit, and the source locations at which the
6087 /// first use occurred.
6088 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
6089
6090 /// The list of vtables that are required but have not yet been
6091 /// materialized.
6092 SmallVector<VTableUse, 16> VTableUses;
6093
6094 /// The set of classes whose vtables have been used within
6095 /// this translation unit, and a bit that will be true if the vtable is
6096 /// required to be emitted (otherwise, it should be emitted only if needed
6097 /// by code generation).
6098 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
6099
6100 /// Load any externally-stored vtable uses.
6101 void LoadExternalVTableUses();
6102
6103 /// Note that the vtable for the given class was used at the
6104 /// given location.
6105 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6106 bool DefinitionRequired = false);
6107
6108 /// Mark the exception specifications of all virtual member functions
6109 /// in the given class as needed.
6110 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
6111 const CXXRecordDecl *RD);
6112
6113 /// MarkVirtualMembersReferenced - Will mark all members of the given
6114 /// CXXRecordDecl referenced.
6115 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
6116 bool ConstexprOnly = false);
6117
6118 /// Define all of the vtables that have been used in this
6119 /// translation unit and reference any virtual members used by those
6120 /// vtables.
6121 ///
6122 /// \returns true if any work was done, false otherwise.
6123 bool DefineUsedVTables();
6124
6125 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6126 /// special functions, such as the default constructor, copy
6127 /// constructor, or destructor, to the given C++ class (C++
6128 /// [special]p1). This routine can only be executed just before the
6129 /// definition of the class is complete.
6130 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
6131
6132 /// ActOnMemInitializers - Handle the member initializers for a constructor.
6133 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
6134 ArrayRef<CXXCtorInitializer *> MemInits,
6135 bool AnyErrors);
6136
6137 /// Check class-level dllimport/dllexport attribute. The caller must
6138 /// ensure that referenceDLLExportedClassMethods is called some point later
6139 /// when all outer classes of Class are complete.
6140 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
6141 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
6142
6143 void referenceDLLExportedClassMethods();
6144
6145 /// Perform propagation of DLL attributes from a derived class to a
6146 /// templated base class for MS compatibility.
6147 void propagateDLLAttrToBaseClassTemplate(
6148 CXXRecordDecl *Class, Attr *ClassAttr,
6149 ClassTemplateSpecializationDecl *BaseTemplateSpec,
6150 SourceLocation BaseLoc);
6151
6152 /// Perform semantic checks on a class definition that has been
6153 /// completing, introducing implicitly-declared members, checking for
6154 /// abstract types, etc.
6155 ///
6156 /// \param S The scope in which the class was parsed. Null if we didn't just
6157 /// parse a class definition.
6158 /// \param Record The completed class.
6159 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6160
6161 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6162 /// conditions that are needed for the attribute to have an effect.
6163 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6164
6165 /// Check that VTable Pointer authentication is only being set on the first
6166 /// first instantiation of the vtable
6167 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6168
6169 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6170 Decl *TagDecl, SourceLocation LBrac,
6171 SourceLocation RBrac,
6172 const ParsedAttributesView &AttrList);
6173
6174 /// Perform any semantic analysis which needs to be delayed until all
6175 /// pending class member declarations have been parsed.
6176 void ActOnFinishCXXMemberDecls();
6177 void ActOnFinishCXXNonNestedClass();
6178
6179 /// This is used to implement the constant expression evaluation part of the
6180 /// attribute enable_if extension. There is nothing in standard C++ which
6181 /// would require reentering parameters.
6182 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6183 unsigned ActOnReenterTemplateScope(Decl *Template,
6184 llvm::function_ref<Scope *()> EnterScope);
6185 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6186
6187 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6188 /// parsing a top-level (non-nested) C++ class, and we are now
6189 /// parsing those parts of the given Method declaration that could
6190 /// not be parsed earlier (C++ [class.mem]p2), such as default
6191 /// arguments. This action should enter the scope of the given
6192 /// Method declaration as if we had just parsed the qualified method
6193 /// name. However, it should not bring the parameters into scope;
6194 /// that will be performed by ActOnDelayedCXXMethodParameter.
6195 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6196 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6197 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6198
6199 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6200 /// processing the delayed method declaration for Method. The method
6201 /// declaration is now considered finished. There may be a separate
6202 /// ActOnStartOfFunctionDef action later (not necessarily
6203 /// immediately!) for this method, if it was also defined inside the
6204 /// class body.
6205 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6206 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6207
6208 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6209
6210 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6211 StringEvaluationContext EvalContext,
6212 bool ErrorOnInvalidMessage);
6213 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6214 StringEvaluationContext EvalContext,
6215 bool ErrorOnInvalidMessage);
6216
6217 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6218 Expr *AssertExpr, Expr *AssertMessageExpr,
6219 SourceLocation RParenLoc);
6220 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6221 Expr *AssertExpr, Expr *AssertMessageExpr,
6222 SourceLocation RParenLoc, bool Failed);
6223
6224 /// Try to print more useful information about a failed static_assert
6225 /// with expression \E
6226 void DiagnoseStaticAssertDetails(const Expr *E);
6227
6228 /// If E represents a built-in type trait, or a known standard type trait,
6229 /// try to print more information about why the type type-trait failed.
6230 /// This assumes we already evaluated the expression to a false boolean value.
6231 void DiagnoseTypeTraitDetails(const Expr *E);
6232
6233 /// Handle a friend type declaration. This works in tandem with
6234 /// ActOnTag.
6235 ///
6236 /// Notes on friend class templates:
6237 ///
6238 /// We generally treat friend class declarations as if they were
6239 /// declaring a class. So, for example, the elaborated type specifier
6240 /// in a friend declaration is required to obey the restrictions of a
6241 /// class-head (i.e. no typedefs in the scope chain), template
6242 /// parameters are required to match up with simple template-ids, &c.
6243 /// However, unlike when declaring a template specialization, it's
6244 /// okay to refer to a template specialization without an empty
6245 /// template parameter declaration, e.g.
6246 /// friend class A<T>::B<unsigned>;
6247 /// We permit this as a special case; if there are any template
6248 /// parameters present at all, require proper matching, i.e.
6249 /// template <> template \<class T> friend class A<int>::B;
6250 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6251 MultiTemplateParamsArg TemplateParams,
6252 SourceLocation EllipsisLoc);
6253 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6254 MultiTemplateParamsArg TemplateParams);
6255
6256 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6257 /// the well-formedness of the constructor declarator @p D with type @p
6258 /// R. If there are any errors in the declarator, this routine will
6259 /// emit diagnostics and set the invalid bit to true. In any case, the type
6260 /// will be updated to reflect a well-formed type for the constructor and
6261 /// returned.
6262 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6263 StorageClass &SC);
6264
6265 /// CheckConstructor - Checks a fully-formed constructor for
6266 /// well-formedness, issuing any diagnostics required. Returns true if
6267 /// the constructor declarator is invalid.
6268 void CheckConstructor(CXXConstructorDecl *Constructor);
6269
6270 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6271 /// the well-formednes of the destructor declarator @p D with type @p
6272 /// R. If there are any errors in the declarator, this routine will
6273 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6274 /// will be updated to reflect a well-formed type for the destructor and
6275 /// returned.
6276 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6277 StorageClass &SC);
6278
6279 /// CheckDestructor - Checks a fully-formed destructor definition for
6280 /// well-formedness, issuing any diagnostics required. Returns true
6281 /// on error.
6282 bool CheckDestructor(CXXDestructorDecl *Destructor);
6283
6284 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6285 /// well-formednes of the conversion function declarator @p D with
6286 /// type @p R. If there are any errors in the declarator, this routine
6287 /// will emit diagnostics and return true. Otherwise, it will return
6288 /// false. Either way, the type @p R will be updated to reflect a
6289 /// well-formed type for the conversion operator.
6290 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6291
6292 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6293 /// the declaration of the given C++ conversion function. This routine
6294 /// is responsible for recording the conversion function in the C++
6295 /// class, if possible.
6296 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6297
6298 /// Check the validity of a declarator that we parsed for a deduction-guide.
6299 /// These aren't actually declarators in the grammar, so we need to check that
6300 /// the user didn't specify any pieces that are not part of the
6301 /// deduction-guide grammar. Return true on invalid deduction-guide.
6302 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6303 StorageClass &SC);
6304
6305 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6306
6307 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6308 CXXSpecialMemberKind CSM,
6309 SourceLocation DefaultLoc);
6310 void CheckDelayedMemberExceptionSpecs();
6311
6312 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6313 DefaultedComparisonKind DCK);
6314 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6315 FunctionDecl *Spaceship);
6316 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6317 DefaultedComparisonKind DCK);
6318
6319 /// Check a defaulted postfix increment or decrement operator function
6320 /// (C++2d [over.inc.default]), defining it as deleted if necessary.
6321 ///
6322 /// \param S The scope in which the function is defaulted, used to perform
6323 /// the unqualified name lookups needed by the implicit definition, or
6324 /// \c nullptr if those lookups have already been performed.
6325 ///
6326 /// \returns \c true if the function is ill-formed.
6327 bool CheckExplicitlyDefaultedPostfixOperator(Scope *S, FunctionDecl *FD,
6328 PostfixOperatorKind Kind);
6329 /// Synthesize the body of a defaulted postfix increment or decrement
6330 /// operator function (C++2d [over.inc.default]p3).
6331 void DefineDefaultedPostfixOperator(SourceLocation Loc, FunctionDecl *FD,
6332 PostfixOperatorKind Kind);
6333
6334 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6335 QualType R, bool IsLambda,
6336 DeclContext *DC = nullptr);
6337 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6338 DeclarationName Name, QualType R);
6339 void CheckExplicitObjectLambda(Declarator &D);
6340
6341 //===--------------------------------------------------------------------===//
6342 // C++ Derived Classes
6343 //
6344
6345 /// Check the validity of a C++ base class specifier.
6346 ///
6347 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6348 /// and returns NULL otherwise.
6349 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6350 SourceRange SpecifierRange, bool Virtual,
6351 AccessSpecifier Access,
6352 TypeSourceInfo *TInfo,
6353 SourceLocation EllipsisLoc);
6354
6355 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6356 /// one entry in the base class list of a class specifier, for
6357 /// example:
6358 /// class foo : public bar, virtual private baz {
6359 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6360 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6361 const ParsedAttributesView &Attrs, bool Virtual,
6362 AccessSpecifier Access, ParsedType basetype,
6363 SourceLocation BaseLoc,
6364 SourceLocation EllipsisLoc);
6365
6366 /// Performs the actual work of attaching the given base class
6367 /// specifiers to a C++ class.
6368 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6369 MutableArrayRef<CXXBaseSpecifier *> Bases);
6370
6371 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6372 /// class, after checking whether there are any duplicate base
6373 /// classes.
6374 void ActOnBaseSpecifiers(Decl *ClassDecl,
6375 MutableArrayRef<CXXBaseSpecifier *> Bases);
6376
6377 /// Determine whether the type \p Derived is a C++ class that is
6378 /// derived from the type \p Base.
6379 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6380 CXXRecordDecl *Base, CXXBasePaths &Paths);
6381 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6382 CXXRecordDecl *Base);
6383 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6384 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6385 CXXBasePaths &Paths);
6386
6387 // FIXME: I don't like this name.
6388 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6389
6390 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6391 SourceLocation Loc, SourceRange Range,
6392 CXXCastPath *BasePath = nullptr,
6393 bool IgnoreAccess = false);
6394
6395 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6396 /// conversion (where Derived and Base are class types) is
6397 /// well-formed, meaning that the conversion is unambiguous (and
6398 /// that all of the base classes are accessible). Returns true
6399 /// and emits a diagnostic if the code is ill-formed, returns false
6400 /// otherwise. Loc is the location where this routine should point to
6401 /// if there is an error, and Range is the source range to highlight
6402 /// if there is an error.
6403 ///
6404 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6405 /// diagnostic for the respective type of error will be suppressed, but the
6406 /// check for ill-formed code will still be performed.
6407 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6408 unsigned InaccessibleBaseID,
6409 unsigned AmbiguousBaseConvID,
6410 SourceLocation Loc, SourceRange Range,
6411 DeclarationName Name, CXXCastPath *BasePath,
6412 bool IgnoreAccess = false);
6413
6414 /// Builds a string representing ambiguous paths from a
6415 /// specific derived class to different subobjects of the same base
6416 /// class.
6417 ///
6418 /// This function builds a string that can be used in error messages
6419 /// to show the different paths that one can take through the
6420 /// inheritance hierarchy to go from the derived class to different
6421 /// subobjects of a base class. The result looks something like this:
6422 /// @code
6423 /// struct D -> struct B -> struct A
6424 /// struct D -> struct C -> struct A
6425 /// @endcode
6426 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6427
6428 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6429 const CXXMethodDecl *Old);
6430
6431 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6432 /// covariant, according to C++ [class.virtual]p5.
6433 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6434 const CXXMethodDecl *Old);
6435
6436 // Check that the overriding method has no explicit object parameter.
6437 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6438 const CXXMethodDecl *Old);
6439
6440 /// Mark the given method pure.
6441 ///
6442 /// \param Method the method to be marked pure.
6443 ///
6444 /// \param InitRange the source range that covers the "0" initializer.
6445 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6446
6447 /// CheckOverrideControl - Check C++11 override control semantics.
6448 void CheckOverrideControl(NamedDecl *D);
6449
6450 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6451 /// not used in the declaration of an overriding method.
6452 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6453
6454 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6455 /// function overrides a virtual member function marked 'final', according to
6456 /// C++11 [class.virtual]p4.
6457 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6458 const CXXMethodDecl *Old);
6459
6460 enum AbstractDiagSelID {
6461 AbstractNone = -1,
6462 AbstractReturnType,
6463 AbstractParamType,
6464 AbstractVariableType,
6465 AbstractFieldType,
6466 AbstractIvarType,
6467 AbstractSynthesizedIvarType,
6468 AbstractArrayType
6469 };
6470
6471 struct TypeDiagnoser;
6472
6473 bool isAbstractType(SourceLocation Loc, QualType T);
6474 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6475 TypeDiagnoser &Diagnoser);
6476 template <typename... Ts>
6477 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6478 const Ts &...Args) {
6479 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6480 return RequireNonAbstractType(Loc, T, Diagnoser);
6481 }
6482
6483 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6484
6485 //===--------------------------------------------------------------------===//
6486 // C++ Overloaded Operators [C++ 13.5]
6487 //
6488
6489 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6490 /// of this overloaded operator is well-formed. If so, returns false;
6491 /// otherwise, emits appropriate diagnostics and returns true.
6492 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6493
6494 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6495 /// of this literal operator function is well-formed. If so, returns
6496 /// false; otherwise, emits appropriate diagnostics and returns true.
6497 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6498
6499 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6500 /// found in an explicit(bool) specifier.
6501 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6502
6503 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6504 /// Returns true if the explicit specifier is now resolved.
6505 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6506
6507 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6508 /// C++ if/switch/while/for statement.
6509 /// e.g: "if (int x = f()) {...}"
6510 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6511
6512 // Emitting members of dllexported classes is delayed until the class
6513 // (including field initializers) is fully parsed.
6514 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6515 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6516
6517 /// Merge the exception specifications of two variable declarations.
6518 ///
6519 /// This is called when there's a redeclaration of a VarDecl. The function
6520 /// checks if the redeclaration might have an exception specification and
6521 /// validates compatibility and merges the specs if necessary.
6522 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6523
6524 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6525 /// function, once we already know that they have the same
6526 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6527 /// error, false otherwise.
6528 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6529
6530 /// Helpers for dealing with blocks and functions.
6531 void CheckCXXDefaultArguments(FunctionDecl *FD);
6532
6533 /// CheckExtraCXXDefaultArguments - Check for any extra default
6534 /// arguments in the declarator, which is not a function declaration
6535 /// or definition and therefore is not permitted to have default
6536 /// arguments. This routine should be invoked for every declarator
6537 /// that is not a function declaration or definition.
6538 void CheckExtraCXXDefaultArguments(Declarator &D);
6539
6540 /// Perform semantic analysis for the variable declaration that
6541 /// occurs within a C++ catch clause, returning the newly-created
6542 /// variable.
6543 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6544 SourceLocation StartLoc,
6545 SourceLocation IdLoc,
6546 const IdentifierInfo *Id);
6547
6548 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6549 /// handler.
6550 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6551
6552 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6553
6554 /// Handle a friend tag declaration where the scope specifier was
6555 /// templated.
6556 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6557 unsigned TagSpec, SourceLocation TagLoc,
6558 CXXScopeSpec &SS, IdentifierInfo *Name,
6559 SourceLocation NameLoc,
6560 SourceLocation EllipsisLoc,
6561 const ParsedAttributesView &Attr,
6562 MultiTemplateParamsArg TempParamLists,
6563 TemplateIdAnnotation *TemplateId);
6564
6565 bool CheckDependentFriend(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc,
6566 ArrayRef<TemplateParameterList *> TPLs,
6567 bool IsInstantiation);
6568
6569 bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
6570 NestedNameSpecifierLoc NNSLoc);
6571
6572 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6573 SourceLocation DeclStart, Declarator &D,
6574 Expr *BitfieldWidth,
6575 InClassInitStyle InitStyle,
6576 AccessSpecifier AS,
6577 const ParsedAttr &MSPropertyAttr);
6578
6579 /// Diagnose why the specified class does not have a trivial special member of
6580 /// the given kind.
6581 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6582 CXXSpecialMemberKind CSM);
6583
6584 /// Determine whether a defaulted or deleted special member function is
6585 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6586 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6587 bool SpecialMemberIsTrivial(
6588 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6589 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6590 bool Diagnose = false);
6591
6592 /// Handle a C++11 empty-declaration and attribute-declaration.
6593 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6594 SourceLocation SemiLoc);
6595
6596 enum class CheckConstexprKind {
6597 /// Diagnose issues that are non-constant or that are extensions.
6598 Diagnose,
6599 /// Identify whether this function satisfies the formal rules for constexpr
6600 /// functions in the current lanugage mode (with no extensions).
6601 CheckValid
6602 };
6603
6604 // Check whether a function declaration satisfies the requirements of a
6605 // constexpr function definition or a constexpr constructor definition. If so,
6606 // return true. If not, produce appropriate diagnostics (unless asked not to
6607 // by Kind) and return false.
6608 //
6609 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6610 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6611 CheckConstexprKind Kind);
6612
6613 /// Diagnose methods which overload virtual methods in a base class
6614 /// without overriding any.
6615 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6616
6617 /// Check if a method overloads virtual methods in a base class without
6618 /// overriding any.
6619 void
6620 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6621 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6622 void
6623 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6624 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6625
6626 /// ActOnParamDefaultArgument - Check whether the default argument
6627 /// provided for a function parameter is well-formed. If so, attach it
6628 /// to the parameter declaration.
6629 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6630 Expr *defarg);
6631
6632 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6633 /// argument for a function parameter, but we can't parse it yet
6634 /// because we're inside a class definition. Note that this default
6635 /// argument will be parsed later.
6636 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6637 SourceLocation ArgLoc);
6638
6639 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6640 /// the default argument for the parameter param failed.
6641 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6642 Expr *DefaultArg);
6643 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6644 SourceLocation EqualLoc);
6645 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6646 SourceLocation EqualLoc);
6647
6648 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6649 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6650 StringLiteral *Message = nullptr);
6651 /// Mark the given declaration as explicitly defaulted.
6652 ///
6653 /// \param S The scope in which the function is defaulted, if it is
6654 /// available. It is used to perform the unqualified name lookups needed by
6655 /// the implicit definition of an out-of-class defaulted function.
6656 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc,
6657 Scope *S = nullptr);
6658
6659 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6660 StringLiteral *DeletedMessage = nullptr,
6661 Scope *S = nullptr);
6662 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6663 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6664 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6665
6666 NamedDecl *
6667 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6668 MultiTemplateParamsArg TemplateParamLists);
6669 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6670 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6671 RecordDecl *ClassDecl,
6672 const IdentifierInfo *Name);
6673
6674 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6675 SourceLocation Loc);
6676 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6677
6678 /// Stack containing information needed when in C++2a an 'auto' is encountered
6679 /// in a function declaration parameter type specifier in order to invent a
6680 /// corresponding template parameter in the enclosing abbreviated function
6681 /// template. This information is also present in LambdaScopeInfo, stored in
6682 /// the FunctionScopes stack.
6683 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6684
6685 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6686 std::unique_ptr<CXXFieldCollector> FieldCollector;
6687
6688 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6689 /// Set containing all declared private fields that are not used.
6690 NamedDeclSetType UnusedPrivateFields;
6691
6692 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6693
6694 /// PureVirtualClassDiagSet - a set of class declarations which we have
6695 /// emitted a list of pure virtual functions. Used to prevent emitting the
6696 /// same list more than once.
6697 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6698
6699 typedef LazyVector<CXXConstructorDecl *,
6700 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6701 DelegatingCtorDeclsType;
6702
6703 /// All the delegating constructors seen so far in the file, used for
6704 /// cycle detection at the end of the TU.
6705 DelegatingCtorDeclsType DelegatingCtorDecls;
6706
6707 /// The C++ "std" namespace, where the standard library resides.
6708 LazyDeclPtr StdNamespace;
6709
6710 /// The C++ "std::initializer_list" template, which is defined in
6711 /// \<initializer_list>.
6712 ClassTemplateDecl *StdInitializerList;
6713
6714 /// The C++ "std::type_identity" template, which is defined in
6715 /// \<type_traits>.
6716 ClassTemplateDecl *StdTypeIdentity;
6717
6718 // Contains the locations of the beginning of unparsed default
6719 // argument locations.
6720 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6721
6722 /// UndefinedInternals - all the used, undefined objects which require a
6723 /// definition in this translation unit.
6724 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6725
6726 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6727 SpecialMemberDecl;
6728
6729 /// The C++ special members which we are currently in the process of
6730 /// declaring. If this process recursively triggers the declaration of the
6731 /// same special member, we should act as if it is not yet declared.
6732 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6733
6734 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6735
6736 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6737
6738 typedef ProcessingContextState ParsingClassState;
6739 ParsingClassState PushParsingClass() {
6740 ParsingClassDepth++;
6741 return DelayedDiagnostics.pushUndelayed();
6742 }
6743 void PopParsingClass(ParsingClassState state) {
6744 ParsingClassDepth--;
6745 DelayedDiagnostics.popUndelayed(state);
6746 }
6747
6748 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6749 CXXScopeSpec &SS,
6750 ParsedType TemplateTypeTy,
6751 IdentifierInfo *MemberOrBase);
6752
6753private:
6754 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6755 QualType ResultTy,
6756 ArrayRef<QualType> Args);
6757 // Helper for ActOnFields to check for all function pointer members.
6758 bool EntirelyFunctionPointers(const RecordDecl *Record);
6759
6760 // A cache representing if we've fully checked the various comparison category
6761 // types stored in ASTContext. The bit-index corresponds to the integer value
6762 // of a ComparisonCategoryType enumerator.
6763 llvm::SmallBitVector FullyCheckedComparisonCategories;
6764
6765 /// Check if there is a field shadowing.
6766 void CheckShadowInheritedFields(const SourceLocation &Loc,
6767 DeclarationName FieldName,
6768 const CXXRecordDecl *RD,
6769 bool DeclIsField = true);
6770
6771 ///@}
6772
6773 //
6774 //
6775 // -------------------------------------------------------------------------
6776 //
6777 //
6778
6779 /// \name C++ Exception Specifications
6780 /// Implementations are in SemaExceptionSpec.cpp
6781 ///@{
6782
6783public:
6784 /// All the overriding functions seen during a class definition
6785 /// that had their exception spec checks delayed, plus the overridden
6786 /// function.
6787 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6788 DelayedOverridingExceptionSpecChecks;
6789
6790 /// All the function redeclarations seen during a class definition that had
6791 /// their exception spec checks delayed, plus the prior declaration they
6792 /// should be checked against. Except during error recovery, the new decl
6793 /// should always be a friend declaration, as that's the only valid way to
6794 /// redeclare a special member before its class is complete.
6795 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6796 DelayedEquivalentExceptionSpecChecks;
6797
6798 /// Determine if we're in a case where we need to (incorrectly) eagerly
6799 /// parse an exception specification to work around a libstdc++ bug.
6800 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6801
6802 /// Check the given noexcept-specifier, convert its expression, and compute
6803 /// the appropriate ExceptionSpecificationType.
6804 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6805 ExceptionSpecificationType &EST);
6806
6807 CanThrowResult canThrow(const Stmt *E);
6808 /// Determine whether the callee of a particular function call can throw.
6809 /// E, D and Loc are all optional.
6810 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6811 SourceLocation Loc = SourceLocation());
6812 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6813 const FunctionProtoType *FPT);
6814 void UpdateExceptionSpec(FunctionDecl *FD,
6815 const FunctionProtoType::ExceptionSpecInfo &ESI);
6816
6817 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6818 /// exception specification. Incomplete types, or pointers to incomplete types
6819 /// other than void are not allowed.
6820 ///
6821 /// \param[in,out] T The exception type. This will be decayed to a pointer
6822 /// type
6823 /// when the input is an array or a function type.
6824 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6825
6826 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6827 /// pointer to member to a function with an exception specification. This
6828 /// means that it is invalid to add another level of indirection.
6829 bool CheckDistantExceptionSpec(QualType T);
6830 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6831
6832 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6833 /// exception specifications. Exception specifications are equivalent if
6834 /// they allow exactly the same set of exception types. It does not matter how
6835 /// that is achieved. See C++ [except.spec]p2.
6836 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6837 SourceLocation OldLoc,
6838 const FunctionProtoType *New,
6839 SourceLocation NewLoc);
6840 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6841 const PartialDiagnostic &NoteID,
6842 const FunctionProtoType *Old,
6843 SourceLocation OldLoc,
6844 const FunctionProtoType *New,
6845 SourceLocation NewLoc);
6846 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6847
6848 /// CheckExceptionSpecSubset - Check whether the second function type's
6849 /// exception specification is a subset (or equivalent) of the first function
6850 /// type. This is used by override and pointer assignment checks.
6851 bool CheckExceptionSpecSubset(
6852 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6853 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6854 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6855 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6856 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6857
6858 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6859 /// two functions have equivalent exception specs. This is part of the
6860 /// assignment and override compatibility check. We do not check the
6861 /// parameters of parameter function pointers recursively, as no sane
6862 /// programmer would even be able to write such a function type.
6863 bool CheckParamExceptionSpec(
6864 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6865 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6866 SourceLocation TargetLoc, const FunctionProtoType *Source,
6867 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6868
6869 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6870
6871 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6872 /// spec is a subset of base spec.
6873 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6874 const CXXMethodDecl *Old);
6875
6876 ///@}
6877
6878 //
6879 //
6880 // -------------------------------------------------------------------------
6881 //
6882 //
6883
6884 /// \name Expressions
6885 /// Implementations are in SemaExpr.cpp
6886 ///@{
6887
6888public:
6889 /// Describes how the expressions currently being parsed are
6890 /// evaluated at run-time, if at all.
6891 enum class ExpressionEvaluationContext {
6892 /// The current expression and its subexpressions occur within an
6893 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6894 /// \c sizeof, where the type of the expression may be significant but
6895 /// no code will be generated to evaluate the value of the expression at
6896 /// run time.
6897 Unevaluated,
6898
6899 /// The current expression occurs within a braced-init-list within
6900 /// an unevaluated operand. This is mostly like a regular unevaluated
6901 /// context, except that we still instantiate constexpr functions that are
6902 /// referenced here so that we can perform narrowing checks correctly.
6903 UnevaluatedList,
6904
6905 /// The current expression occurs within a discarded statement.
6906 /// This behaves largely similarly to an unevaluated operand in preventing
6907 /// definitions from being required, but not in other ways.
6908 DiscardedStatement,
6909
6910 /// The current expression occurs within an unevaluated
6911 /// operand that unconditionally permits abstract references to
6912 /// fields, such as a SIZE operator in MS-style inline assembly.
6913 UnevaluatedAbstract,
6914
6915 /// The current context is "potentially evaluated" in C++11 terms,
6916 /// but the expression is evaluated at compile-time (like the values of
6917 /// cases in a switch statement).
6918 ConstantEvaluated,
6919
6920 /// In addition of being constant evaluated, the current expression
6921 /// occurs in an immediate function context - either a consteval function
6922 /// or a consteval if statement.
6923 ImmediateFunctionContext,
6924
6925 /// The current expression is potentially evaluated at run time,
6926 /// which means that code may be generated to evaluate the value of the
6927 /// expression at run time.
6928 PotentiallyEvaluated,
6929
6930 /// The current expression is potentially evaluated, but any
6931 /// declarations referenced inside that expression are only used if
6932 /// in fact the current expression is used.
6933 ///
6934 /// This value is used when parsing default function arguments, for which
6935 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6936 /// through varargs) but do not want to mark declarations as "referenced"
6937 /// until the default argument is used.
6938 PotentiallyEvaluatedIfUsed
6939 };
6940
6941 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6942 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6943 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6944 /// have been applied to all subexpressions of the enclosing full expression.
6945 /// This is cleared at the end of each full expression.
6946 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6947 MaybeODRUseExprSet MaybeODRUseExprs;
6948
6949 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6950
6951 /// Data structure used to record current or nested
6952 /// expression evaluation contexts.
6953 struct ExpressionEvaluationContextRecord {
6954 /// The expression evaluation context.
6955 ExpressionEvaluationContext Context;
6956
6957 /// Whether the enclosing context needed a cleanup.
6958 CleanupInfo ParentCleanup;
6959
6960 /// The number of active cleanup objects when we entered
6961 /// this expression evaluation context.
6962 unsigned NumCleanupObjects;
6963
6964 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6965
6966 /// The lambdas that are present within this context, if it
6967 /// is indeed an unevaluated context.
6968 SmallVector<LambdaExpr *, 2> Lambdas;
6969
6970 /// The declaration that provides context for lambda expressions
6971 /// and block literals if the normal declaration context does not
6972 /// suffice, e.g., in a default function argument.
6973 Decl *ManglingContextDecl;
6974
6975 /// Declaration for initializer if one is currently being
6976 /// parsed. Used when an expression has a possibly unreachable
6977 /// diagnostic to reference the declaration as a whole.
6978 VarDecl *DeclForInitializer = nullptr;
6979
6980 /// If we are processing a decltype type, a set of call expressions
6981 /// for which we have deferred checking the completeness of the return type.
6982 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6983
6984 /// If we are processing a decltype type, a set of temporary binding
6985 /// expressions for which we have deferred checking the destructor.
6986 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6987
6988 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6989
6990 /// Expressions appearing as the LHS of a volatile assignment in this
6991 /// context. We produce a warning for these when popping the context if
6992 /// they are not discarded-value expressions nor unevaluated operands.
6993 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6994
6995 /// Set of candidates for starting an immediate invocation.
6996 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6997 ImmediateInvocationCandidates;
6998
6999 /// Set of DeclRefExprs referencing a consteval function when used in a
7000 /// context not already known to be immediately invoked.
7001 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
7002
7003 /// P2718R0 - Lifetime extension in range-based for loops.
7004 /// MaterializeTemporaryExprs in for-range-init expressions which need to
7005 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
7006 /// InLifetimeExtendingContext is true.
7007 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
7008
7009 /// Small set of gathered accesses to potentially misaligned members
7010 /// due to the packed attribute.
7011 SmallVector<MisalignedMember, 4> MisalignedMembers;
7012
7013 /// \brief Describes whether we are in an expression constext which we have
7014 /// to handle differently.
7015 enum ExpressionKind {
7016 EK_Decltype,
7017 EK_TemplateArgument,
7018 EK_AttrArgument,
7019 EK_VariableInit,
7020 EK_Other
7021 } ExprContext;
7022
7023 // A context can be nested in both a discarded statement context and
7024 // an immediate function context, so they need to be tracked independently.
7025 bool InDiscardedStatement;
7026 bool InImmediateFunctionContext;
7027 bool InImmediateEscalatingFunctionContext;
7028
7029 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
7030
7031 // We are in a constant context, but we also allow
7032 // non constant expressions, for example for array bounds (which may be
7033 // VLAs).
7034 bool InConditionallyConstantEvaluateContext = false;
7035
7036 /// Whether we are currently in a context in which all temporaries must be
7037 /// lifetime-extended, even if they're not bound to a reference (for
7038 /// example, in a for-range initializer).
7039 bool InLifetimeExtendingContext = false;
7040
7041 /// Whether evaluating an expression for a switch case label.
7042 bool IsCaseExpr = false;
7043
7044 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
7045 bool RebuildDefaultArgOrDefaultInit = false;
7046
7047 // When evaluating immediate functions in the initializer of a default
7048 // argument or default member initializer, this is the declaration whose
7049 // default initializer is being evaluated and the location of the call
7050 // or constructor definition.
7051 struct InitializationContext {
7052 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
7053 DeclContext *Context)
7054 : Loc(Loc), Decl(Decl), Context(Context) {
7055 assert(Decl && Context && "invalid initialization context");
7056 }
7057
7058 SourceLocation Loc;
7059 ValueDecl *Decl = nullptr;
7060 DeclContext *Context = nullptr;
7061 };
7062 std::optional<InitializationContext> DelayedDefaultInitializationContext;
7063
7064 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
7065 unsigned NumCleanupObjects,
7066 CleanupInfo ParentCleanup,
7067 Decl *ManglingContextDecl,
7068 ExpressionKind ExprContext)
7069 : Context(Context), ParentCleanup(ParentCleanup),
7070 NumCleanupObjects(NumCleanupObjects),
7071 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
7072 InDiscardedStatement(false), InImmediateFunctionContext(false),
7073 InImmediateEscalatingFunctionContext(false) {}
7074
7075 bool isUnevaluated() const {
7076 return Context == ExpressionEvaluationContext::Unevaluated ||
7077 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
7078 Context == ExpressionEvaluationContext::UnevaluatedList;
7079 }
7080
7081 bool isPotentiallyEvaluated() const {
7082 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
7083 Context ==
7084 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
7085 Context == ExpressionEvaluationContext::ConstantEvaluated;
7086 }
7087
7088 bool isConstantEvaluated() const {
7089 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
7090 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
7091 }
7092
7093 bool isImmediateFunctionContext() const {
7094 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
7095 (Context == ExpressionEvaluationContext::DiscardedStatement &&
7096 InImmediateFunctionContext) ||
7097 // C++23 [expr.const]p14:
7098 // An expression or conversion is in an immediate function
7099 // context if it is potentially evaluated and either:
7100 // * its innermost enclosing non-block scope is a function
7101 // parameter scope of an immediate function, or
7102 // * its enclosing statement is enclosed by the compound-
7103 // statement of a consteval if statement.
7104 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
7105 InImmediateFunctionContext);
7106 }
7107
7108 bool isDiscardedStatementContext() const {
7109 return Context == ExpressionEvaluationContext::DiscardedStatement ||
7110 ((Context ==
7111 ExpressionEvaluationContext::ImmediateFunctionContext ||
7112 isPotentiallyEvaluated()) &&
7113 InDiscardedStatement);
7114 }
7115 };
7116
7117 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
7118 assert(!ExprEvalContexts.empty() &&
7119 "Must be in an expression evaluation context");
7120 return ExprEvalContexts.back();
7121 }
7122
7123 ExpressionEvaluationContextRecord &currentEvaluationContext() {
7124 assert(!ExprEvalContexts.empty() &&
7125 "Must be in an expression evaluation context");
7126 return ExprEvalContexts.back();
7127 }
7128
7129 ExpressionEvaluationContextRecord &parentEvaluationContext() {
7130 assert(ExprEvalContexts.size() >= 2 &&
7131 "Must be in an expression evaluation context");
7132 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7133 }
7134
7135 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
7136 return const_cast<Sema *>(this)->parentEvaluationContext();
7137 }
7138
7139 bool isAttrContext() const {
7140 return ExprEvalContexts.back().ExprContext ==
7141 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
7142 }
7143
7144 /// Increment when we find a reference; decrement when we find an ignored
7145 /// assignment. Ultimately the value is 0 if every reference is an ignored
7146 /// assignment.
7147 ///
7148 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7149 /// static data members get tracked as a single entry.
7150 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7151
7152 /// Used to control the generation of ExprWithCleanups.
7153 CleanupInfo Cleanup;
7154
7155 /// ExprCleanupObjects - This is the stack of objects requiring
7156 /// cleanup that are created by the current full expression.
7157 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7158
7159 /// Determine whether the use of this declaration is valid, without
7160 /// emitting diagnostics.
7161 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7162 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7163 // has been used to find this declaration, which means we don't have to bother
7164 // checking the trailing requires clause.
7165 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7166 return DiagnoseUseOfDecl(
7167 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7168 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7169 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7170 }
7171
7172 /// Determine whether the use of this declaration is valid, and
7173 /// emit any corresponding diagnostics.
7174 ///
7175 /// This routine diagnoses various problems with referencing
7176 /// declarations that can occur when using a declaration. For example,
7177 /// it might warn if a deprecated or unavailable declaration is being
7178 /// used, or produce an error (and return true) if a C++0x deleted
7179 /// function is being used.
7180 ///
7181 /// \returns true if there was an error (this declaration cannot be
7182 /// referenced), false otherwise.
7183 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7184 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7185 bool ObjCPropertyAccess = false,
7186 bool AvoidPartialAvailabilityChecks = false,
7187 ObjCInterfaceDecl *ClassReceiver = nullptr,
7188 bool SkipTrailingRequiresClause = false);
7189
7190 /// Emit a note explaining that this function is deleted.
7191 void NoteDeletedFunction(FunctionDecl *FD);
7192
7193 /// DiagnoseSentinelCalls - This routine checks whether a call or
7194 /// message-send is to a declaration with the sentinel attribute, and
7195 /// if so, it checks that the requirements of the sentinel are
7196 /// satisfied.
7197 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7198 ArrayRef<Expr *> Args);
7199
7200 void PushExpressionEvaluationContext(
7201 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7202 ExpressionEvaluationContextRecord::ExpressionKind Type =
7203 ExpressionEvaluationContextRecord::EK_Other);
7204
7205 void PushExpressionEvaluationContextForFunction(
7206 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7207
7208 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7209 void PushExpressionEvaluationContext(
7210 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7211 ExpressionEvaluationContextRecord::ExpressionKind Type =
7212 ExpressionEvaluationContextRecord::EK_Other);
7213 void PopExpressionEvaluationContext();
7214
7215 void DiscardCleanupsInEvaluationContext();
7216
7217 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7218 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7219 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7220
7221 /// Check whether E, which is either a discarded-value expression or an
7222 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7223 /// lvalue, and if so, remove it from the list of volatile-qualified
7224 /// assignments that we are going to warn are deprecated.
7225 void CheckUnusedVolatileAssignment(Expr *E);
7226
7227 ExprResult ActOnConstantExpression(ExprResult Res);
7228
7229 // Functions for marking a declaration referenced. These functions also
7230 // contain the relevant logic for marking if a reference to a function or
7231 // variable is an odr-use (in the C++11 sense). There are separate variants
7232 // for expressions referring to a decl; these exist because odr-use marking
7233 // needs to be delayed for some constant variables when we build one of the
7234 // named expressions.
7235 //
7236 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7237 // should usually be true. This only needs to be set to false if the lack of
7238 // odr-use cannot be determined from the current context (for instance,
7239 // because the name denotes a virtual function and was written without an
7240 // explicit nested-name-specifier).
7241 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7242
7243 /// Mark a function referenced, and check whether it is odr-used
7244 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7245 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7246 bool MightBeOdrUse = true);
7247
7248 /// Mark a variable referenced, and check whether it is odr-used
7249 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7250 /// used directly for normal expressions referring to VarDecl.
7251 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7252
7253 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7254 ///
7255 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7256 /// be handled with care if the DeclRefExpr is not newly-created.
7257 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7258
7259 /// Perform reference-marking and odr-use handling for a MemberExpr.
7260 void MarkMemberReferenced(MemberExpr *E);
7261
7262 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7263 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7264 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7265 unsigned CapturingScopeIndex);
7266
7267 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7268 void CleanupVarDeclMarking();
7269
7270 /// Try to capture the given variable.
7271 ///
7272 /// \param Var The variable to capture.
7273 ///
7274 /// \param Loc The location at which the capture occurs.
7275 ///
7276 /// \param Kind The kind of capture, which may be implicit (for either a
7277 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7278 ///
7279 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7280 /// an explicit lambda capture.
7281 ///
7282 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7283 /// captures or diagnose errors. If false, this routine merely check whether
7284 /// the capture can occur without performing the capture itself or complaining
7285 /// if the variable cannot be captured.
7286 ///
7287 /// \param CaptureType Will be set to the type of the field used to capture
7288 /// this variable in the innermost block or lambda. Only valid when the
7289 /// variable can be captured.
7290 ///
7291 /// \param DeclRefType Will be set to the type of a reference to the capture
7292 /// from within the current scope. Only valid when the variable can be
7293 /// captured.
7294 ///
7295 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7296 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7297 /// This is useful when enclosing lambdas must speculatively capture
7298 /// variables that may or may not be used in certain specializations of
7299 /// a nested generic lambda.
7300 ///
7301 /// \returns true if an error occurred (i.e., the variable cannot be
7302 /// captured) and false if the capture succeeded.
7303 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7304 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7305 bool BuildAndDiagnose, QualType &CaptureType,
7306 QualType &DeclRefType,
7307 const unsigned *const FunctionScopeIndexToStopAt);
7308
7309 /// Try to capture the given variable.
7310 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7311 TryCaptureKind Kind = TryCaptureKind::Implicit,
7312 SourceLocation EllipsisLoc = SourceLocation());
7313
7314 /// Checks if the variable must be captured.
7315 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7316
7317 /// Given a variable, determine the type that a reference to that
7318 /// variable will have in the given scope.
7319 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7320
7321 /// Handle a use of the variably modified type \p T in the current context.
7322 /// Array bounds evaluated in an enclosing context are captured by the
7323 /// lambdas in between; if a local class or a block is in between instead,
7324 /// the use is diagnosed. Returns false if the use is invalid.
7325 bool CheckVariablyModifiedTypeUse(QualType T, SourceLocation Loc);
7326
7327 /// Mark all of the declarations referenced within a particular AST node as
7328 /// referenced. Used when template instantiation instantiates a non-dependent
7329 /// type -- entities referenced by the type are now referenced.
7330 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7331
7332 /// Mark any declarations that appear within this expression or any
7333 /// potentially-evaluated subexpressions as "referenced".
7334 ///
7335 /// \param SkipLocalVariables If true, don't mark local variables as
7336 /// 'referenced'.
7337 /// \param StopAt Subexpressions that we shouldn't recurse into.
7338 void MarkDeclarationsReferencedInExpr(Expr *E,
7339 bool SkipLocalVariables = false,
7340 ArrayRef<const Expr *> StopAt = {});
7341
7342 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7343 /// conversion.
7344 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7345
7346 /// Conditionally issue a diagnostic based on the statements's reachability
7347 /// analysis.
7348 ///
7349 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7350 /// the function body is parsed, and then do a basic reachability analysis to
7351 /// determine if the statement is reachable. If it is unreachable, the
7352 /// diagnostic will not be emitted.
7353 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7354 const PartialDiagnostic &PD);
7355
7356 /// Conditionally issue a diagnostic based on the current
7357 /// evaluation context.
7358 ///
7359 /// \param Statement If Statement is non-null, delay reporting the
7360 /// diagnostic until the function body is parsed, and then do a basic
7361 /// reachability analysis to determine if the statement is reachable.
7362 /// If it is unreachable, the diagnostic will not be emitted.
7363 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7364 const PartialDiagnostic &PD);
7365 /// Similar, but diagnostic is only produced if all the specified statements
7366 /// are reachable.
7367 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7368 const PartialDiagnostic &PD);
7369
7370 // Primary Expressions.
7371 SourceRange getExprRange(Expr *E) const;
7372
7373 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7374 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7375 bool IsCall, bool IsAddressOfOperand,
7376 CorrectionCandidateCallback *CCC = nullptr,
7377 bool IsInlineAsmIdentifier = false);
7378
7379 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7380 /// possibly a list of template arguments.
7381 ///
7382 /// If this produces template arguments, it is permitted to call
7383 /// DecomposeTemplateName.
7384 ///
7385 /// This actually loses a lot of source location information for
7386 /// non-standard name kinds; we should consider preserving that in
7387 /// some way.
7388 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7389 TemplateArgumentListInfo &Buffer,
7390 DeclarationNameInfo &NameInfo,
7391 const TemplateArgumentListInfo *&TemplateArgs);
7392
7393 /// Diagnose a lookup that found results in an enclosing class during error
7394 /// recovery. This usually indicates that the results were found in a
7395 /// dependent base class that could not be searched as part of a template
7396 /// definition. Always issues a diagnostic (though this may be only a warning
7397 /// in MS compatibility mode).
7398 ///
7399 /// Return \c true if the error is unrecoverable, or \c false if the caller
7400 /// should attempt to recover using these lookup results.
7401 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7402
7403 /// Diagnose an empty lookup.
7404 ///
7405 /// \return false if new lookup candidates were found
7406 bool
7407 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7408 CorrectionCandidateCallback &CCC,
7409 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7410 ArrayRef<Expr *> Args = {},
7411 DeclContext *LookupCtx = nullptr);
7412
7413 /// If \p D cannot be odr-used in the current expression evaluation context,
7414 /// return a reason explaining why. Otherwise, return NOUR_None.
7415 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7416
7417 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7418 SourceLocation Loc,
7419 const CXXScopeSpec *SS = nullptr);
7420 DeclRefExpr *
7421 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7422 const DeclarationNameInfo &NameInfo,
7423 const CXXScopeSpec *SS = nullptr,
7424 NamedDecl *FoundD = nullptr,
7425 SourceLocation TemplateKWLoc = SourceLocation(),
7426 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7427
7428 /// BuildDeclRefExpr - Build an expression that references a
7429 /// declaration that does not require a closure capture.
7430 DeclRefExpr *
7431 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7432 const DeclarationNameInfo &NameInfo,
7433 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7434 SourceLocation TemplateKWLoc = SourceLocation(),
7435 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7436
7437 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7438 bool IsCall);
7439
7440 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7441 /// declaration name, generally during template instantiation.
7442 /// There's a large number of things which don't need to be done along
7443 /// this path.
7444 ExprResult BuildQualifiedDeclarationNameExpr(
7445 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7446 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7447
7448 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7449 bool NeedsADL,
7450 bool AcceptInvalidDecl = false);
7451
7452 /// Complete semantic analysis for a reference to the given declaration.
7453 ExprResult BuildDeclarationNameExpr(
7454 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7455 NamedDecl *FoundD = nullptr,
7456 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7457 bool AcceptInvalidDecl = false);
7458
7459 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7460 // where Tokens representing function local predefined macros (such as
7461 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7462 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7463
7464 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7465 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7466 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7467
7468 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7469
7470 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7471 ExprResult ActOnCharacterConstant(const Token &Tok,
7472 Scope *UDLScope = nullptr);
7473 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7474 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7475 MultiExprArg Val);
7476 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7477 unsigned NumUserSpecifiedExprs,
7478 SourceLocation InitLoc,
7479 SourceLocation LParenLoc,
7480 SourceLocation RParenLoc);
7481
7482 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7483 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7484 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7485 /// from multiple tokens. However, the common case is that StringToks points
7486 /// to one string.
7487 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7488 Scope *UDLScope = nullptr,
7489 ConversionAction Action = CA_ToLiteralEncoding);
7490
7491 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7492
7493 /// ControllingExprOrType is either an opaque pointer coming out of a
7494 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7495 /// into two so we don't take a void *, but that's awkward because one of
7496 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7497 /// itself to generic code very well.
7498 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7499 SourceLocation DefaultLoc,
7500 SourceLocation RParenLoc,
7501 bool PredicateIsExpr,
7502 void *ControllingExprOrType,
7503 ArrayRef<ParsedType> ArgTypes,
7504 ArrayRef<Expr *> ArgExprs);
7505 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7506 /// it'd be better to split this interface into two so we don't take a
7507 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7508 /// isn't a trivial change.
7509 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7510 SourceLocation DefaultLoc,
7511 SourceLocation RParenLoc,
7512 bool PredicateIsExpr,
7513 void *ControllingExprOrType,
7514 ArrayRef<TypeSourceInfo *> Types,
7515 ArrayRef<Expr *> Exprs);
7516
7517 // Binary/Unary Operators. 'Tok' is the token for the operator.
7518 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7519 Expr *InputExpr, bool IsAfterAmp = false);
7520 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7521 Expr *Input, bool IsAfterAmp = false);
7522
7523 /// Unary Operators. 'Tok' is the token for the operator.
7524 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7525 Expr *Input, bool IsAfterAmp = false);
7526
7527 /// Determine whether the given expression is a qualified member
7528 /// access expression, of a form that could be turned into a pointer to member
7529 /// with the address-of operator.
7530 bool isQualifiedMemberAccess(Expr *E);
7531 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7532 const Expr *Op,
7533 const CXXMethodDecl *MD);
7534
7535 /// CheckAddressOfOperand - The operand of & must be either a function
7536 /// designator or an lvalue designating an object. If it is an lvalue, the
7537 /// object cannot be declared with storage class register or be a bit field.
7538 /// Note: The usual conversions are *not* applied to the operand of the &
7539 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7540 /// In C++, the operand might be an overloaded function name, in which case
7541 /// we allow the '&' but retain the overloaded-function type.
7542 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7543
7544 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7545 /// _Alignas(type-name) .
7546 /// [dcl.align] An alignment-specifier of the form
7547 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7548 ///
7549 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7550 /// _Alignas(_Alignof(type-name)).
7551 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7552 SourceLocation OpLoc, SourceRange R);
7553 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7554 SourceLocation OpLoc, SourceRange R);
7555
7556 /// Build a sizeof or alignof expression given a type operand.
7557 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7558 SourceLocation OpLoc,
7559 UnaryExprOrTypeTrait ExprKind,
7560 SourceRange R);
7561
7562 /// Build a sizeof or alignof expression given an expression
7563 /// operand.
7564 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7565 UnaryExprOrTypeTrait ExprKind);
7566
7567 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7568 /// expr and the same for @c alignof and @c __alignof
7569 /// Note that the ArgRange is invalid if isType is false.
7570 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7571 UnaryExprOrTypeTrait ExprKind,
7572 bool IsType, void *TyOrEx,
7573 SourceRange ArgRange);
7574
7575 /// Check for operands with placeholder types and complain if found.
7576 /// Returns ExprError() if there was an error and no recovery was possible.
7577 ExprResult CheckPlaceholderExpr(Expr *E);
7578 bool CheckVecStepExpr(Expr *E);
7579
7580 /// Check the constraints on expression operands to unary type expression
7581 /// and type traits.
7582 ///
7583 /// Completes any types necessary and validates the constraints on the operand
7584 /// expression. The logic mostly mirrors the type-based overload, but may
7585 /// modify the expression as it completes the type for that expression through
7586 /// template instantiation, etc.
7587 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7588
7589 /// Check the constraints on operands to unary expression and type
7590 /// traits.
7591 ///
7592 /// This will complete any types necessary, and validate the various
7593 /// constraints on those operands.
7594 ///
7595 /// The UsualUnaryConversions() function is *not* called by this routine.
7596 /// C99 6.3.2.1p[2-4] all state:
7597 /// Except when it is the operand of the sizeof operator ...
7598 ///
7599 /// C++ [expr.sizeof]p4
7600 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7601 /// standard conversions are not applied to the operand of sizeof.
7602 ///
7603 /// This policy is followed for all of the unary trait expressions.
7604 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7605 SourceRange ExprRange,
7606 UnaryExprOrTypeTrait ExprKind,
7607 StringRef KWName);
7608
7609 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7610 tok::TokenKind Kind, Expr *Input);
7611
7612 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7613 MultiExprArg ArgExprs,
7614 SourceLocation RLoc);
7615 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7616 Expr *Idx, SourceLocation RLoc);
7617
7618 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7619 SourceLocation RBLoc);
7620
7621 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7622 Expr *ColumnIdx,
7623 SourceLocation RBLoc);
7624
7625 /// ConvertArgumentsForCall - Converts the arguments specified in
7626 /// Args/NumArgs to the parameter types of the function FDecl with
7627 /// function prototype Proto. Call is the call expression itself, and
7628 /// Fn is the function expression. For a C++ member function, this
7629 /// routine does not attempt to convert the object argument. Returns
7630 /// true if the call is ill-formed.
7631 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7632 const FunctionProtoType *Proto,
7633 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7634 bool ExecConfig = false);
7635
7636 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7637 /// array parameter, check that it is non-null, and that if it is formed by
7638 /// array-to-pointer decay, the underlying array is sufficiently large.
7639 ///
7640 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7641 /// the array type derivation, then for each call to the function, the value
7642 /// of the corresponding actual argument shall provide access to the first
7643 /// element of an array with at least as many elements as specified by the
7644 /// size expression.
7645 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7646 const Expr *ArgExpr);
7647
7648 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7649 /// This provides the location of the left/right parens and a list of comma
7650 /// locations.
7651 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7652 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7653 Expr *ExecConfig = nullptr);
7654
7655 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7656 /// This provides the location of the left/right parens and a list of comma
7657 /// locations.
7658 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7659 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7660 Expr *ExecConfig = nullptr,
7661 bool IsExecConfig = false,
7662 bool AllowRecovery = false);
7663
7664 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7665 /// with the specified CallArgs. Id is unsigned rather than Builtin::ID, so
7666 /// that it can also be a target-specific builtin ID, which is not in
7667 /// Builtin::ID, e.g., BPF::BI__builtin_preserve_enum_value.
7668 Expr *BuildBuiltinCallExpr(SourceLocation Loc, unsigned Id,
7669 MultiExprArg CallArgs);
7670
7671 using ADLCallKind = CallExpr::ADLCallKind;
7672
7673 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7674 /// i.e. an expression not of \p OverloadTy. The expression should
7675 /// unary-convert to an expression of function-pointer or
7676 /// block-pointer type.
7677 ///
7678 /// \param NDecl the declaration being called, if available
7679 ExprResult
7680 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7681 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7682 Expr *Config = nullptr, bool IsExecConfig = false,
7683 ADLCallKind UsesADL = ADLCallKind::NotADL);
7684
7685 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7686 ParsedType &Ty, SourceLocation RParenLoc,
7687 Expr *CastExpr);
7688
7689 /// Prepares for a scalar cast, performing all the necessary stages
7690 /// except the final cast and returning the kind required.
7691 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7692
7693 /// Build an altivec or OpenCL literal.
7694 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7695 SourceLocation RParenLoc, Expr *E,
7696 TypeSourceInfo *TInfo);
7697
7698 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7699 /// the ParenListExpr into a sequence of comma binary operators.
7700 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7701
7702 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7703 SourceLocation RParenLoc, Expr *InitExpr);
7704
7705 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7706 TypeSourceInfo *TInfo,
7707 SourceLocation RParenLoc,
7708 Expr *LiteralExpr);
7709
7710 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7711 SourceLocation RBraceLoc);
7712
7713 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7714 SourceLocation RBraceLoc, bool IsExplicit);
7715
7716 /// Binary Operators. 'Tok' is the token for the operator.
7717 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7718 Expr *LHSExpr, Expr *RHSExpr);
7719 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7720 Expr *LHSExpr, Expr *RHSExpr,
7721 bool ForFoldExpression = false);
7722
7723 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7724 /// operator @p Opc at location @c TokLoc. This routine only supports
7725 /// built-in operations; ActOnBinOp handles overloaded operators.
7726 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7727 Expr *LHSExpr, Expr *RHSExpr,
7728 bool ForFoldExpression = false);
7729 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7730 UnresolvedSetImpl &Functions);
7731
7732 /// Look for instances where it is likely the comma operator is confused with
7733 /// another operator. There is an explicit list of acceptable expressions for
7734 /// the left hand side of the comma operator, otherwise emit a warning.
7735 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7736
7737 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7738 /// in the case of a the GNU conditional expr extension.
7739 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7740 SourceLocation ColonLoc, Expr *CondExpr,
7741 Expr *LHSExpr, Expr *RHSExpr);
7742
7743 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7744 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7745 LabelDecl *TheDecl);
7746
7747 void ActOnStartStmtExpr();
7748 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7749 SourceLocation RPLoc);
7750 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7751 SourceLocation RPLoc, unsigned TemplateDepth);
7752 // Handle the final expression in a statement expression.
7753 ExprResult ActOnStmtExprResult(ExprResult E);
7754 void ActOnStmtExprError();
7755
7756 /// __builtin_offsetof(type, a.b[123][456].c)
7757 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7758 TypeSourceInfo *TInfo,
7759 const Designation &Desig,
7760 SourceLocation RParenLoc);
7761 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7762 SourceLocation TypeLoc,
7763 ParsedType ParsedArgTy,
7764 const Designation &Desig,
7765 SourceLocation RParenLoc);
7766
7767 // __builtin_choose_expr(constExpr, expr1, expr2)
7768 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7769 Expr *LHSExpr, Expr *RHSExpr,
7770 SourceLocation RPLoc);
7771
7772 // __builtin_va_arg(expr, type)
7773 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7774 SourceLocation RPLoc);
7775 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7776 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7777
7778 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7779 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7780 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7781 SourceLocation BuiltinLoc,
7782 SourceLocation RPLoc);
7783
7784 // #embed
7785 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7786 StringLiteral *BinaryData, StringRef FileName);
7787
7788 // Build a potentially resolved SourceLocExpr.
7789 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7790 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7791 DeclContext *ParentContext);
7792
7793 // __null
7794 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7795
7796 bool CheckCaseExpression(Expr *E);
7797
7798 //===------------------------- "Block" Extension ------------------------===//
7799
7800 /// ActOnBlockStart - This callback is invoked when a block literal is
7801 /// started.
7802 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7803
7804 /// ActOnBlockArguments - This callback allows processing of block arguments.
7805 /// If there are no arguments, this is still invoked.
7806 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7807 Scope *CurScope);
7808
7809 /// ActOnBlockError - If there is an error parsing a block, this callback
7810 /// is invoked to pop the information about the block from the action impl.
7811 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7812
7813 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7814 /// literal was successfully completed. ^(int x){...}
7815 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7816 Scope *CurScope);
7817
7818 //===---------------------------- Clang Extensions ----------------------===//
7819
7820 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7821 /// provided arguments.
7822 ///
7823 /// __builtin_convertvector( value, dst type )
7824 ///
7825 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7826 SourceLocation BuiltinLoc,
7827 SourceLocation RParenLoc);
7828
7829 //===---------------------------- OpenCL Features -----------------------===//
7830
7831 /// Parse a __builtin_astype expression.
7832 ///
7833 /// __builtin_astype( value, dst type )
7834 ///
7835 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7836 SourceLocation BuiltinLoc,
7837 SourceLocation RParenLoc);
7838
7839 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7840 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7841 SourceLocation BuiltinLoc,
7842 SourceLocation RParenLoc);
7843
7844 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7845 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7846 ArrayRef<Expr *> SubExprs,
7847 QualType T = QualType());
7848
7849 /// Cast a base object to a member's actual type.
7850 ///
7851 /// There are two relevant checks:
7852 ///
7853 /// C++ [class.access.base]p7:
7854 ///
7855 /// If a class member access operator [...] is used to access a non-static
7856 /// data member or non-static member function, the reference is ill-formed
7857 /// if the left operand [...] cannot be implicitly converted to a pointer to
7858 /// the naming class of the right operand.
7859 ///
7860 /// C++ [expr.ref]p7:
7861 ///
7862 /// If E2 is a non-static data member or a non-static member function, the
7863 /// program is ill-formed if the class of which E2 is directly a member is
7864 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7865 ///
7866 /// Note that the latter check does not consider access; the access of the
7867 /// "real" base class is checked as appropriate when checking the access of
7868 /// the member name.
7869 ExprResult PerformObjectMemberConversion(Expr *From,
7870 NestedNameSpecifier Qualifier,
7871 NamedDecl *FoundDecl,
7872 NamedDecl *Member);
7873
7874 /// CheckCallReturnType - Checks that a call expression's return type is
7875 /// complete. Returns true on failure. The location passed in is the location
7876 /// that best represents the call.
7877 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7878 CallExpr *CE, FunctionDecl *FD);
7879
7880 /// Emit a warning for all pending noderef expressions that we recorded.
7881 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7882
7883private:
7884 /// Shared logic for building default member initializer which used in a
7885 /// constructor or an aggregate initialization.
7886 ///
7887 ///
7888 /// The caller enters that evaluation context and decides whether the result
7889 /// is finished as a full-expression. \p NestedDefaultChecking and
7890 /// \p NeedRebuild have to be sampled before entering it.
7891 ExprResult BuildCXXDefaultInitInternal(SourceLocation Loc, FieldDecl *Field,
7892 const InitializedEntity &Entity,
7893 bool NestedDefaultChecking,
7894 bool NeedRebuild);
7895
7896public:
7897 ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7898 ExprResult
7899 BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field,
7900 const InitializedEntity &MemberEntity);
7901
7902 /// Instantiate or parse a C++ default argument expression as necessary.
7903 /// Return true on error.
7904 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7905 ParmVarDecl *Param, Expr *Init = nullptr,
7906 bool SkipImmediateInvocations = true);
7907
7908 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7909 /// the default expr if needed.
7910 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7911 ParmVarDecl *Param, Expr *Init = nullptr);
7912
7913 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7914 /// invocation.
7915 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7916
7917 void MarkExpressionAsImmediateEscalating(Expr *E);
7918
7919 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7920 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7921
7922 /// Abstract base class used for diagnosing integer constant
7923 /// expression violations.
7924 class VerifyICEDiagnoser {
7925 public:
7926 bool Suppress;
7927
7928 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7929
7930 virtual SemaDiagnosticBuilder
7931 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7932 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7933 SourceLocation Loc) = 0;
7934 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7935 virtual ~VerifyICEDiagnoser() {}
7936 };
7937
7938 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7939 /// and reports the appropriate diagnostics. Returns false on success.
7940 /// Can optionally return the value of the expression.
7941 ExprResult
7942 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7943 VerifyICEDiagnoser &Diagnoser,
7944 AllowFoldKind CanFold = AllowFoldKind::No);
7945 ExprResult
7946 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7947 unsigned DiagID,
7948 AllowFoldKind CanFold = AllowFoldKind::No);
7949 ExprResult
7950 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7951 AllowFoldKind CanFold = AllowFoldKind::No);
7952 ExprResult
7953 VerifyIntegerConstantExpression(Expr *E,
7954 AllowFoldKind CanFold = AllowFoldKind::No) {
7955 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7956 }
7957
7958 /// DiagnoseAssignmentAsCondition - Given that an expression is
7959 /// being used as a boolean condition, warn if it's an assignment.
7960 void DiagnoseAssignmentAsCondition(Expr *E);
7961
7962 /// Redundant parentheses over an equality comparison can indicate
7963 /// that the user intended an assignment used as condition.
7964 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7965
7966 class FullExprArg {
7967 public:
7968 FullExprArg() : E(nullptr) {}
7969 FullExprArg(Sema &actions) : E(nullptr) {}
7970
7971 ExprResult release() { return E; }
7972
7973 Expr *get() const { return E; }
7974
7975 Expr *operator->() { return E; }
7976
7977 private:
7978 // FIXME: No need to make the entire Sema class a friend when it's just
7979 // Sema::MakeFullExpr that needs access to the constructor below.
7980 friend class Sema;
7981
7982 explicit FullExprArg(Expr *expr) : E(expr) {}
7983
7984 Expr *E;
7985 };
7986
7987 FullExprArg MakeFullExpr(Expr *Arg) {
7988 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7989 }
7990 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7991 return FullExprArg(
7992 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7993 }
7994 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7995 ExprResult FE =
7996 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7997 /*DiscardedValue*/ DiscardedValue: true);
7998 return FullExprArg(FE.get());
7999 }
8000
8001 class ConditionResult {
8002 Decl *ConditionVar;
8003 ExprResult Condition;
8004 bool Invalid;
8005 std::optional<bool> KnownValue;
8006
8007 friend class Sema;
8008 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
8009 bool IsConstexpr)
8010 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
8011 if (IsConstexpr && Condition.get()) {
8012 if (std::optional<llvm::APSInt> Val =
8013 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
8014 KnownValue = !!(*Val);
8015 }
8016 }
8017 }
8018 explicit ConditionResult(bool Invalid)
8019 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
8020 KnownValue(std::nullopt) {}
8021
8022 public:
8023 ConditionResult() : ConditionResult(false) {}
8024 bool isInvalid() const { return Invalid; }
8025 std::pair<VarDecl *, Expr *> get() const {
8026 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
8027 y: Condition.get());
8028 }
8029 std::optional<bool> getKnownValue() const { return KnownValue; }
8030 };
8031 static ConditionResult ConditionError() { return ConditionResult(true); }
8032
8033 /// CheckBooleanCondition - Diagnose problems involving the use of
8034 /// the given expression as a boolean condition (e.g. in an if
8035 /// statement). Also performs the standard function and array
8036 /// decays, possibly changing the input variable.
8037 ///
8038 /// \param Loc - A location associated with the condition, e.g. the
8039 /// 'if' keyword.
8040 /// \return true iff there were any errors
8041 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
8042 bool IsConstexpr = false);
8043
8044 enum class ConditionKind {
8045 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
8046 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
8047 Switch ///< An integral condition for a 'switch' statement.
8048 };
8049
8050 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
8051 ConditionKind CK, bool MissingOK = false);
8052
8053 QualType CheckConditionalOperands( // C99 6.5.15
8054 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
8055 ExprObjectKind &OK, SourceLocation QuestionLoc);
8056
8057 /// Emit a specialized diagnostic when one expression is a null pointer
8058 /// constant and the other is not a pointer. Returns true if a diagnostic is
8059 /// emitted.
8060 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8061 SourceLocation QuestionLoc);
8062
8063 /// type checking for vector binary operators.
8064 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8065 SourceLocation Loc, bool IsCompAssign,
8066 bool AllowBothBool, bool AllowBoolConversion,
8067 bool AllowBoolOperation);
8068
8069 /// Return a signed ext_vector_type that is of identical size and number of
8070 /// elements. For floating point vectors, return an integer type of identical
8071 /// size and number of elements. In the non ext_vector_type case, search from
8072 /// the largest type to the smallest type to avoid cases where long long ==
8073 /// long, where long gets picked over long long.
8074 QualType GetSignedVectorType(QualType V);
8075 QualType GetSignedSizelessVectorType(QualType V);
8076
8077 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8078 /// operates on extended vector types. Instead of producing an IntTy result,
8079 /// like a scalar comparison, a vector comparison produces a vector of integer
8080 /// types.
8081 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8082 SourceLocation Loc,
8083 BinaryOperatorKind Opc);
8084 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8085 SourceLocation Loc,
8086 BinaryOperatorKind Opc);
8087 QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS,
8088 SourceLocation Loc,
8089 BinaryOperatorKind Opc);
8090 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8091 SourceLocation Loc,
8092 BinaryOperatorKind Opc);
8093 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8094 SourceLocation Loc,
8095 BinaryOperatorKind Opc);
8096 // type checking for sizeless vector binary operators.
8097 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
8098 SourceLocation Loc, bool IsCompAssign,
8099 ArithConvKind OperationKind);
8100
8101 /// Type checking for matrix binary operators.
8102 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
8103 SourceLocation Loc,
8104 bool IsCompAssign);
8105 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
8106 SourceLocation Loc, bool IsCompAssign);
8107
8108 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
8109 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
8110 /// VLST) allowed?
8111 ///
8112 /// This will also return false if the two given types do not make sense from
8113 /// the perspective of SVE bitcasts.
8114 bool isValidSveBitcast(QualType srcType, QualType destType);
8115
8116 /// Are the two types matrix types and do they have the same dimensions i.e.
8117 /// do they have the same number of rows and the same number of columns?
8118 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
8119
8120 bool areVectorTypesSameSize(QualType srcType, QualType destType);
8121
8122 /// Are the two types lax-compatible vector types? That is, given
8123 /// that one of them is a vector, do they have equal storage sizes,
8124 /// where the storage size is the number of elements times the element
8125 /// size?
8126 ///
8127 /// This will also return false if either of the types is neither a
8128 /// vector nor a real type.
8129 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
8130
8131 /// Is this a legal conversion between two types, one of which is
8132 /// known to be a vector type?
8133 bool isLaxVectorConversion(QualType srcType, QualType destType);
8134
8135 // This returns true if at least one of the types is an altivec vector.
8136 bool anyAltivecTypes(QualType srcType, QualType destType);
8137
8138 // type checking C++ declaration initializers (C++ [dcl.init]).
8139
8140 /// Check a cast of an unknown-any type. We intentionally only
8141 /// trigger this for C-style casts.
8142 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8143 Expr *CastExpr, CastKind &CastKind,
8144 ExprValueKind &VK, CXXCastPath &Path);
8145
8146 /// Force an expression with unknown-type to an expression of the
8147 /// given type.
8148 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8149
8150 /// Type-check an expression that's being passed to an
8151 /// __unknown_anytype parameter.
8152 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
8153 QualType &paramType);
8154
8155 // CheckMatrixCast - Check type constraints for matrix casts.
8156 // We allow casting between matrixes of the same dimensions i.e. when they
8157 // have the same number of rows and column. Returns true if the cast is
8158 // invalid.
8159 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8160 CastKind &Kind);
8161
8162 // CheckVectorCast - check type constraints for vectors.
8163 // Since vectors are an extension, there are no C standard reference for this.
8164 // We allow casting between vectors and integer datatypes of the same size.
8165 // returns true if the cast is invalid
8166 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8167 CastKind &Kind);
8168
8169 /// Prepare `SplattedExpr` for a vector splat operation, adding
8170 /// implicit casts if necessary.
8171 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8172
8173 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8174 /// implicit casts if necessary.
8175 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8176
8177 // CheckExtVectorCast - check type constraints for extended vectors.
8178 // Since vectors are an extension, there are no C standard reference for this.
8179 // We allow casting between vectors and integer datatypes of the same size,
8180 // or vectors and the element type of that vector.
8181 // returns the cast expr
8182 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8183 CastKind &Kind);
8184
8185 QualType PreferredConditionType(ConditionKind K) const {
8186 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8187 }
8188
8189 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8190 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8191 // promotes floating-piont types according to the language semantics.
8192 ExprResult UsualUnaryConversions(Expr *E);
8193
8194 // UsualUnaryFPConversions - promotes floating-point types according to the
8195 // current language semantics.
8196 ExprResult UsualUnaryFPConversions(Expr *E);
8197
8198 /// CallExprUnaryConversions - a special case of an unary conversion
8199 /// performed on a function designator of a call expression.
8200 ExprResult CallExprUnaryConversions(Expr *E);
8201
8202 // DefaultFunctionArrayConversion - converts functions and arrays
8203 // to their respective pointers (C99 6.3.2.1).
8204 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8205
8206 // DefaultFunctionArrayLvalueConversion - converts functions and
8207 // arrays to their respective pointers and performs the
8208 // lvalue-to-rvalue conversion.
8209 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8210 bool Diagnose = true);
8211
8212 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8213 // the operand. This function is a no-op if the operand has a function type
8214 // or an array type.
8215 ExprResult DefaultLvalueConversion(Expr *E);
8216
8217 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8218 // do not have a prototype. Integer promotions are performed on each
8219 // argument, and arguments that have type float are promoted to double.
8220 ExprResult DefaultArgumentPromotion(Expr *E);
8221
8222 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8223 const FunctionProtoType *Proto,
8224 Expr *Fn);
8225
8226 /// Determine the degree of POD-ness for an expression.
8227 /// Incomplete types are considered POD, since this check can be performed
8228 /// when we're in an unevaluated context.
8229 VarArgKind isValidVarArgType(const QualType &Ty);
8230
8231 /// Check to see if the given expression is a valid argument to a variadic
8232 /// function, issuing a diagnostic if not.
8233 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8234
8235 /// GatherArgumentsForCall - Collector argument expressions for various
8236 /// form of call prototypes.
8237 bool GatherArgumentsForCall(
8238 SourceLocation CallLoc, FunctionDecl *FDecl,
8239 const FunctionProtoType *Proto, unsigned FirstParam,
8240 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8241 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8242 bool AllowExplicit = false, bool IsListInitialization = false);
8243
8244 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8245 // will create a runtime trap if the resulting type is not a POD type.
8246 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8247 FunctionDecl *FDecl);
8248
8249 // Check that the usual arithmetic conversions can be performed on this pair
8250 // of expressions that might be of enumeration type.
8251 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8252 ArithConvKind ACK);
8253
8254 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8255 // operands and then handles various conversions that are common to binary
8256 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8257 // routine returns the first non-arithmetic type found. The client is
8258 // responsible for emitting appropriate error diagnostics.
8259 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8260 SourceLocation Loc, ArithConvKind ACK);
8261
8262 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8263 switch (ConvTy) {
8264 default:
8265 return false;
8266 case AssignConvertType::Compatible:
8267 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8268 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8269 return true;
8270 }
8271 llvm_unreachable("impossible");
8272 }
8273
8274 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8275 /// assignment conversion type specified by ConvTy. This returns true if the
8276 /// conversion was invalid or false if the conversion was accepted.
8277 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8278 QualType DstType, QualType SrcType,
8279 Expr *SrcExpr, AssignmentAction Action,
8280 bool *Complained = nullptr);
8281
8282 /// CheckAssignmentConstraints - Perform type checking for assignment,
8283 /// argument passing, variable initialization, and function return values.
8284 /// C99 6.5.16.
8285 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8286 QualType LHSType,
8287 QualType RHSType);
8288
8289 /// Check assignment constraints and optionally prepare for a conversion of
8290 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8291 /// is true.
8292 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8293 ExprResult &RHS, CastKind &Kind,
8294 bool ConvertRHS = true);
8295
8296 /// Check assignment constraints for an assignment of RHS to LHSType.
8297 ///
8298 /// \param LHSType The destination type for the assignment.
8299 /// \param RHS The source expression for the assignment.
8300 /// \param Diagnose If \c true, diagnostics may be produced when checking
8301 /// for assignability. If a diagnostic is produced, \p RHS will be
8302 /// set to ExprError(). Note that this function may still return
8303 /// without producing a diagnostic, even for an invalid assignment.
8304 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8305 /// in an audited Core Foundation API and does not need to be checked
8306 /// for ARC retain issues.
8307 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8308 /// conversions necessary to perform the assignment. If \c false,
8309 /// \p Diagnose must also be \c false.
8310 AssignConvertType CheckSingleAssignmentConstraints(
8311 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8312 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8313
8314 // If the lhs type is a transparent union, check whether we
8315 // can initialize the transparent union with the given expression.
8316 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8317 ExprResult &RHS);
8318
8319 /// the following "Check" methods will return a valid/converted QualType
8320 /// or a null QualType (indicating an error diagnostic was issued).
8321
8322 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8323 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8324 ExprResult &RHS);
8325
8326 /// Diagnose cases where a scalar was implicitly converted to a vector and
8327 /// diagnose the underlying types. Otherwise, diagnose the error
8328 /// as invalid vector logical operands for non-C++ cases.
8329 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8330 ExprResult &RHS);
8331
8332 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8333 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8334 BinaryOperatorKind Opc);
8335 QualType CheckRemainderOperands( // C99 6.5.5
8336 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8337 bool IsCompAssign = false);
8338 QualType CheckAdditionOperands( // C99 6.5.6
8339 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8340 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8341 QualType CheckSubtractionOperands( // C99 6.5.6
8342 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8343 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8344 QualType CheckShiftOperands( // C99 6.5.7
8345 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8346 BinaryOperatorKind Opc, bool IsCompAssign = false);
8347 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8348 QualType CheckCompareOperands( // C99 6.5.8/9
8349 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8350 BinaryOperatorKind Opc);
8351 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8352 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8353 BinaryOperatorKind Opc);
8354 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8355 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8356 BinaryOperatorKind Opc);
8357 // CheckAssignmentOperands is used for both simple and compound assignment.
8358 // For simple assignment, pass both expressions and a null converted type.
8359 // For compound assignment, pass both expressions and the converted type.
8360 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8361 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8362 BinaryOperatorKind Opc);
8363
8364 /// To be used for checking whether the arguments being passed to
8365 /// function exceeds the number of parameters expected for it.
8366 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8367 bool PartialOverloading = false) {
8368 // We check whether we're just after a comma in code-completion.
8369 if (NumArgs > 0 && PartialOverloading)
8370 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8371 return NumArgs > NumParams;
8372 }
8373
8374 /// Whether the AST is currently being rebuilt to correct immediate
8375 /// invocations. Immediate invocation candidates and references to consteval
8376 /// functions aren't tracked when this is set.
8377 bool RebuildingImmediateInvocation = false;
8378
8379 bool isAlwaysConstantEvaluatedContext() const {
8380 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8381 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8382 !Ctx.InConditionallyConstantEvaluateContext;
8383 }
8384
8385 /// Determines whether we are currently in a context that
8386 /// is not evaluated as per C++ [expr] p5.
8387 bool isUnevaluatedContext() const {
8388 return currentEvaluationContext().isUnevaluated();
8389 }
8390
8391 bool isImmediateFunctionContext() const {
8392 return currentEvaluationContext().isImmediateFunctionContext();
8393 }
8394
8395 bool isInLifetimeExtendingContext() const {
8396 return currentEvaluationContext().InLifetimeExtendingContext;
8397 }
8398
8399 bool needsRebuildOfDefaultArgOrInit() const {
8400 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8401 }
8402
8403 bool isCheckingDefaultArgumentOrInitializer() const {
8404 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8405 return (Ctx.Context ==
8406 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8407 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8408 }
8409
8410 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8411 InnermostDeclarationWithDelayedImmediateInvocations() const {
8412 assert(!ExprEvalContexts.empty() &&
8413 "Must be in an expression evaluation context");
8414 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8415 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8416 Ctx.DelayedDefaultInitializationContext)
8417 return Ctx.DelayedDefaultInitializationContext;
8418 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8419 Ctx.isUnevaluated())
8420 break;
8421 }
8422 return std::nullopt;
8423 }
8424
8425 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8426 OutermostDeclarationWithDelayedImmediateInvocations() const {
8427 assert(!ExprEvalContexts.empty() &&
8428 "Must be in an expression evaluation context");
8429 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8430 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8431 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8432 !Ctx.DelayedDefaultInitializationContext && Res)
8433 break;
8434 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8435 Ctx.isUnevaluated())
8436 break;
8437 Res = Ctx.DelayedDefaultInitializationContext;
8438 }
8439 return Res;
8440 }
8441
8442 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8443 /// SelfAssigned when inside a CXXMethodDecl.
8444 const FieldDecl *
8445 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8446
8447 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8448
8449 template <typename... Ts>
8450 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8451 const Ts &...Args) {
8452 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8453 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8454 }
8455
8456 template <typename... Ts>
8457 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8458 const Ts &...Args) {
8459 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8460 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8461 }
8462
8463 /// Abstract class used to diagnose incomplete types.
8464 struct TypeDiagnoser {
8465 TypeDiagnoser() {}
8466
8467 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8468 virtual ~TypeDiagnoser() {}
8469 };
8470
8471 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8472 protected:
8473 unsigned DiagID;
8474 std::tuple<const Ts &...> Args;
8475
8476 template <std::size_t... Is>
8477 void emit(const SemaDiagnosticBuilder &DB,
8478 std::index_sequence<Is...>) const {
8479 // Apply all tuple elements to the builder in order.
8480 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8481 (void)Dummy;
8482 }
8483
8484 public:
8485 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8486 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8487 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8488 }
8489
8490 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8491 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8492 emit(DB, std::index_sequence_for<Ts...>());
8493 DB << T;
8494 }
8495 };
8496
8497 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8498 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8499 /// For example, a diagnostic with no other parameters would generally have
8500 /// the form "...%select{incomplete|sizeless}0 type %1...".
8501 template <typename... Ts>
8502 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8503 public:
8504 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8505 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8506
8507 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8508 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8509 this->emit(DB, std::index_sequence_for<Ts...>());
8510 DB << T->isSizelessType() << T;
8511 }
8512 };
8513
8514 /// Check an argument list for placeholders that we won't try to
8515 /// handle later.
8516 bool CheckArgsForPlaceholders(MultiExprArg args);
8517
8518 /// The C++ "std::source_location::__impl" struct, defined in
8519 /// \<source_location>.
8520 RecordDecl *StdSourceLocationImplDecl;
8521
8522 /// A stack of expression evaluation contexts.
8523 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8524
8525 // Set of failed immediate invocations to avoid double diagnosing.
8526 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8527
8528 /// List of SourceLocations where 'self' is implicitly retained inside a
8529 /// block.
8530 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8531 ImplicitlyRetainedSelfLocs;
8532
8533 /// Do an explicit extend of the given block pointer if we're in ARC.
8534 void maybeExtendBlockObject(ExprResult &E);
8535
8536 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8537 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8538 void DiagnosePrecisionLossInComplexDivision();
8539
8540private:
8541 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8542
8543 /// Maps the size expression of each VLA type created inside a function,
8544 /// block or lambda to the context in which that size is evaluated.
8545 llvm::DenseMap<const Expr *, const DeclContext *> VLASizeExprOwners;
8546
8547 /// Methods for marking which expressions involve dereferencing a pointer
8548 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8549 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8550 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8551 /// `*p`, but need to check that `address of` is called on it. This requires
8552 /// keeping a container of all pending expressions and checking if the address
8553 /// of them are eventually taken.
8554 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8555 void CheckAddressOfNoDeref(const Expr *E);
8556
8557 ///@}
8558
8559 //
8560 //
8561 // -------------------------------------------------------------------------
8562 //
8563 //
8564
8565 /// \name C++ Expressions
8566 /// Implementations are in SemaExprCXX.cpp
8567 ///@{
8568
8569public:
8570 /// The C++ "std::bad_alloc" class, which is defined by the C++
8571 /// standard library.
8572 LazyDeclPtr StdBadAlloc;
8573
8574 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8575 /// standard library.
8576 LazyDeclPtr StdAlignValT;
8577
8578 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8579 RecordDecl *CXXTypeInfoDecl;
8580
8581 /// A flag to remember whether the implicit forms of operator new and delete
8582 /// have been declared.
8583 bool GlobalNewDeleteDeclared;
8584
8585 /// Delete-expressions to be analyzed at the end of translation unit
8586 ///
8587 /// This list contains class members, and locations of delete-expressions
8588 /// that could not be proven as to whether they mismatch with new-expression
8589 /// used in initializer of the field.
8590 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8591
8592 /// Handle the result of the special case name lookup for inheriting
8593 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8594 /// constructor names in member using declarations, even if 'X' is not the
8595 /// name of the corresponding type.
8596 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8597 SourceLocation NameLoc,
8598 const IdentifierInfo &Name);
8599
8600 ParsedType getConstructorName(const IdentifierInfo &II,
8601 SourceLocation NameLoc, Scope *S,
8602 CXXScopeSpec &SS, bool EnteringContext);
8603 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8604 Scope *S, CXXScopeSpec &SS,
8605 ParsedType ObjectType, bool EnteringContext);
8606
8607 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8608 ParsedType ObjectType);
8609
8610 /// Build a C++ typeid expression with a type operand.
8611 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8612 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8613
8614 /// Build a C++ typeid expression with an expression operand.
8615 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8616 Expr *Operand, SourceLocation RParenLoc);
8617
8618 /// ActOnCXXTypeid - Parse typeid( something ).
8619 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8620 bool isType, void *TyOrExpr,
8621 SourceLocation RParenLoc);
8622
8623 /// Build a Microsoft __uuidof expression with a type operand.
8624 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8625 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8626
8627 /// Build a Microsoft __uuidof expression with an expression operand.
8628 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8629 Expr *Operand, SourceLocation RParenLoc);
8630
8631 /// ActOnCXXUuidof - Parse __uuidof( something ).
8632 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8633 bool isType, void *TyOrExpr,
8634 SourceLocation RParenLoc);
8635
8636 //// ActOnCXXThis - Parse 'this' pointer.
8637 ExprResult ActOnCXXThis(SourceLocation Loc);
8638
8639 /// Check whether the type of 'this' is valid in the current context.
8640 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8641
8642 /// Build a CXXThisExpr and mark it referenced in the current context.
8643 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8644 void MarkThisReferenced(CXXThisExpr *This);
8645
8646 /// Try to retrieve the type of the 'this' pointer.
8647 ///
8648 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8649 QualType getCurrentThisType();
8650
8651 /// When non-NULL, the C++ 'this' expression is allowed despite the
8652 /// current context not being a non-static member function. In such cases,
8653 /// this provides the type used for 'this'.
8654 QualType CXXThisTypeOverride;
8655
8656 /// RAII object used to temporarily allow the C++ 'this' expression
8657 /// to be used, with the given qualifiers on the current class type.
8658 class CXXThisScopeRAII {
8659 Sema &S;
8660 QualType OldCXXThisTypeOverride;
8661 bool Enabled;
8662
8663 public:
8664 /// Introduce a new scope where 'this' may be allowed (when enabled),
8665 /// using the given declaration (which is either a class template or a
8666 /// class) along with the given qualifiers.
8667 /// along with the qualifiers placed on '*this'.
8668 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8669 bool Enabled = true);
8670
8671 ~CXXThisScopeRAII();
8672 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8673 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8674 };
8675
8676 /// Make sure the value of 'this' is actually available in the current
8677 /// context, if it is a potentially evaluated context.
8678 ///
8679 /// \param Loc The location at which the capture of 'this' occurs.
8680 ///
8681 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8682 /// capture list.
8683 ///
8684 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8685 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8686 /// This is useful when enclosing lambdas must speculatively capture
8687 /// 'this' that may or may not be used in certain specializations of
8688 /// a nested generic lambda (depending on whether the name resolves to
8689 /// a non-static member function or a static function).
8690 /// \return returns 'true' if failed, 'false' if success.
8691 bool CheckCXXThisCapture(
8692 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8693 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8694 bool ByCopy = false);
8695
8696 /// Determine whether the given type is the type of *this that is used
8697 /// outside of the body of a member function for a type that is currently
8698 /// being defined.
8699 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8700
8701 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8702 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8703
8704 /// Build a boolean-typed literal expression.
8705 ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value);
8706
8707 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8708 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8709
8710 //// ActOnCXXThrow - Parse throw expressions.
8711 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8712 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8713 bool IsThrownVarInScope);
8714
8715 /// CheckCXXThrowOperand - Validate the operand of a throw.
8716 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8717
8718 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8719 /// Can be interpreted either as function-style casting ("int(x)")
8720 /// or class type construction ("ClassType(x,y,z)")
8721 /// or creation of a value-initialized type ("int()").
8722 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8723 SourceLocation LParenOrBraceLoc,
8724 MultiExprArg Exprs,
8725 SourceLocation RParenOrBraceLoc,
8726 bool ListInitialization);
8727
8728 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8729 SourceLocation LParenLoc,
8730 MultiExprArg Exprs,
8731 SourceLocation RParenLoc,
8732 bool ListInitialization);
8733
8734 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8735 ///
8736 /// E.g.:
8737 /// @code new (memory) int[size][4] @endcode
8738 /// or
8739 /// @code ::new Foo(23, "hello") @endcode
8740 ///
8741 /// \param StartLoc The first location of the expression.
8742 /// \param UseGlobal True if 'new' was prefixed with '::'.
8743 /// \param PlacementLParen Opening paren of the placement arguments.
8744 /// \param PlacementArgs Placement new arguments.
8745 /// \param PlacementRParen Closing paren of the placement arguments.
8746 /// \param TypeIdParens If the type is in parens, the source range.
8747 /// \param D The type to be allocated, as well as array dimensions.
8748 /// \param Initializer The initializing expression or initializer-list, or
8749 /// null if there is none.
8750 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8751 SourceLocation PlacementLParen,
8752 MultiExprArg PlacementArgs,
8753 SourceLocation PlacementRParen,
8754 SourceRange TypeIdParens, Declarator &D,
8755 Expr *Initializer);
8756 ExprResult
8757 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8758 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8759 SourceRange TypeIdParens, QualType AllocType,
8760 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8761 SourceRange DirectInitRange, Expr *Initializer);
8762
8763 /// Determine whether \p FD is an aligned allocation or deallocation
8764 /// function that is unavailable.
8765 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8766
8767 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8768 /// function that is unavailable.
8769 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8770 SourceLocation Loc);
8771
8772 /// Checks that a type is suitable as the allocated type
8773 /// in a new-expression.
8774 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8775 SourceRange R);
8776
8777 /// Finds the overloads of operator new and delete that are appropriate
8778 /// for the allocation.
8779 std::optional<ResolvedAllocation> FindAllocationFunctions(
8780 SourceLocation StartLoc, SourceRange Range,
8781 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8782 QualType AllocType, bool IsArray, const ImplicitAllocationParameters &IAP,
8783 MultiExprArg PlaceArgs, bool Diagnose = true);
8784
8785 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8786 /// delete. These are:
8787 /// @code
8788 /// // C++03:
8789 /// void* operator new(std::size_t) throw(std::bad_alloc);
8790 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8791 /// void operator delete(void *) throw();
8792 /// void operator delete[](void *) throw();
8793 /// // C++11:
8794 /// void* operator new(std::size_t);
8795 /// void* operator new[](std::size_t);
8796 /// void operator delete(void *) noexcept;
8797 /// void operator delete[](void *) noexcept;
8798 /// // C++1y:
8799 /// void* operator new(std::size_t);
8800 /// void* operator new[](std::size_t);
8801 /// void operator delete(void *) noexcept;
8802 /// void operator delete[](void *) noexcept;
8803 /// void operator delete(void *, std::size_t) noexcept;
8804 /// void operator delete[](void *, std::size_t) noexcept;
8805 /// @endcode
8806 /// Note that the placement and nothrow forms of new are *not* implicitly
8807 /// declared. Their use requires including \<new\>.
8808 void DeclareGlobalNewDelete();
8809 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8810 ArrayRef<QualType> Params);
8811
8812 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8813 DeclarationName Name, FunctionDecl *&Operator,
8814 ImplicitDeallocationParameters,
8815 bool Diagnose = true);
8816 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8817 ImplicitDeallocationParameters,
8818 DeclarationName Name,
8819 bool Diagnose = true);
8820 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8821 CXXRecordDecl *RD,
8822 bool Diagnose,
8823 bool LookForGlobal,
8824 DeclarationName Name);
8825
8826 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8827 /// @code ::delete ptr; @endcode
8828 /// or
8829 /// @code delete [] ptr; @endcode
8830 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8831 bool ArrayForm, Expr *Operand);
8832 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8833 bool IsDelete, bool CallCanBeVirtual,
8834 bool WarnOnNonAbstractTypes,
8835 SourceLocation DtorLoc);
8836
8837 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8838 Expr *Operand, SourceLocation RParen);
8839 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8840 SourceLocation RParen);
8841
8842 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8843 SourceLocation OpLoc,
8844 tok::TokenKind OpKind,
8845 ParsedType &ObjectType,
8846 bool &MayBePseudoDestructor);
8847
8848 ExprResult BuildPseudoDestructorExpr(
8849 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8850 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8851 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8852
8853 ExprResult ActOnPseudoDestructorExpr(
8854 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8855 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8856 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8857
8858 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8859 SourceLocation OpLoc,
8860 tok::TokenKind OpKind,
8861 SourceLocation TildeLoc,
8862 const DeclSpec &DS);
8863
8864 /// MaybeCreateExprWithCleanups - If the current full-expression
8865 /// requires any cleanups, surround it with a ExprWithCleanups node.
8866 /// Otherwise, just returns the passed-in expression.
8867 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8868 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8869 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8870
8871 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8872 return ActOnFinishFullExpr(
8873 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8874 }
8875 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8876 bool DiscardedValue, bool IsConstexpr = false,
8877 bool IsTemplateArgument = false);
8878 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8879
8880 /// Process the expression contained within a decltype. For such expressions,
8881 /// certain semantic checks on temporaries are delayed until this point, and
8882 /// are omitted for the 'topmost' call in the decltype expression. If the
8883 /// topmost call bound a temporary, strip that temporary off the expression.
8884 ExprResult ActOnDecltypeExpression(Expr *E);
8885
8886 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8887 bool IsUDSuffix);
8888
8889 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8890
8891 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8892 SourceLocation StmtLoc,
8893 ConditionKind CK);
8894
8895 /// Check the use of the given variable as a C++ condition in an if,
8896 /// while, do-while, or switch statement.
8897 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8898 SourceLocation StmtLoc, ConditionKind CK);
8899
8900 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8901 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8902
8903 /// Helper function to determine whether this is the (deprecated) C++
8904 /// conversion from a string literal to a pointer to non-const char or
8905 /// non-const wchar_t (for narrow and wide string literals,
8906 /// respectively).
8907 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8908
8909 /// PerformImplicitConversion - Perform an implicit conversion of the
8910 /// expression From to the type ToType using the pre-computed implicit
8911 /// conversion sequence ICS. Returns the converted
8912 /// expression. Action is the kind of conversion we're performing,
8913 /// used in the error message.
8914 ExprResult PerformImplicitConversion(
8915 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8916 AssignmentAction Action,
8917 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8918
8919 /// PerformImplicitConversion - Perform an implicit conversion of the
8920 /// expression From to the type ToType by following the standard
8921 /// conversion sequence SCS. Returns the converted
8922 /// expression. Flavor is the context in which we're performing this
8923 /// conversion, for use in error messages.
8924 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8925 const StandardConversionSequence &SCS,
8926 AssignmentAction Action,
8927 CheckedConversionKind CCK);
8928
8929 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8930
8931 /// Parsed one of the type trait support pseudo-functions.
8932 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8933 ArrayRef<ParsedType> Args,
8934 SourceLocation RParenLoc);
8935 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8936 ArrayRef<TypeSourceInfo *> Args,
8937 SourceLocation RParenLoc);
8938
8939 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8940 /// pseudo-functions.
8941 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8942 ParsedType LhsTy, Expr *DimExpr,
8943 SourceLocation RParen);
8944
8945 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8946 TypeSourceInfo *TSInfo, Expr *DimExpr,
8947 SourceLocation RParen);
8948
8949 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8950 /// pseudo-functions.
8951 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8952 Expr *Queried, SourceLocation RParen);
8953
8954 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8955 Expr *Queried, SourceLocation RParen);
8956
8957 QualType CheckPointerToMemberOperands( // C++ 5.5
8958 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8959 bool isIndirect);
8960 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8961 ExprResult &RHS,
8962 SourceLocation QuestionLoc);
8963
8964 //// Determines if a type is trivially relocatable
8965 /// according to the C++26 rules.
8966 // FIXME: This is in Sema because it requires
8967 // overload resolution, can we move to ASTContext?
8968 bool IsCXXTriviallyRelocatableType(QualType T);
8969 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8970
8971 /// Check the operands of ?: under C++ semantics.
8972 ///
8973 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8974 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8975 ///
8976 /// This function also implements GCC's vector extension and the
8977 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8978 /// permit the use of a?b:c where the type of a is that of a integer vector
8979 /// with the same number of elements and size as the vectors of b and c. If
8980 /// one of either b or c is a scalar it is implicitly converted to match the
8981 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8982 /// c are scalars, then b and c are checked and converted to the type of a if
8983 /// possible.
8984 ///
8985 /// The expressions are evaluated differently for GCC's and OpenCL's
8986 /// extensions. For the GCC extension, the ?: operator is evaluated as
8987 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8988 /// For the OpenCL extensions, the ?: operator is evaluated as
8989 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8990 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8991 QualType CXXCheckConditionalOperands( // C++ 5.16
8992 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8993 ExprObjectKind &OK, SourceLocation questionLoc);
8994
8995 /// Find a merged pointer type and convert the two expressions to it.
8996 ///
8997 /// This finds the composite pointer type for \p E1 and \p E2 according to
8998 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8999 /// it. It does not emit diagnostics (FIXME: that's not true if \p
9000 /// ConvertArgs is \c true).
9001 ///
9002 /// \param Loc The location of the operator requiring these two expressions to
9003 /// be converted to the composite pointer type.
9004 ///
9005 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
9006 /// type.
9007 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9008 bool ConvertArgs = true);
9009 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
9010 ExprResult &E2, bool ConvertArgs = true) {
9011 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9012 QualType Composite =
9013 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
9014 E1 = E1Tmp;
9015 E2 = E2Tmp;
9016 return Composite;
9017 }
9018
9019 /// MaybeBindToTemporary - If the passed in expression has a record type with
9020 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
9021 /// it simply returns the passed in expression.
9022 ExprResult MaybeBindToTemporary(Expr *E);
9023
9024 /// IgnoredValueConversions - Given that an expression's result is
9025 /// syntactically ignored, perform any conversions that are
9026 /// required.
9027 ExprResult IgnoredValueConversions(Expr *E);
9028
9029 ExprResult CheckUnevaluatedOperand(Expr *E);
9030
9031 IfExistsResult
9032 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
9033 const DeclarationNameInfo &TargetNameInfo);
9034
9035 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
9036 SourceLocation KeywordLoc,
9037 bool IsIfExists, CXXScopeSpec &SS,
9038 UnqualifiedId &Name);
9039
9040 RequiresExprBodyDecl *
9041 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
9042 ArrayRef<ParmVarDecl *> LocalParameters,
9043 Scope *BodyScope);
9044 void ActOnFinishRequiresExpr();
9045 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
9046 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
9047 CXXScopeSpec &SS,
9048 SourceLocation NameLoc,
9049 const IdentifierInfo *TypeName,
9050 TemplateIdAnnotation *TemplateId);
9051 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
9052 SourceLocation NoexceptLoc);
9053 concepts::Requirement *ActOnCompoundRequirement(
9054 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9055 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
9056 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
9057 concepts::ExprRequirement *BuildExprRequirement(
9058 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
9059 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
9060 concepts::ExprRequirement *BuildExprRequirement(
9061 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
9062 bool IsSatisfied, SourceLocation NoexceptLoc,
9063 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
9064 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
9065 concepts::TypeRequirement *BuildTypeRequirement(
9066 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
9067 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
9068 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
9069 RequiresExprBodyDecl *Body,
9070 SourceLocation LParenLoc,
9071 ArrayRef<ParmVarDecl *> LocalParameters,
9072 SourceLocation RParenLoc,
9073 ArrayRef<concepts::Requirement *> Requirements,
9074 SourceLocation ClosingBraceLoc);
9075
9076private:
9077 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
9078 bool IsDelete);
9079
9080 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
9081 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
9082 bool DeleteWasArrayForm);
9083
9084 std::optional<AllocationArgumentSet>
9085 resolveAllocationArguments(LookupResult &R,
9086 const ImplicitAllocationParameters &,
9087 ArrayRef<Expr *> PlacementArguments);
9088
9089 // Attempts to construct the type identity argument for the call to a
9090 // type aware operator new. Returns null on failure.
9091 Expr *tryGetTypeIdentityArgument(QualType Type, SourceLocation);
9092
9093 Expr *AllocationSizeExpr = nullptr;
9094 Expr *AllocationAlignmentExpr = nullptr;
9095 llvm::DenseMap<QualType, Expr *> AllocationTypeIdentityArguments;
9096
9097 ///@}
9098
9099 //
9100 //
9101 // -------------------------------------------------------------------------
9102 //
9103 //
9104
9105 /// \name Member Access Expressions
9106 /// Implementations are in SemaExprMember.cpp
9107 ///@{
9108
9109public:
9110 /// Check whether an expression might be an implicit class member access.
9111 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
9112 bool IsAddressOfOperand);
9113
9114 /// Builds an expression which might be an implicit member expression.
9115 ExprResult BuildPossibleImplicitMemberExpr(
9116 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
9117 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
9118
9119 /// Builds an implicit member access expression. The current context
9120 /// is known to be an instance method, and the given unqualified lookup
9121 /// set is known to contain only instance members, at least one of which
9122 /// is from an appropriate type.
9123 ExprResult
9124 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9125 LookupResult &R,
9126 const TemplateArgumentListInfo *TemplateArgs,
9127 bool IsDefiniteInstance, const Scope *S);
9128
9129 ExprResult ActOnDependentMemberExpr(
9130 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
9131 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9132 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9133 const TemplateArgumentListInfo *TemplateArgs);
9134
9135 /// The main callback when the parser finds something like
9136 /// expression . [nested-name-specifier] identifier
9137 /// expression -> [nested-name-specifier] identifier
9138 /// where 'identifier' encompasses a fairly broad spectrum of
9139 /// possibilities, including destructor and operator references.
9140 ///
9141 /// \param OpKind either tok::arrow or tok::period
9142 /// \param ObjCImpDecl the current Objective-C \@implementation
9143 /// decl; this is an ugly hack around the fact that Objective-C
9144 /// \@implementations aren't properly put in the context chain
9145 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
9146 tok::TokenKind OpKind, CXXScopeSpec &SS,
9147 SourceLocation TemplateKWLoc,
9148 UnqualifiedId &Member, Decl *ObjCImpDecl);
9149
9150 MemberExpr *
9151 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9152 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9153 ValueDecl *Member, DeclAccessPair FoundDecl,
9154 bool HadMultipleCandidates,
9155 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9156 ExprValueKind VK, ExprObjectKind OK,
9157 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9158
9159 // Check whether the declarations we found through a nested-name
9160 // specifier in a member expression are actually members of the base
9161 // type. The restriction here is:
9162 //
9163 // C++ [expr.ref]p2:
9164 // ... In these cases, the id-expression shall name a
9165 // member of the class or of one of its base classes.
9166 //
9167 // So it's perfectly legitimate for the nested-name specifier to name
9168 // an unrelated class, and for us to find an overload set including
9169 // decls from classes which are not superclasses, as long as the decl
9170 // we actually pick through overload resolution is from a superclass.
9171 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9172 const CXXScopeSpec &SS,
9173 const LookupResult &R);
9174
9175 // This struct is for use by ActOnMemberAccess to allow
9176 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9177 // changing the access operator from a '.' to a '->' (to see if that is the
9178 // change needed to fix an error about an unknown member, e.g. when the class
9179 // defines a custom operator->).
9180 struct ActOnMemberAccessExtraArgs {
9181 Scope *S;
9182 UnqualifiedId &Id;
9183 Decl *ObjCImpDecl;
9184 };
9185
9186 ExprResult BuildMemberReferenceExpr(
9187 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9188 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9189 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9190 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9191 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9192
9193 ExprResult
9194 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9195 bool IsArrow, const CXXScopeSpec &SS,
9196 SourceLocation TemplateKWLoc,
9197 NamedDecl *FirstQualifierInScope, LookupResult &R,
9198 const TemplateArgumentListInfo *TemplateArgs,
9199 const Scope *S, bool SuppressQualifierCheck = false,
9200 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9201
9202 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9203 SourceLocation OpLoc,
9204 const CXXScopeSpec &SS, FieldDecl *Field,
9205 DeclAccessPair FoundDecl,
9206 const DeclarationNameInfo &MemberNameInfo);
9207
9208 /// Perform conversions on the LHS of a member access expression.
9209 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9210
9211 ExprResult BuildAnonymousStructUnionMemberReference(
9212 const CXXScopeSpec &SS, SourceLocation nameLoc,
9213 IndirectFieldDecl *indirectField,
9214 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9215 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9216
9217private:
9218 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9219
9220 ///@}
9221
9222 //
9223 //
9224 // -------------------------------------------------------------------------
9225 //
9226 //
9227
9228 /// \name Initializers
9229 /// Implementations are in SemaInit.cpp
9230 ///@{
9231
9232public:
9233 /// Stack of types that correspond to the parameter entities that are
9234 /// currently being copy-initialized. Can be empty.
9235 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9236
9237 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9238 AggregateDeductionCandidates;
9239
9240 bool IsStringInit(Expr *Init, const ArrayType *AT);
9241
9242 /// The initializers of \p ILE with each multi-element EmbedExpr split into
9243 /// one EmbedExpr per embedded element; \p Storage is used only if needed.
9244 MultiExprArg getInitsWithEmbedExpanded(InitListExpr *ILE,
9245 SmallVectorImpl<Expr *> &Storage);
9246
9247 /// Determine whether we can perform aggregate initialization for the purposes
9248 /// of overload resolution.
9249 bool CanPerformAggregateInitializationForOverloadResolution(
9250 const InitializedEntity &Entity, InitListExpr *From);
9251
9252 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9253 SourceLocation EqualOrColonLoc,
9254 bool GNUSyntax, ExprResult Init);
9255
9256 /// Check that the lifetime of the initializer (and its subobjects) is
9257 /// sufficient for initializing the entity, and perform lifetime extension
9258 /// (when permitted) if not.
9259 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9260
9261 MaterializeTemporaryExpr *
9262 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9263 bool BoundToLvalueReference);
9264
9265 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9266 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9267 /// we don't have xvalues there.
9268 ExprResult TemporaryMaterializationConversion(Expr *E);
9269
9270 ExprResult PerformQualificationConversion(
9271 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9272 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9273
9274 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9275 ExprResult Init);
9276 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9277 SourceLocation EqualLoc, ExprResult Init,
9278 bool TopLevelOfInitList = false,
9279 bool AllowExplicit = false);
9280
9281 QualType DeduceTemplateSpecializationFromInitializer(
9282 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9283 const InitializationKind &Kind, MultiExprArg Init);
9284
9285 ///@}
9286
9287 //
9288 //
9289 // -------------------------------------------------------------------------
9290 //
9291 //
9292
9293 /// \name C++ Lambda Expressions
9294 /// Implementations are in SemaLambda.cpp
9295 ///@{
9296
9297public:
9298 /// Create a new lambda closure type.
9299 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9300 TypeSourceInfo *Info,
9301 unsigned LambdaDependencyKind,
9302 LambdaCaptureDefault CaptureDefault);
9303
9304 /// Number lambda for linkage purposes if necessary.
9305 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9306 std::optional<CXXRecordDecl::LambdaNumbering>
9307 NumberingOverride = std::nullopt);
9308
9309 /// Endow the lambda scope info with the relevant properties.
9310 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9311 SourceRange IntroducerRange,
9312 LambdaCaptureDefault CaptureDefault,
9313 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9314 bool Mutable);
9315
9316 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9317 CXXRecordDecl *Class);
9318
9319 void AddTemplateParametersToLambdaCallOperator(
9320 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9321 TemplateParameterList *TemplateParams);
9322
9323 void
9324 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9325 SourceLocation CallOperatorLoc,
9326 const AssociatedConstraint &TrailingRequiresClause,
9327 TypeSourceInfo *MethodTyInfo,
9328 ConstexprSpecKind ConstexprKind, StorageClass SC,
9329 ArrayRef<ParmVarDecl *> Params,
9330 bool HasExplicitResultType);
9331
9332 /// Returns true if the explicit object parameter was invalid.
9333 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9334 SourceLocation CallLoc);
9335
9336 /// Perform initialization analysis of the init-capture and perform
9337 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9338 /// not being used to initialize a reference.
9339 ParsedType actOnLambdaInitCaptureInitialization(
9340 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9341 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9342 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9343 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9344 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9345 }
9346 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9347 SourceLocation EllipsisLoc,
9348 UnsignedOrNone NumExpansions,
9349 IdentifierInfo *Id,
9350 bool DirectInit, Expr *&Init);
9351
9352 /// Create a dummy variable within the declcontext of the lambda's
9353 /// call operator, for name lookup purposes for a lambda init capture.
9354 ///
9355 /// CodeGen handles emission of lambda captures, ignoring these dummy
9356 /// variables appropriately.
9357 VarDecl *createLambdaInitCaptureVarDecl(
9358 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9359 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9360
9361 /// Add an init-capture to a lambda scope.
9362 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9363
9364 /// Note that we have finished the explicit captures for the
9365 /// given lambda.
9366 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9367
9368 /// Deduce a block or lambda's return type based on the return
9369 /// statements present in the body.
9370 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9371
9372 /// Once the Lambdas capture are known, we can start to create the closure,
9373 /// call operator method, and keep track of the captures.
9374 /// We do the capture lookup here, but they are not actually captured until
9375 /// after we know what the qualifiers of the call operator are.
9376 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9377 Scope *CurContext);
9378
9379 /// This is called after parsing the explicit template parameter list
9380 /// on a lambda (if it exists) in C++2a.
9381 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9382 SourceLocation LAngleLoc,
9383 ArrayRef<NamedDecl *> TParams,
9384 SourceLocation RAngleLoc,
9385 ExprResult RequiresClause);
9386
9387 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9388 SourceLocation MutableLoc);
9389
9390 void ActOnLambdaClosureParameters(
9391 Scope *LambdaScope,
9392 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9393
9394 /// ActOnStartOfLambdaDefinition - This is called just before we start
9395 /// parsing the body of a lambda; it analyzes the explicit captures and
9396 /// arguments, and sets up various data-structures for the body of the
9397 /// lambda.
9398 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9399 Declarator &ParamInfo, const DeclSpec &DS);
9400
9401 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9402 /// is invoked to pop the information about the lambda.
9403 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9404 bool IsInstantiation = false);
9405
9406 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9407 /// was successfully completed.
9408 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9409
9410 /// Does copying/destroying the captured variable have side effects?
9411 bool CaptureHasSideEffects(const sema::Capture &From);
9412
9413 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9414 /// diagnostic is emitted.
9415 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9416 SourceRange FixItRange,
9417 const sema::Capture &From);
9418
9419 /// Build a FieldDecl suitable to hold the given capture.
9420 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture,
9421 bool IsOpenMP = false);
9422
9423 /// Initialize the given capture with a suitable expression.
9424 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9425 SourceLocation ImplicitCaptureLoc,
9426 bool IsOpenMPMapping = false);
9427
9428 /// Complete a lambda-expression having processed and attached the
9429 /// lambda body.
9430 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9431
9432 /// Get the return type to use for a lambda's conversion function(s) to
9433 /// function pointer type, given the type of the call operator.
9434 QualType
9435 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9436 CallingConv CC);
9437
9438 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9439 SourceLocation ConvLocation,
9440 CXXConversionDecl *Conv, Expr *Src);
9441
9442 class LambdaScopeForCallOperatorInstantiationRAII
9443 : private FunctionScopeRAII {
9444 public:
9445 LambdaScopeForCallOperatorInstantiationRAII(
9446 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9447 LocalInstantiationScope &Scope,
9448 bool ShouldAddDeclsFromParentScope = true);
9449 };
9450
9451 /// Compute the mangling number context for a lambda expression or
9452 /// block literal. Also return the extra mangling decl if any.
9453 ///
9454 /// \param DC - The DeclContext containing the lambda expression or
9455 /// block literal.
9456 std::tuple<MangleNumberingContext *, Decl *>
9457 getCurrentMangleNumberContext(const DeclContext *DC);
9458
9459 ///@}
9460
9461 //
9462 //
9463 // -------------------------------------------------------------------------
9464 //
9465 //
9466
9467 /// \name Name Lookup
9468 ///
9469 /// These routines provide name lookup that is used during semantic
9470 /// analysis to resolve the various kinds of names (identifiers,
9471 /// overloaded operator names, constructor names, etc.) into zero or
9472 /// more declarations within a particular scope. The major entry
9473 /// points are LookupName, which performs unqualified name lookup,
9474 /// and LookupQualifiedName, which performs qualified name lookup.
9475 ///
9476 /// All name lookup is performed based on some specific criteria,
9477 /// which specify what names will be visible to name lookup and how
9478 /// far name lookup should work. These criteria are important both
9479 /// for capturing language semantics (certain lookups will ignore
9480 /// certain names, for example) and for performance, since name
9481 /// lookup is often a bottleneck in the compilation of C++. Name
9482 /// lookup criteria is specified via the LookupCriteria enumeration.
9483 ///
9484 /// The results of name lookup can vary based on the kind of name
9485 /// lookup performed, the current language, and the translation
9486 /// unit. In C, for example, name lookup will either return nothing
9487 /// (no entity found) or a single declaration. In C++, name lookup
9488 /// can additionally refer to a set of overloaded functions or
9489 /// result in an ambiguity. All of the possible results of name
9490 /// lookup are captured by the LookupResult class, which provides
9491 /// the ability to distinguish among them.
9492 ///
9493 /// Implementations are in SemaLookup.cpp
9494 ///@{
9495
9496public:
9497 /// Tracks whether we are in a context where typo correction is
9498 /// disabled.
9499 bool DisableTypoCorrection;
9500
9501 /// The number of typos corrected by CorrectTypo.
9502 unsigned TyposCorrected;
9503
9504 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9505 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9506
9507 /// A cache containing identifiers for which typo correction failed and
9508 /// their locations, so that repeated attempts to correct an identifier in a
9509 /// given location are ignored if typo correction already failed for it.
9510 IdentifierSourceLocations TypoCorrectionFailures;
9511
9512 /// SpecialMemberOverloadResult - The overloading result for a special member
9513 /// function.
9514 ///
9515 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9516 /// integer are used to determine whether overload resolution succeeded.
9517 class SpecialMemberOverloadResult {
9518 public:
9519 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9520
9521 private:
9522 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9523
9524 public:
9525 SpecialMemberOverloadResult() {}
9526 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9527 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9528
9529 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9530 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9531
9532 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9533 void setKind(Kind K) { Pair.setInt(K); }
9534 };
9535
9536 using SpecialMemberCacheKey = std::pair<const CXXRecordDecl *, unsigned>;
9537
9538 /// A cache of special member function overload resolution results
9539 /// for C++ records.
9540 llvm::DenseMap<SpecialMemberCacheKey, SpecialMemberOverloadResult>
9541 SpecialMemberCache;
9542
9543 enum class AcceptableKind { Visible, Reachable };
9544
9545 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9546 // TODO: make this is a typesafe union.
9547 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9548 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9549
9550 /// Describes the kind of name lookup to perform.
9551 enum LookupNameKind {
9552 /// Ordinary name lookup, which finds ordinary names (functions,
9553 /// variables, typedefs, etc.) in C and most kinds of names
9554 /// (functions, variables, members, types, etc.) in C++.
9555 LookupOrdinaryName = 0,
9556 /// Tag name lookup, which finds the names of enums, classes,
9557 /// structs, and unions.
9558 LookupTagName,
9559 /// Label name lookup.
9560 LookupLabel,
9561 /// Member name lookup, which finds the names of
9562 /// class/struct/union members.
9563 LookupMemberName,
9564 /// Look up of an operator name (e.g., operator+) for use with
9565 /// operator overloading. This lookup is similar to ordinary name
9566 /// lookup, but will ignore any declarations that are class members.
9567 LookupOperatorName,
9568 /// Look up a name following ~ in a destructor name. This is an ordinary
9569 /// lookup, but prefers tags to typedefs.
9570 LookupDestructorName,
9571 /// Look up of a name that precedes the '::' scope resolution
9572 /// operator in C++. This lookup completely ignores operator, object,
9573 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9574 LookupNestedNameSpecifierName,
9575 /// Look up a namespace name within a C++ using directive or
9576 /// namespace alias definition, ignoring non-namespace names (C++
9577 /// [basic.lookup.udir]p1).
9578 LookupNamespaceName,
9579 /// Look up all declarations in a scope with the given name,
9580 /// including resolved using declarations. This is appropriate
9581 /// for checking redeclarations for a using declaration.
9582 LookupUsingDeclName,
9583 /// Look up an ordinary name that is going to be redeclared as a
9584 /// name with linkage. This lookup ignores any declarations that
9585 /// are outside of the current scope unless they have linkage. See
9586 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9587 LookupRedeclarationWithLinkage,
9588 /// Look up a friend of a local class. This lookup does not look
9589 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9590 LookupLocalFriendName,
9591 /// Look up the name of an Objective-C protocol.
9592 LookupObjCProtocolName,
9593 /// Look up implicit 'self' parameter of an objective-c method.
9594 LookupObjCImplicitSelfParam,
9595 /// Look up the name of an OpenMP user-defined reduction operation.
9596 LookupOMPReductionName,
9597 /// Look up the name of an OpenMP user-defined mapper.
9598 LookupOMPMapperName,
9599 /// Look up any declaration with any name.
9600 LookupAnyName
9601 };
9602
9603 /// The possible outcomes of name lookup for a literal operator.
9604 enum LiteralOperatorLookupResult {
9605 /// The lookup resulted in an error.
9606 LOLR_Error,
9607 /// The lookup found no match but no diagnostic was issued.
9608 LOLR_ErrorNoDiagnostic,
9609 /// The lookup found a single 'cooked' literal operator, which
9610 /// expects a normal literal to be built and passed to it.
9611 LOLR_Cooked,
9612 /// The lookup found a single 'raw' literal operator, which expects
9613 /// a string literal containing the spelling of the literal token.
9614 LOLR_Raw,
9615 /// The lookup found an overload set of literal operator templates,
9616 /// which expect the characters of the spelling of the literal token to be
9617 /// passed as a non-type template argument pack.
9618 LOLR_Template,
9619 /// The lookup found an overload set of literal operator templates,
9620 /// which expect the character type and characters of the spelling of the
9621 /// string literal token to be passed as template arguments.
9622 LOLR_StringTemplatePack,
9623 };
9624
9625 SpecialMemberOverloadResult
9626 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9627 bool VolatileArg, bool RValueThis, bool ConstThis,
9628 bool VolatileThis);
9629
9630 RedeclarationKind forRedeclarationInCurContext() const;
9631
9632 /// Look up a name, looking for a single declaration. Return
9633 /// null if the results were absent, ambiguous, or overloaded.
9634 ///
9635 /// It is preferable to use the elaborated form and explicitly handle
9636 /// ambiguity and overloaded.
9637 NamedDecl *LookupSingleName(
9638 Scope *S, DeclarationName Name, SourceLocation Loc,
9639 LookupNameKind NameKind,
9640 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9641
9642 /// Lookup a builtin function, when name lookup would otherwise
9643 /// fail.
9644 bool LookupBuiltin(LookupResult &R);
9645 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9646
9647 /// Perform unqualified name lookup starting from a given
9648 /// scope.
9649 ///
9650 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9651 /// used to find names within the current scope. For example, 'x' in
9652 /// @code
9653 /// int x;
9654 /// int f() {
9655 /// return x; // unqualified name look finds 'x' in the global scope
9656 /// }
9657 /// @endcode
9658 ///
9659 /// Different lookup criteria can find different names. For example, a
9660 /// particular scope can have both a struct and a function of the same
9661 /// name, and each can be found by certain lookup criteria. For more
9662 /// information about lookup criteria, see the documentation for the
9663 /// class LookupCriteria.
9664 ///
9665 /// @param S The scope from which unqualified name lookup will
9666 /// begin. If the lookup criteria permits, name lookup may also search
9667 /// in the parent scopes.
9668 ///
9669 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9670 /// look up and the lookup kind), and is updated with the results of lookup
9671 /// including zero or more declarations and possibly additional information
9672 /// used to diagnose ambiguities.
9673 ///
9674 /// @returns \c true if lookup succeeded and false otherwise.
9675 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9676 bool ForceNoCPlusPlus = false);
9677
9678 /// Perform qualified name lookup into a given context.
9679 ///
9680 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9681 /// names when the context of those names is explicit specified, e.g.,
9682 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9683 ///
9684 /// Different lookup criteria can find different names. For example, a
9685 /// particular scope can have both a struct and a function of the same
9686 /// name, and each can be found by certain lookup criteria. For more
9687 /// information about lookup criteria, see the documentation for the
9688 /// class LookupCriteria.
9689 ///
9690 /// \param R captures both the lookup criteria and any lookup results found.
9691 ///
9692 /// \param LookupCtx The context in which qualified name lookup will
9693 /// search. If the lookup criteria permits, name lookup may also search
9694 /// in the parent contexts or (for C++ classes) base classes.
9695 ///
9696 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9697 /// occurs as part of unqualified name lookup.
9698 ///
9699 /// \returns true if lookup succeeded, false if it failed.
9700 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9701 bool InUnqualifiedLookup = false);
9702
9703 /// Performs qualified name lookup or special type of lookup for
9704 /// "__super::" scope specifier.
9705 ///
9706 /// This routine is a convenience overload meant to be called from contexts
9707 /// that need to perform a qualified name lookup with an optional C++ scope
9708 /// specifier that might require special kind of lookup.
9709 ///
9710 /// \param R captures both the lookup criteria and any lookup results found.
9711 ///
9712 /// \param LookupCtx The context in which qualified name lookup will
9713 /// search.
9714 ///
9715 /// \param SS An optional C++ scope-specifier.
9716 ///
9717 /// \returns true if lookup succeeded, false if it failed.
9718 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9719 CXXScopeSpec &SS);
9720
9721 /// Performs name lookup for a name that was parsed in the
9722 /// source code, and may contain a C++ scope specifier.
9723 ///
9724 /// This routine is a convenience routine meant to be called from
9725 /// contexts that receive a name and an optional C++ scope specifier
9726 /// (e.g., "N::M::x"). It will then perform either qualified or
9727 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9728 /// respectively) on the given name and return those results. It will
9729 /// perform a special type of lookup for "__super::" scope specifier.
9730 ///
9731 /// @param S The scope from which unqualified name lookup will
9732 /// begin.
9733 ///
9734 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9735 ///
9736 /// @param EnteringContext Indicates whether we are going to enter the
9737 /// context of the scope-specifier SS (if present).
9738 ///
9739 /// @returns True if any decls were found (but possibly ambiguous)
9740 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9741 QualType ObjectType, bool AllowBuiltinCreation = false,
9742 bool EnteringContext = false);
9743
9744 /// Perform qualified name lookup into all base classes of the given
9745 /// class.
9746 ///
9747 /// \param R captures both the lookup criteria and any lookup results found.
9748 ///
9749 /// \param Class The context in which qualified name lookup will
9750 /// search. Name lookup will search in all base classes merging the results.
9751 ///
9752 /// @returns True if any decls were found (but possibly ambiguous)
9753 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9754
9755 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9756 UnresolvedSetImpl &Functions);
9757
9758 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9759 /// If GnuLabelLoc is a valid source location, then this is a definition
9760 /// of an __label__ label name, otherwise it is a normal label definition
9761 /// or use. If IsLabelStmt is true, then this is the label of a
9762 /// labeled-statement.
9763 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9764 SourceLocation GnuLabelLoc = SourceLocation(),
9765 bool IsLabelStmt = false);
9766
9767 /// Perform a name lookup for a label with the specified name; this does not
9768 /// create a new label if the lookup fails.
9769 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9770
9771 /// Look up the constructors for the given class.
9772 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9773
9774 /// Look up the default constructor for the given class.
9775 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9776
9777 /// Look up the copying constructor for the given class.
9778 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9779 unsigned Quals);
9780
9781 /// Look up the copying assignment operator for the given class.
9782 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9783 bool RValueThis, unsigned ThisQuals);
9784
9785 /// Look up the moving constructor for the given class.
9786 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9787 unsigned Quals);
9788
9789 /// Look up the moving assignment operator for the given class.
9790 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9791 bool RValueThis, unsigned ThisQuals);
9792
9793 /// Look for the destructor of the given class.
9794 ///
9795 /// During semantic analysis, this routine should be used in lieu of
9796 /// CXXRecordDecl::getDestructor().
9797 ///
9798 /// \returns The destructor for this class.
9799 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9800
9801 /// Force the declaration of any implicitly-declared members of this
9802 /// class.
9803 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9804
9805 /// Make a merged definition of an existing hidden definition \p ND
9806 /// visible at the specified location.
9807 void makeMergedDefinitionVisible(NamedDecl *ND);
9808
9809 /// Check ODR hashes for C/ObjC when merging types from modules.
9810 /// Differently from C++, actually parse the body and reject in case
9811 /// of a mismatch.
9812 template <typename T,
9813 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9814 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9815 if (Duplicate->getODRHash() != Previous->getODRHash())
9816 return false;
9817
9818 // Make the previous decl visible.
9819 makeMergedDefinitionVisible(ND: Previous);
9820 return true;
9821 }
9822
9823 /// Get the set of additional modules that should be checked during
9824 /// name lookup. A module and its imports become visible when instanting a
9825 /// template defined within it.
9826 llvm::DenseSet<Module *> &getLookupModules();
9827
9828 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9829 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9830
9831 /// Determine if the template parameter \p D has a visible default argument.
9832 bool
9833 hasVisibleDefaultArgument(const NamedDecl *D,
9834 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9835 /// Determine if the template parameter \p D has a reachable default argument.
9836 bool hasReachableDefaultArgument(
9837 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9838 /// Determine if the template parameter \p D has a reachable default argument.
9839 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9840 llvm::SmallVectorImpl<Module *> *Modules,
9841 Sema::AcceptableKind Kind);
9842
9843 /// Determine if there is a visible declaration of \p D that is an explicit
9844 /// specialization declaration for a specialization of a template. (For a
9845 /// member specialization, use hasVisibleMemberSpecialization.)
9846 bool hasVisibleExplicitSpecialization(
9847 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9848 /// Determine if there is a reachable declaration of \p D that is an explicit
9849 /// specialization declaration for a specialization of a template. (For a
9850 /// member specialization, use hasReachableMemberSpecialization.)
9851 bool hasReachableExplicitSpecialization(
9852 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9853
9854 /// Determine if there is a visible declaration of \p D that is a member
9855 /// specialization declaration (as opposed to an instantiated declaration).
9856 bool hasVisibleMemberSpecialization(
9857 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9858 /// Determine if there is a reachable declaration of \p D that is a member
9859 /// specialization declaration (as opposed to an instantiated declaration).
9860 bool hasReachableMemberSpecialization(
9861 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9862
9863 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9864
9865 /// Determine whether any declaration of an entity is visible.
9866 bool
9867 hasVisibleDeclaration(const NamedDecl *D,
9868 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9869 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9870 }
9871
9872 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9873 llvm::SmallVectorImpl<Module *> *Modules);
9874 /// Determine whether any declaration of an entity is reachable.
9875 bool
9876 hasReachableDeclaration(const NamedDecl *D,
9877 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9878 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9879 }
9880 bool hasReachableDeclarationSlow(
9881 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9882
9883 void diagnoseTypo(const TypoCorrection &Correction,
9884 const PartialDiagnostic &TypoDiag,
9885 bool ErrorRecovery = true);
9886
9887 /// Diagnose a successfully-corrected typo. Separated from the correction
9888 /// itself to allow external validation of the result, etc.
9889 ///
9890 /// \param Correction The result of performing typo correction.
9891 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9892 /// string added to it (and usually also a fixit).
9893 /// \param PrevNote A note to use when indicating the location of the entity
9894 /// to which we are correcting. Will have the correction string added
9895 /// to it.
9896 /// \param ErrorRecovery If \c true (the default), the caller is going to
9897 /// recover from the typo as if the corrected string had been typed.
9898 /// In this case, \c PDiag must be an error, and we will attach a fixit
9899 /// to it.
9900 void diagnoseTypo(const TypoCorrection &Correction,
9901 const PartialDiagnostic &TypoDiag,
9902 const PartialDiagnostic &PrevNote,
9903 bool ErrorRecovery = true);
9904
9905 /// Find the associated classes and namespaces for
9906 /// argument-dependent lookup for a call with the given set of
9907 /// arguments.
9908 ///
9909 /// This routine computes the sets of associated classes and associated
9910 /// namespaces searched by argument-dependent lookup
9911 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9912 void FindAssociatedClassesAndNamespaces(
9913 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9914 AssociatedNamespaceSet &AssociatedNamespaces,
9915 AssociatedClassSet &AssociatedClasses);
9916
9917 /// Produce a diagnostic describing the ambiguity that resulted
9918 /// from name lookup.
9919 ///
9920 /// \param Result The result of the ambiguous lookup to be diagnosed.
9921 void DiagnoseAmbiguousLookup(LookupResult &Result);
9922
9923 /// LookupLiteralOperator - Determine which literal operator should be used
9924 /// for a user-defined literal, per C++11 [lex.ext].
9925 ///
9926 /// Normal overload resolution is not used to select which literal operator to
9927 /// call for a user-defined literal. Look up the provided literal operator
9928 /// name, and filter the results to the appropriate set for the given argument
9929 /// types.
9930 LiteralOperatorLookupResult
9931 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9932 bool AllowRaw, bool AllowTemplate,
9933 bool AllowStringTemplate, bool DiagnoseMissing,
9934 StringLiteral *StringLit = nullptr);
9935
9936 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9937 ArrayRef<Expr *> Args, ADLResult &Functions);
9938
9939 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9940 VisibleDeclConsumer &Consumer,
9941 bool IncludeGlobalScope = true,
9942 bool LoadExternal = true);
9943 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9944 VisibleDeclConsumer &Consumer,
9945 bool IncludeGlobalScope = true,
9946 bool IncludeDependentBases = false,
9947 bool LoadExternal = true);
9948
9949 /// Try to "correct" a typo in the source code by finding
9950 /// visible declarations whose names are similar to the name that was
9951 /// present in the source code.
9952 ///
9953 /// \param TypoName the \c DeclarationNameInfo structure that contains
9954 /// the name that was present in the source code along with its location.
9955 ///
9956 /// \param LookupKind the name-lookup criteria used to search for the name.
9957 ///
9958 /// \param S the scope in which name lookup occurs.
9959 ///
9960 /// \param SS the nested-name-specifier that precedes the name we're
9961 /// looking for, if present.
9962 ///
9963 /// \param CCC A CorrectionCandidateCallback object that provides further
9964 /// validation of typo correction candidates. It also provides flags for
9965 /// determining the set of keywords permitted.
9966 ///
9967 /// \param MemberContext if non-NULL, the context in which to look for
9968 /// a member access expression.
9969 ///
9970 /// \param EnteringContext whether we're entering the context described by
9971 /// the nested-name-specifier SS.
9972 ///
9973 /// \param OPT when non-NULL, the search for visible declarations will
9974 /// also walk the protocols in the qualified interfaces of \p OPT.
9975 ///
9976 /// \returns a \c TypoCorrection containing the corrected name if the typo
9977 /// along with information such as the \c NamedDecl where the corrected name
9978 /// was declared, and any additional \c NestedNameSpecifier needed to access
9979 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9980 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9981 Sema::LookupNameKind LookupKind, Scope *S,
9982 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9983 CorrectTypoKind Mode,
9984 DeclContext *MemberContext = nullptr,
9985 bool EnteringContext = false,
9986 const ObjCObjectPointerType *OPT = nullptr,
9987 bool RecordFailure = true);
9988
9989 /// Kinds of missing import. Note, the values of these enumerators correspond
9990 /// to %select values in diagnostics.
9991 enum class MissingImportKind {
9992 Declaration,
9993 Definition,
9994 DefaultArgument,
9995 ExplicitSpecialization,
9996 PartialSpecialization
9997 };
9998
9999 /// Diagnose that the specified declaration needs to be visible but
10000 /// isn't, and suggest a module import that would resolve the problem.
10001 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
10002 MissingImportKind MIK, bool Recover = true);
10003 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
10004 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
10005 MissingImportKind MIK, bool Recover);
10006
10007 /// Called on #pragma clang __debug dump II
10008 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10009
10010 /// Called on #pragma clang __debug dump E
10011 void ActOnPragmaDump(Expr *E);
10012
10013private:
10014 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
10015 //
10016 // The boolean value will be true to indicate that the namespace was loaded
10017 // from an AST/PCH file, or false otherwise.
10018 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
10019
10020 /// Whether we have already loaded known namespaces from an extenal
10021 /// source.
10022 bool LoadedExternalKnownNamespaces;
10023
10024 bool CppLookupName(LookupResult &R, Scope *S);
10025
10026 /// Determine if we could use all the declarations in the module.
10027 bool isUsableModule(const Module *M);
10028
10029 /// Helper for CorrectTypo used to create and populate a new
10030 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
10031 /// skipped entirely.
10032 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
10033 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
10034 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
10035 DeclContext *MemberContext, bool EnteringContext,
10036 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
10037
10038 /// Cache for module units which is usable for current module.
10039 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
10040
10041 /// Record the typo correction failure and return an empty correction.
10042 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
10043 bool RecordFailure = true) {
10044 if (RecordFailure)
10045 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
10046 return TypoCorrection();
10047 }
10048
10049 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
10050
10051 /// Determine whether two declarations should be linked together, given that
10052 /// the old declaration might not be visible and the new declaration might
10053 /// not have external linkage.
10054 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
10055 const NamedDecl *New) {
10056 if (isVisible(D: Old))
10057 return true;
10058 // See comment in below overload for why it's safe to compute the linkage
10059 // of the new declaration here.
10060 if (New->isExternallyDeclarable()) {
10061 assert(Old->isExternallyDeclarable() &&
10062 "should not have found a non-externally-declarable previous decl");
10063 return true;
10064 }
10065 return false;
10066 }
10067 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
10068
10069 ///@}
10070
10071 //
10072 //
10073 // -------------------------------------------------------------------------
10074 //
10075 //
10076
10077 /// \name Modules
10078 /// Implementations are in SemaModule.cpp
10079 ///@{
10080
10081public:
10082 /// Get the module unit whose scope we are currently within.
10083 Module *getCurrentModule() const {
10084 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
10085 }
10086
10087 /// Is the module scope we are an implementation unit?
10088 bool currentModuleIsImplementation() const {
10089 if (ModuleScopes.empty())
10090 return false;
10091 const Module *M = ModuleScopes.back().Module;
10092 return M->isModuleImplementation() || M->isModulePartitionImplementation();
10093 }
10094
10095 // When loading a non-modular PCH files, this is used to restore module
10096 // visibility.
10097 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
10098 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
10099 }
10100
10101 enum class ModuleDeclKind {
10102 Interface, ///< 'export module X;'
10103 Implementation, ///< 'module X;'
10104 PartitionInterface, ///< 'export module X:Y;'
10105 PartitionImplementation, ///< 'module X:Y;'
10106 };
10107
10108 /// An enumeration to represent the transition of states in parsing module
10109 /// fragments and imports. If we are not parsing a C++20 TU, or we find
10110 /// an error in state transition, the state is set to NotACXX20Module.
10111 enum class ModuleImportState {
10112 FirstDecl, ///< Parsing the first decl in a TU.
10113 GlobalFragment, ///< after 'module;' but before 'module X;'
10114 ImportAllowed, ///< after 'module X;' but before any non-import decl.
10115 ImportFinished, ///< after any non-import decl.
10116 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
10117 ///< non-import decl.
10118 PrivateFragmentImportFinished, ///< after 'module :private;' but a
10119 ///< non-import decl has already been seen.
10120 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
10121 };
10122
10123 /// The parser has processed a module-declaration that begins the definition
10124 /// of a module interface or implementation.
10125 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
10126 SourceLocation ModuleLoc, ModuleDeclKind MDK,
10127 ModuleIdPath Path, ModuleIdPath Partition,
10128 ModuleImportState &ImportState,
10129 bool SeenNoTrivialPPDirective);
10130
10131 /// The parser has processed a global-module-fragment declaration that begins
10132 /// the definition of the global module fragment of the current module unit.
10133 /// \param ModuleLoc The location of the 'module' keyword.
10134 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
10135
10136 /// The parser has processed a private-module-fragment declaration that begins
10137 /// the definition of the private module fragment of the current module unit.
10138 /// \param ModuleLoc The location of the 'module' keyword.
10139 /// \param PrivateLoc The location of the 'private' keyword.
10140 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
10141 SourceLocation PrivateLoc);
10142
10143 /// The parser has processed a module import declaration.
10144 ///
10145 /// \param StartLoc The location of the first token in the declaration. This
10146 /// could be the location of an '@', 'export', or 'import'.
10147 /// \param ExportLoc The location of the 'export' keyword, if any.
10148 /// \param ImportLoc The location of the 'import' keyword.
10149 /// \param Path The module toplevel name as an access path.
10150 /// \param IsPartition If the name is for a partition.
10151 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10152 SourceLocation ExportLoc,
10153 SourceLocation ImportLoc, ModuleIdPath Path,
10154 bool IsPartition = false);
10155 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10156 SourceLocation ExportLoc,
10157 SourceLocation ImportLoc, Module *M,
10158 ModuleIdPath Path = {});
10159
10160 /// The parser has processed a module import translated from a
10161 /// #include or similar preprocessing directive.
10162 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10163 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10164
10165 /// The parsed has entered a submodule.
10166 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10167 /// The parser has left a submodule.
10168 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10169
10170 /// Create an implicit import of the given module at the given
10171 /// source location, for error recovery, if possible.
10172 ///
10173 /// This routine is typically used when an entity found by name lookup
10174 /// is actually hidden within a module that we know about but the user
10175 /// has forgotten to import.
10176 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10177 Module *Mod);
10178
10179 /// We have parsed the start of an export declaration, including the '{'
10180 /// (if present).
10181 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10182 SourceLocation LBraceLoc);
10183
10184 /// Complete the definition of an export declaration.
10185 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10186 SourceLocation RBraceLoc);
10187
10188private:
10189 /// The parser has begun a translation unit to be compiled as a C++20
10190 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10191 void HandleStartOfHeaderUnit();
10192
10193 struct ModuleScope {
10194 SourceLocation BeginLoc;
10195 clang::Module *Module = nullptr;
10196 VisibleModuleSet OuterVisibleModules;
10197 };
10198 /// The modules we're currently parsing.
10199 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10200
10201 /// For an interface unit, this is the implicitly imported interface unit.
10202 clang::Module *ThePrimaryInterface = nullptr;
10203
10204 /// The explicit global module fragment of the current translation unit.
10205 /// The explicit Global Module Fragment, as specified in C++
10206 /// [module.global.frag].
10207 clang::Module *TheGlobalModuleFragment = nullptr;
10208
10209 /// The implicit global module fragments of the current translation unit.
10210 ///
10211 /// The contents in the implicit global module fragment can't be discarded.
10212 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10213
10214 /// Namespace definitions that we will export when they finish.
10215 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10216
10217 /// In a C++ standard module, inline declarations require a definition to be
10218 /// present at the end of a definition domain. This set holds the decls to
10219 /// be checked at the end of the TU.
10220 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10221
10222 /// Helper function to judge if we are in module purview.
10223 /// Return false if we are not in a module.
10224 bool isCurrentModulePurview() const;
10225
10226 /// Enter the scope of the explicit global module fragment.
10227 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10228 /// Leave the scope of the explicit global module fragment.
10229 void PopGlobalModuleFragment();
10230
10231 /// Enter the scope of an implicit global module fragment.
10232 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10233 /// Leave the scope of an implicit global module fragment.
10234 void PopImplicitGlobalModuleFragment();
10235
10236 VisibleModuleSet VisibleModules;
10237
10238 /// Whether we had imported any named modules.
10239 bool HadImportedNamedModules = false;
10240 /// The set of instantiations we need to check if they references TU-local
10241 /// entity from TUs. This only makes sense if we imported any named modules.
10242 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10243 PendingCheckReferenceForTULocal;
10244 /// Implement [basic.link]p18, which requires that we can't use TU-local
10245 /// entities from other TUs (ignoring header units).
10246 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10247 SourceLocation PointOfInstantiation);
10248 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10249 /// module interface or module partition.
10250 void checkExposure(const TranslationUnitDecl *TU);
10251
10252 ///@}
10253
10254 //
10255 //
10256 // -------------------------------------------------------------------------
10257 //
10258 //
10259
10260 /// \name C++ Overloading
10261 /// Implementations are in SemaOverload.cpp
10262 ///@{
10263
10264public:
10265 /// Whether deferrable diagnostics should be deferred.
10266 bool DeferDiags = false;
10267
10268 /// RAII class to control scope of DeferDiags.
10269 class DeferDiagsRAII {
10270 Sema &S;
10271 bool SavedDeferDiags = false;
10272
10273 public:
10274 DeferDiagsRAII(Sema &S, bool DeferDiags)
10275 : S(S), SavedDeferDiags(S.DeferDiags) {
10276 S.DeferDiags = SavedDeferDiags || DeferDiags;
10277 }
10278 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10279 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10280 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10281 };
10282
10283 /// Flag indicating if Sema is building a recovery call expression.
10284 ///
10285 /// This flag is used to avoid building recovery call expressions
10286 /// if Sema is already doing so, which would cause infinite recursions.
10287 bool IsBuildingRecoveryCallExpr;
10288
10289 /// Determine whether the given New declaration is an overload of the
10290 /// declarations in Old. This routine returns OverloadKind::Match or
10291 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10292 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10293 /// Old declarations aren't functions (or function templates) at all. When it
10294 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10295 /// will point to the decl that New cannot be overloaded with. This decl may
10296 /// be a UsingShadowDecl on top of the underlying declaration.
10297 ///
10298 /// Example: Given the following input:
10299 ///
10300 /// void f(int, float); // #1
10301 /// void f(int, int); // #2
10302 /// int f(int, int); // #3
10303 ///
10304 /// When we process #1, there is no previous declaration of "f", so IsOverload
10305 /// will not be used.
10306 ///
10307 /// When we process #2, Old contains only the FunctionDecl for #1. By
10308 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10309 /// they have different signatures), so this routine returns
10310 /// OverloadKind::Overload; MatchedDecl is unchanged.
10311 ///
10312 /// When we process #3, Old is an overload set containing #1 and #2. We
10313 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10314 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10315 /// types of functions are not part of the signature), IsOverload returns
10316 /// OverloadKind::Match and MatchedDecl will be set to point to the
10317 /// FunctionDecl for #2.
10318 ///
10319 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10320 /// class by a using declaration. The rules for whether to hide shadow
10321 /// declarations ignore some properties which otherwise figure into a function
10322 /// template's signature.
10323 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10324 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10325 bool UseMemberUsingDeclRules);
10326 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10327 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10328
10329 // Checks whether MD constitutes an override the base class method BaseMD.
10330 // When checking for overrides, the object object members are ignored.
10331 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10332 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10333
10334 enum class AllowedExplicit {
10335 /// Allow no explicit functions to be used.
10336 None,
10337 /// Allow explicit conversion functions but not explicit constructors.
10338 Conversions,
10339 /// Allow both explicit conversion functions and explicit constructors.
10340 All
10341 };
10342
10343 ImplicitConversionSequence TryImplicitConversion(
10344 Expr *From, QualType ToType, bool SuppressUserConversions,
10345 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10346 bool AllowObjCWritebackConversion);
10347
10348 /// PerformImplicitConversion - Perform an implicit conversion of the
10349 /// expression From to the type ToType. Returns the
10350 /// converted expression. Flavor is the kind of conversion we're
10351 /// performing, used in the error message. If @p AllowExplicit,
10352 /// explicit user-defined conversions are permitted.
10353 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10354 AssignmentAction Action,
10355 bool AllowExplicit = false);
10356
10357 /// IsIntegralPromotion - Determines whether the conversion from the
10358 /// expression From (whose potentially-adjusted type is FromType) to
10359 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10360 /// sets PromotedType to the promoted type.
10361 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10362
10363 /// IsFloatingPointPromotion - Determines whether the conversion from
10364 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10365 /// returns true and sets PromotedType to the promoted type.
10366 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10367
10368 /// Determine if a conversion is a complex promotion.
10369 ///
10370 /// A complex promotion is defined as a complex -> complex conversion
10371 /// where the conversion between the underlying real types is a
10372 /// floating-point or integral promotion.
10373 bool IsComplexPromotion(QualType FromType, QualType ToType);
10374
10375 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10376 /// FromType to ToType involves an OverflowBehaviorType FromType being
10377 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10378 /// If so, returns true and sets FromType to ToType.
10379 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10380
10381 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10382 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10383 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10384 /// ToType.
10385 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10386
10387 /// IsPointerConversion - Determines whether the conversion of the
10388 /// expression From, which has the (possibly adjusted) type FromType,
10389 /// can be converted to the type ToType via a pointer conversion (C++
10390 /// 4.10). If so, returns true and places the converted type (that
10391 /// might differ from ToType in its cv-qualifiers at some level) into
10392 /// ConvertedType.
10393 ///
10394 /// This routine also supports conversions to and from block pointers
10395 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10396 /// pointers to interfaces. FIXME: Once we've determined the
10397 /// appropriate overloading rules for Objective-C, we may want to
10398 /// split the Objective-C checks into a different routine; however,
10399 /// GCC seems to consider all of these conversions to be pointer
10400 /// conversions, so for now they live here. IncompatibleObjC will be
10401 /// set if the conversion is an allowed Objective-C conversion that
10402 /// should result in a warning.
10403 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10404 bool InOverloadResolution, QualType &ConvertedType,
10405 bool &IncompatibleObjC);
10406
10407 /// isObjCPointerConversion - Determines whether this is an
10408 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10409 /// with the same arguments and return values.
10410 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10411 QualType &ConvertedType, bool &IncompatibleObjC);
10412 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10413 QualType &ConvertedType);
10414
10415 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10416 /// for equality of their parameter types. Caller has already checked that
10417 /// they have same number of parameters. If the parameters are different,
10418 /// ArgPos will have the parameter index of the first different parameter.
10419 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10420 /// reverse order. That's useful if one of the functions is being used as a
10421 /// C++20 synthesized operator overload with a reversed parameter order.
10422 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10423 ArrayRef<QualType> New,
10424 unsigned *ArgPos = nullptr,
10425 bool Reversed = false);
10426
10427 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10428 const FunctionProtoType *NewType,
10429 unsigned *ArgPos = nullptr,
10430 bool Reversed = false);
10431
10432 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10433 const FunctionDecl *NewFunction,
10434 unsigned *ArgPos = nullptr,
10435 bool Reversed = false);
10436
10437 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10438 /// function types. Catches different number of parameter, mismatch in
10439 /// parameter types, and different return types.
10440 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10441 QualType ToType);
10442
10443 /// CheckPointerConversion - Check the pointer conversion from the
10444 /// expression From to the type ToType. This routine checks for
10445 /// ambiguous or inaccessible derived-to-base pointer
10446 /// conversions for which IsPointerConversion has already returned
10447 /// true. It returns true and produces a diagnostic if there was an
10448 /// error, or returns false otherwise.
10449 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10450 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10451 bool Diagnose = true);
10452
10453 /// IsMemberPointerConversion - Determines whether the conversion of the
10454 /// expression From, which has the (possibly adjusted) type FromType, can be
10455 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10456 /// If so, returns true and places the converted type (that might differ from
10457 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10458 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10459 bool InOverloadResolution,
10460 QualType &ConvertedType);
10461
10462 enum class MemberPointerConversionResult {
10463 Success,
10464 DifferentPointee,
10465 NotDerived,
10466 Ambiguous,
10467 Virtual,
10468 Inaccessible
10469 };
10470 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10471 /// CheckMemberPointerConversion - Check the member pointer conversion from
10472 /// the expression From to the type ToType. This routine checks for ambiguous
10473 /// or virtual or inaccessible base-to-derived member pointer conversions for
10474 /// which IsMemberPointerConversion has already returned true. It produces a
10475 // diagnostic if there was an error.
10476 MemberPointerConversionResult CheckMemberPointerConversion(
10477 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10478 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10479 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10480
10481 /// IsQualificationConversion - Determines whether the conversion from
10482 /// an rvalue of type FromType to ToType is a qualification conversion
10483 /// (C++ 4.4).
10484 ///
10485 /// \param ObjCLifetimeConversion Output parameter that will be set to
10486 /// indicate when the qualification conversion involves a change in the
10487 /// Objective-C object lifetime.
10488 bool IsQualificationConversion(QualType FromType, QualType ToType,
10489 bool CStyle, bool &ObjCLifetimeConversion);
10490
10491 /// Determine whether the conversion from FromType to ToType is a valid
10492 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10493 /// More precisely, this method checks whether FromType can be transformed
10494 /// into an exact match for ToType, by transforming its extended function
10495 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10496 /// or "noexcept", or by stripping "noescape" for arguments).
10497 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10498
10499 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10500 /// `ResultTy` to `ToType`.
10501 bool TryFunctionConversion(QualType FromType, QualType ToType,
10502 QualType &ResultTy) const;
10503
10504 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10505 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10506 DeclarationName Name,
10507 OverloadCandidateSet &CandidateSet,
10508 FunctionDecl *Fn, MultiExprArg Args,
10509 bool IsMember = false);
10510
10511 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10512 FunctionDecl *Fun);
10513 ExprResult PerformImplicitObjectArgumentInitialization(
10514 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10515 CXXMethodDecl *Method);
10516
10517 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10518 /// of the expression From to bool (C++0x [conv]p3).
10519 ExprResult PerformContextuallyConvertToBool(Expr *From);
10520
10521 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10522 /// conversion of the expression From to an Objective-C pointer type.
10523 /// Returns a valid but null ExprResult if no conversion sequence exists.
10524 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10525
10526 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10527 CCEKind CCE,
10528 NamedDecl *Dest = nullptr);
10529
10530 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10531 llvm::APSInt &Value, CCEKind CCE);
10532 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10533 APValue &Value, CCEKind CCE,
10534 NamedDecl *Dest = nullptr);
10535
10536 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10537 /// That is a converted constant expression
10538 /// (which was built with BuildConvertedConstantExpression)
10539 ExprResult
10540 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10541 CCEKind CCE, bool RequireInt,
10542 const APValue &PreNarrowingValue);
10543
10544 /// Abstract base class used to perform a contextual implicit
10545 /// conversion from an expression to any type passing a filter.
10546 class ContextualImplicitConverter {
10547 public:
10548 bool Suppress;
10549 bool SuppressConversion;
10550
10551 ContextualImplicitConverter(bool Suppress = false,
10552 bool SuppressConversion = false)
10553 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10554
10555 /// Determine whether the specified type is a valid destination type
10556 /// for this conversion.
10557 virtual bool match(QualType T) = 0;
10558
10559 /// Emits a diagnostic complaining that the expression does not have
10560 /// integral or enumeration type.
10561 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10562 QualType T) = 0;
10563
10564 /// Emits a diagnostic when the expression has incomplete class type.
10565 virtual SemaDiagnosticBuilder
10566 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10567
10568 /// Emits a diagnostic when the only matching conversion function
10569 /// is explicit.
10570 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10571 SourceLocation Loc,
10572 QualType T,
10573 QualType ConvTy) = 0;
10574
10575 /// Emits a note for the explicit conversion function.
10576 virtual SemaDiagnosticBuilder
10577 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10578
10579 /// Emits a diagnostic when there are multiple possible conversion
10580 /// functions.
10581 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10582 QualType T) = 0;
10583
10584 /// Emits a note for one of the candidate conversions.
10585 virtual SemaDiagnosticBuilder
10586 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10587
10588 /// Emits a diagnostic when we picked a conversion function
10589 /// (for cases when we are not allowed to pick a conversion function).
10590 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10591 SourceLocation Loc,
10592 QualType T,
10593 QualType ConvTy) = 0;
10594
10595 virtual ~ContextualImplicitConverter() {}
10596 };
10597
10598 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10599 bool AllowScopedEnumerations;
10600
10601 public:
10602 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10603 bool SuppressConversion)
10604 : ContextualImplicitConverter(Suppress, SuppressConversion),
10605 AllowScopedEnumerations(AllowScopedEnumerations) {}
10606
10607 /// Match an integral or (possibly scoped) enumeration type.
10608 bool match(QualType T) override;
10609
10610 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10611 QualType T) override {
10612 return diagnoseNotInt(S, Loc, T);
10613 }
10614
10615 /// Emits a diagnostic complaining that the expression does not have
10616 /// integral or enumeration type.
10617 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10618 QualType T) = 0;
10619 };
10620
10621 /// Perform a contextual implicit conversion.
10622 ExprResult
10623 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10624 ContextualImplicitConverter &Converter);
10625
10626 /// ReferenceCompareResult - Expresses the result of comparing two
10627 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10628 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10629 enum ReferenceCompareResult {
10630 /// Ref_Incompatible - The two types are incompatible, so direct
10631 /// reference binding is not possible.
10632 Ref_Incompatible = 0,
10633 /// Ref_Related - The two types are reference-related, which means
10634 /// that their unqualified forms (T1 and T2) are either the same
10635 /// or T1 is a base class of T2.
10636 Ref_Related,
10637 /// Ref_Compatible - The two types are reference-compatible.
10638 Ref_Compatible
10639 };
10640
10641 // Fake up a scoped enumeration that still contextually converts to bool.
10642 struct ReferenceConversionsScope {
10643 /// The conversions that would be performed on an lvalue of type T2 when
10644 /// binding a reference of type T1 to it, as determined when evaluating
10645 /// whether T1 is reference-compatible with T2.
10646 enum ReferenceConversions {
10647 Qualification = 0x1,
10648 NestedQualification = 0x2,
10649 Function = 0x4,
10650 DerivedToBase = 0x8,
10651 ObjC = 0x10,
10652 ObjCLifetime = 0x20,
10653
10654 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10655 };
10656 };
10657 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10658
10659 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10660 /// determine whether they are reference-compatible,
10661 /// reference-related, or incompatible, for use in C++ initialization by
10662 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10663 /// type, and the first type (T1) is the pointee type of the reference
10664 /// type being initialized.
10665 ReferenceCompareResult
10666 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10667 ReferenceConversions *Conv = nullptr);
10668
10669 /// AddOverloadCandidate - Adds the given function to the set of
10670 /// candidate functions, using the given function call arguments. If
10671 /// @p SuppressUserConversions, then don't allow user-defined
10672 /// conversions via constructors or conversion operators.
10673 ///
10674 /// \param PartialOverloading true if we are performing "partial" overloading
10675 /// based on an incomplete set of function arguments. This feature is used by
10676 /// code completion.
10677 void AddOverloadCandidate(
10678 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10679 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10680 bool PartialOverloading = false, bool AllowExplicit = true,
10681 bool AllowExplicitConversion = false,
10682 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10683 ConversionSequenceList EarlyConversions = {},
10684 OverloadCandidateParamOrder PO = {},
10685 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10686
10687 /// Add all of the function declarations in the given function set to
10688 /// the overload candidate set.
10689 void AddFunctionCandidates(
10690 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10691 OverloadCandidateSet &CandidateSet,
10692 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10693 bool SuppressUserConversions = false, bool PartialOverloading = false,
10694 bool FirstArgumentIsBase = false);
10695
10696 /// AddMethodCandidate - Adds a named decl (which is some kind of
10697 /// method) as a method candidate to the given overload set.
10698 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10699 Expr::Classification ObjectClassification,
10700 ArrayRef<Expr *> Args,
10701 OverloadCandidateSet &CandidateSet,
10702 bool SuppressUserConversion = false,
10703 OverloadCandidateParamOrder PO = {});
10704
10705 /// AddMethodCandidate - Adds the given C++ member function to the set
10706 /// of candidate functions, using the given function call arguments
10707 /// and the object argument (@c Object). For example, in a call
10708 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10709 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10710 /// allow user-defined conversions via constructors or conversion
10711 /// operators.
10712 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10713 CXXRecordDecl *ActingContext, QualType ObjectType,
10714 Expr::Classification ObjectClassification,
10715 ArrayRef<Expr *> Args,
10716 OverloadCandidateSet &CandidateSet,
10717 bool SuppressUserConversions = false,
10718 bool PartialOverloading = false,
10719 ConversionSequenceList EarlyConversions = {},
10720 OverloadCandidateParamOrder PO = {},
10721 bool StrictPackMatch = false);
10722
10723 /// Add a C++ member function template as a candidate to the candidate
10724 /// set, using template argument deduction to produce an appropriate member
10725 /// function template specialization.
10726 void AddMethodTemplateCandidate(
10727 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10728 CXXRecordDecl *ActingContext,
10729 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10730 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10731 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10732 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10733
10734 /// Add a C++ function template specialization as a candidate
10735 /// in the candidate set, using template argument deduction to produce
10736 /// an appropriate function template specialization.
10737 void AddTemplateOverloadCandidate(
10738 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10739 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10740 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10741 bool PartialOverloading = false, bool AllowExplicit = true,
10742 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10743 OverloadCandidateParamOrder PO = {},
10744 bool AggregateCandidateDeduction = false);
10745
10746 struct CheckNonDependentConversionsFlag {
10747 /// Do not consider any user-defined conversions when constructing the
10748 /// initializing sequence.
10749 bool SuppressUserConversions;
10750
10751 /// Before constructing the initializing sequence, we check whether the
10752 /// parameter type and argument type contain any user defined conversions.
10753 /// If so, do not initialize them. This effectively bypasses some undesired
10754 /// instantiation before checking constaints, which might otherwise result
10755 /// in non-SFINAE errors e.g. recursive constraints.
10756 bool OnlyInitializeNonUserDefinedConversions;
10757
10758 CheckNonDependentConversionsFlag(
10759 bool SuppressUserConversions,
10760 bool OnlyInitializeNonUserDefinedConversions)
10761 : SuppressUserConversions(SuppressUserConversions),
10762 OnlyInitializeNonUserDefinedConversions(
10763 OnlyInitializeNonUserDefinedConversions) {}
10764 };
10765
10766 /// Check that implicit conversion sequences can be formed for each argument
10767 /// whose corresponding parameter has a non-dependent type, per DR1391's
10768 /// [temp.deduct.call]p10.
10769 bool CheckNonDependentConversions(
10770 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10771 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10772 ConversionSequenceList &Conversions,
10773 CheckNonDependentConversionsFlag UserConversionFlag,
10774 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10775 Expr::Classification ObjectClassification = {},
10776 OverloadCandidateParamOrder PO = {});
10777
10778 /// AddConversionCandidate - Add a C++ conversion function as a
10779 /// candidate in the candidate set (C++ [over.match.conv],
10780 /// C++ [over.match.copy]). From is the expression we're converting from,
10781 /// and ToType is the type that we're eventually trying to convert to
10782 /// (which may or may not be the same type as the type that the
10783 /// conversion function produces).
10784 void AddConversionCandidate(
10785 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10786 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10787 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10788 bool AllowExplicit, bool AllowResultConversion = true,
10789 bool StrictPackMatch = false);
10790
10791 /// Adds a conversion function template specialization
10792 /// candidate to the overload set, using template argument deduction
10793 /// to deduce the template arguments of the conversion function
10794 /// template from the type that we are converting to (C++
10795 /// [temp.deduct.conv]).
10796 void AddTemplateConversionCandidate(
10797 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10798 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10799 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10800 bool AllowExplicit, bool AllowResultConversion = true);
10801
10802 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10803 /// converts the given @c Object to a function pointer via the
10804 /// conversion function @c Conversion, and then attempts to call it
10805 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10806 /// the type of function that we'll eventually be calling.
10807 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10808 DeclAccessPair FoundDecl,
10809 CXXRecordDecl *ActingContext,
10810 const FunctionProtoType *Proto, Expr *Object,
10811 ArrayRef<Expr *> Args,
10812 OverloadCandidateSet &CandidateSet);
10813
10814 /// Add all of the non-member operator function declarations in the given
10815 /// function set to the overload candidate set.
10816 void AddNonMemberOperatorCandidates(
10817 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10818 OverloadCandidateSet &CandidateSet,
10819 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10820
10821 /// Add overload candidates for overloaded operators that are
10822 /// member functions.
10823 ///
10824 /// Add the overloaded operator candidates that are member functions
10825 /// for the operator Op that was used in an operator expression such
10826 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10827 /// CandidateSet will store the added overload candidates. (C++
10828 /// [over.match.oper]).
10829 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10830 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10831 OverloadCandidateSet &CandidateSet,
10832 OverloadCandidateParamOrder PO = {});
10833
10834 /// AddBuiltinCandidate - Add a candidate for a built-in
10835 /// operator. ResultTy and ParamTys are the result and parameter types
10836 /// of the built-in candidate, respectively. Args and NumArgs are the
10837 /// arguments being passed to the candidate. IsAssignmentOperator
10838 /// should be true when this built-in candidate is an assignment
10839 /// operator. NumContextualBoolArguments is the number of arguments
10840 /// (at the beginning of the argument list) that will be contextually
10841 /// converted to bool.
10842 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10843 OverloadCandidateSet &CandidateSet,
10844 bool IsAssignmentOperator = false,
10845 unsigned NumContextualBoolArguments = 0);
10846
10847 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10848 /// operator overloads to the candidate set (C++ [over.built]), based
10849 /// on the operator @p Op and the arguments given. For example, if the
10850 /// operator is a binary '+', this routine might add "int
10851 /// operator+(int, int)" to cover integer addition.
10852 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10853 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10854 OverloadCandidateSet &CandidateSet);
10855
10856 /// Add function candidates found via argument-dependent lookup
10857 /// to the set of overloading candidates.
10858 ///
10859 /// This routine performs argument-dependent name lookup based on the
10860 /// given function name (which may also be an operator name) and adds
10861 /// all of the overload candidates found by ADL to the overload
10862 /// candidate set (C++ [basic.lookup.argdep]).
10863 void AddArgumentDependentLookupCandidates(
10864 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10865 TemplateArgumentListInfo *ExplicitTemplateArgs,
10866 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10867
10868 /// Check the enable_if expressions on the given function. Returns the first
10869 /// failing attribute, or NULL if they were all successful.
10870 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10871 ArrayRef<Expr *> Args,
10872 bool MissingImplicitThis = false);
10873
10874 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10875 /// non-ArgDependent DiagnoseIfAttrs.
10876 ///
10877 /// Argument-dependent diagnose_if attributes should be checked each time a
10878 /// function is used as a direct callee of a function call.
10879 ///
10880 /// Returns true if any errors were emitted.
10881 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10882 const Expr *ThisArg,
10883 ArrayRef<const Expr *> Args,
10884 SourceLocation Loc);
10885
10886 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10887 /// ArgDependent DiagnoseIfAttrs.
10888 ///
10889 /// Argument-independent diagnose_if attributes should be checked on every use
10890 /// of a function.
10891 ///
10892 /// Returns true if any errors were emitted.
10893 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10894 SourceLocation Loc);
10895
10896 /// Determine if \p A and \p B are equivalent internal linkage declarations
10897 /// from different modules, and thus an ambiguity error can be downgraded to
10898 /// an extension warning.
10899 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10900 const NamedDecl *B);
10901 void diagnoseEquivalentInternalLinkageDeclarations(
10902 SourceLocation Loc, const NamedDecl *D,
10903 ArrayRef<const NamedDecl *> Equiv);
10904
10905 // Emit as a 'note' the specific overload candidate
10906 void NoteOverloadCandidate(
10907 const NamedDecl *Found, const FunctionDecl *Fn,
10908 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10909 QualType DestType = QualType(), bool TakingAddress = false);
10910
10911 // Emit as a series of 'note's all template and non-templates identified by
10912 // the expression Expr
10913 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10914 bool TakingAddress = false);
10915
10916 /// Returns whether the given function's address can be taken or not,
10917 /// optionally emitting a diagnostic if the address can't be taken.
10918 ///
10919 /// Returns false if taking the address of the function is illegal.
10920 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10921 bool Complain = false,
10922 SourceLocation Loc = SourceLocation());
10923
10924 // [PossiblyAFunctionType] --> [Return]
10925 // NonFunctionType --> NonFunctionType
10926 // R (A) --> R(A)
10927 // R (*)(A) --> R (A)
10928 // R (&)(A) --> R (A)
10929 // R (S::*)(A) --> R (A)
10930 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10931
10932 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10933 /// an overloaded function (C++ [over.over]), where @p From is an
10934 /// expression with overloaded function type and @p ToType is the type
10935 /// we're trying to resolve to. For example:
10936 ///
10937 /// @code
10938 /// int f(double);
10939 /// int f(int);
10940 ///
10941 /// int (*pfd)(double) = f; // selects f(double)
10942 /// @endcode
10943 ///
10944 /// This routine returns the resulting FunctionDecl if it could be
10945 /// resolved, and NULL otherwise. When @p Complain is true, this
10946 /// routine will emit diagnostics if there is an error.
10947 FunctionDecl *
10948 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10949 bool Complain, DeclAccessPair &Found,
10950 bool *pHadMultipleCandidates = nullptr);
10951
10952 /// Given an expression that refers to an overloaded function, try to
10953 /// resolve that function to a single function that can have its address
10954 /// taken. This will modify `Pair` iff it returns non-null.
10955 ///
10956 /// This routine can only succeed if from all of the candidates in the
10957 /// overload set for SrcExpr that can have their addresses taken, there is one
10958 /// candidate that is more constrained than the rest.
10959 FunctionDecl *
10960 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10961
10962 /// Given an overloaded function, tries to turn it into a non-overloaded
10963 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10964 /// will perform access checks, diagnose the use of the resultant decl, and,
10965 /// if requested, potentially perform a function-to-pointer decay.
10966 ///
10967 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10968 /// Otherwise, returns true. This may emit diagnostics and return true.
10969 bool resolveAndFixAddressOfSingleOverloadCandidate(
10970 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10971
10972 /// Given an expression that refers to an overloaded function, try to
10973 /// resolve that overloaded function expression down to a single function.
10974 ///
10975 /// This routine can only resolve template-ids that refer to a single function
10976 /// template, where that template-id refers to a single template whose
10977 /// template arguments are either provided by the template-id or have
10978 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10979 ///
10980 /// If no template-ids are found, no diagnostics are emitted and NULL is
10981 /// returned.
10982 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10983 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10984 TemplateSpecCandidateSet *FailedTSC = nullptr,
10985 bool ForTypeDeduction = false);
10986
10987 // Resolve and fix an overloaded expression that can be resolved
10988 // because it identifies a single function template specialization.
10989 //
10990 // Last three arguments should only be supplied if Complain = true
10991 //
10992 // Return true if it was logically possible to so resolve the
10993 // expression, regardless of whether or not it succeeded. Always
10994 // returns true if 'complain' is set.
10995 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10996 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10997 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10998 QualType DestTypeForComplaining = QualType(),
10999 unsigned DiagIDForComplaining = 0);
11000
11001 /// Add the overload candidates named by callee and/or found by argument
11002 /// dependent lookup to the given overload set.
11003 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11004 ArrayRef<Expr *> Args,
11005 OverloadCandidateSet &CandidateSet,
11006 bool PartialOverloading = false);
11007
11008 /// Add the call candidates from the given set of lookup results to the given
11009 /// overload set. Non-function lookup results are ignored.
11010 void AddOverloadedCallCandidates(
11011 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
11012 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
11013
11014 // An enum used to represent the different possible results of building a
11015 // range-based for loop.
11016 enum ForRangeStatus {
11017 FRS_Success,
11018 FRS_NoViableFunction,
11019 FRS_DiagnosticIssued
11020 };
11021
11022 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11023 /// given LookupResult is non-empty, it is assumed to describe a member which
11024 /// will be invoked. Otherwise, the function will be found via argument
11025 /// dependent lookup.
11026 /// CallExpr is set to a valid expression and FRS_Success returned on success,
11027 /// otherwise CallExpr is set to ExprError() and some non-success value
11028 /// is returned.
11029 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
11030 SourceLocation RangeLoc,
11031 const DeclarationNameInfo &NameInfo,
11032 LookupResult &MemberLookup,
11033 OverloadCandidateSet *CandidateSet,
11034 Expr *Range, ExprResult *CallExpr);
11035
11036 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11037 /// (which eventually refers to the declaration Func) and the call
11038 /// arguments Args/NumArgs, attempt to resolve the function call down
11039 /// to a specific function. If overload resolution succeeds, returns
11040 /// the call expression produced by overload resolution.
11041 /// Otherwise, emits diagnostics and returns ExprError.
11042 ExprResult BuildOverloadedCallExpr(
11043 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
11044 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
11045 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
11046
11047 /// Constructs and populates an OverloadedCandidateSet from
11048 /// the given function.
11049 /// \returns true when an the ExprResult output parameter has been set.
11050 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
11051 MultiExprArg Args, SourceLocation RParenLoc,
11052 OverloadCandidateSet *CandidateSet,
11053 ExprResult *Result);
11054
11055 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
11056 NestedNameSpecifierLoc NNSLoc,
11057 DeclarationNameInfo DNI,
11058 const UnresolvedSetImpl &Fns,
11059 bool PerformADL = true);
11060
11061 /// Perform lookup for an overloaded unary operator.
11062 void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet,
11063 OverloadedOperatorKind Op,
11064 const UnresolvedSetImpl &Fns,
11065 ArrayRef<Expr *> Args, bool RequiresADL = true);
11066
11067 /// Create a unary operation that may resolve to an overloaded
11068 /// operator.
11069 ///
11070 /// \param OpLoc The location of the operator itself (e.g., '*').
11071 ///
11072 /// \param Opc The UnaryOperatorKind that describes this operator.
11073 ///
11074 /// \param Fns The set of non-member functions that will be
11075 /// considered by overload resolution. The caller needs to build this
11076 /// set based on the context using, e.g.,
11077 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11078 /// set should not contain any member functions; those will be added
11079 /// by CreateOverloadedUnaryOp().
11080 ///
11081 /// \param Input The input argument.
11082 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
11083 UnaryOperatorKind Opc,
11084 const UnresolvedSetImpl &Fns, Expr *input,
11085 bool RequiresADL = true);
11086
11087 /// Perform lookup for an overloaded binary operator.
11088 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
11089 OverloadedOperatorKind Op,
11090 const UnresolvedSetImpl &Fns,
11091 ArrayRef<Expr *> Args, bool RequiresADL = true);
11092
11093 /// Create a binary operation that may resolve to an overloaded
11094 /// operator.
11095 ///
11096 /// \param OpLoc The location of the operator itself (e.g., '+').
11097 ///
11098 /// \param Opc The BinaryOperatorKind that describes this operator.
11099 ///
11100 /// \param Fns The set of non-member functions that will be
11101 /// considered by overload resolution. The caller needs to build this
11102 /// set based on the context using, e.g.,
11103 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11104 /// set should not contain any member functions; those will be added
11105 /// by CreateOverloadedBinOp().
11106 ///
11107 /// \param LHS Left-hand argument.
11108 /// \param RHS Right-hand argument.
11109 /// \param PerformADL Whether to consider operator candidates found by ADL.
11110 /// \param AllowRewrittenCandidates Whether to consider candidates found by
11111 /// C++20 operator rewrites.
11112 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
11113 /// the function in question. Such a function is never a candidate in
11114 /// our overload resolution. This also enables synthesizing a three-way
11115 /// comparison from < and == as described in C++20 [class.spaceship]p1.
11116 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
11117 const UnresolvedSetImpl &Fns, Expr *LHS,
11118 Expr *RHS, bool RequiresADL = true,
11119 bool AllowRewrittenCandidates = true,
11120 FunctionDecl *DefaultedFn = nullptr);
11121 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
11122 const UnresolvedSetImpl &Fns,
11123 Expr *LHS, Expr *RHS,
11124 FunctionDecl *DefaultedFn);
11125
11126 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11127 SourceLocation RLoc, Expr *Base,
11128 MultiExprArg Args);
11129
11130 /// BuildCallToMemberFunction - Build a call to a member
11131 /// function. MemExpr is the expression that refers to the member
11132 /// function (and includes the object parameter), Args/NumArgs are the
11133 /// arguments to the function call (not including the object
11134 /// parameter). The caller needs to validate that the member
11135 /// expression refers to a non-static member function or an overloaded
11136 /// member function.
11137 ExprResult BuildCallToMemberFunction(
11138 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
11139 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
11140 bool IsExecConfig = false, bool AllowRecovery = false);
11141
11142 /// BuildCallToObjectOfClassType - Build a call to an object of class
11143 /// type (C++ [over.call.object]), which can end up invoking an
11144 /// overloaded function call operator (@c operator()) or performing a
11145 /// user-defined conversion on the object argument.
11146 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
11147 SourceLocation LParenLoc,
11148 MultiExprArg Args,
11149 SourceLocation RParenLoc);
11150
11151 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11152 /// (if one exists), where @c Base is an expression of class type and
11153 /// @c Member is the name of the member we're trying to find.
11154 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
11155 SourceLocation OpLoc,
11156 bool *NoArrowOperatorFound = nullptr);
11157
11158 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
11159 CXXConversionDecl *Method,
11160 bool HadMultipleCandidates);
11161
11162 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11163 /// to a literal operator described by the provided lookup results.
11164 ExprResult BuildLiteralOperatorCall(
11165 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
11166 SourceLocation LitEndLoc,
11167 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11168
11169 /// FixOverloadedFunctionReference - E is an expression that refers to
11170 /// a C++ overloaded function (possibly with some parentheses and
11171 /// perhaps a '&' around it). We have resolved the overloaded function
11172 /// to the function declaration Fn, so patch up the expression E to
11173 /// refer (possibly indirectly) to Fn. Returns the new expr.
11174 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
11175 FunctionDecl *Fn);
11176 ExprResult FixOverloadedFunctionReference(ExprResult,
11177 DeclAccessPair FoundDecl,
11178 FunctionDecl *Fn);
11179
11180 /// - Returns a selector which best matches given argument list or
11181 /// nullptr if none could be found
11182 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11183 bool IsInstance,
11184 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11185
11186 ///@}
11187
11188 //
11189 //
11190 // -------------------------------------------------------------------------
11191 //
11192 //
11193
11194 /// \name Statements
11195 /// Implementations are in SemaStmt.cpp
11196 ///@{
11197
11198public:
11199 /// Stack of active SEH __finally scopes. Can be empty.
11200 SmallVector<Scope *, 2> CurrentSEHFinally;
11201
11202 /// Stack of '_Defer' statements that are currently being parsed, as well
11203 /// as the locations of their '_Defer' keywords. Can be empty.
11204 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11205
11206 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11207 StmtResult ActOnExprStmtError();
11208
11209 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11210 bool HasLeadingEmptyMacro = false);
11211
11212 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11213 SourceLocation EndLoc);
11214 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11215
11216 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11217 /// whose result is unused, warn.
11218 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11219
11220 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11221 void ActOnAfterCompoundStatementLeadingPragmas();
11222 void ActOnFinishOfCompoundStmt();
11223 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11224 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11225
11226 sema::CompoundScopeInfo &getCurCompoundScope() const;
11227
11228 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11229 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11230 SourceLocation DotDotDotLoc, ExprResult RHS,
11231 SourceLocation ColonLoc);
11232
11233 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11234 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11235
11236 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11237 SourceLocation ColonLoc, Stmt *SubStmt,
11238 Scope *CurScope);
11239 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11240 SourceLocation ColonLoc, Stmt *SubStmt);
11241
11242 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11243 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11244 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11245 Stmt *SubStmt);
11246
11247 /// Check whether the given statement can have musttail applied to it,
11248 /// issuing a diagnostic and returning false if not. In the success case,
11249 /// the statement is rewritten to remove implicit nodes from the return
11250 /// value.
11251 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11252
11253 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11254 SourceLocation LParenLoc, Stmt *InitStmt,
11255 ConditionResult Cond, SourceLocation RParenLoc,
11256 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11257 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11258 SourceLocation LParenLoc, Stmt *InitStmt,
11259 ConditionResult Cond, SourceLocation RParenLoc,
11260 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11261
11262 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11263
11264 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11265 SourceLocation LParenLoc, Stmt *InitStmt,
11266 ConditionResult Cond,
11267 SourceLocation RParenLoc);
11268 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11269 Stmt *Body);
11270
11271 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11272 /// integer not in the range of enum values.
11273 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11274 Expr *SrcExpr);
11275
11276 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11277 ConditionResult Cond, SourceLocation RParenLoc,
11278 Stmt *Body);
11279 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11280 SourceLocation WhileLoc, SourceLocation CondLParen,
11281 Expr *Cond, SourceLocation CondRParen);
11282
11283 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11284 Stmt *First, ConditionResult Second,
11285 FullExprArg Third, SourceLocation RParenLoc,
11286 Stmt *Body);
11287
11288 /// In an Objective C collection iteration statement:
11289 /// for (x in y)
11290 /// x can be an arbitrary l-value expression. Bind it up as a
11291 /// full-expression.
11292 StmtResult ActOnForEachLValueExpr(Expr *E);
11293
11294 enum BuildForRangeKind {
11295 /// Initial building of a for-range statement.
11296 BFRK_Build,
11297 /// Instantiation or recovery rebuild of a for-range statement. Don't
11298 /// attempt any typo-correction.
11299 BFRK_Rebuild,
11300 /// Determining whether a for-range statement could be built. Avoid any
11301 /// unnecessary or irreversible actions.
11302 BFRK_Check
11303 };
11304
11305 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11306 ///
11307 /// C++11 [stmt.ranged]:
11308 /// A range-based for statement is equivalent to
11309 ///
11310 /// {
11311 /// auto && __range = range-init;
11312 /// for ( auto __begin = begin-expr,
11313 /// __end = end-expr;
11314 /// __begin != __end;
11315 /// ++__begin ) {
11316 /// for-range-declaration = *__begin;
11317 /// statement
11318 /// }
11319 /// }
11320 ///
11321 /// The body of the loop is not available yet, since it cannot be analysed
11322 /// until we have determined the type of the for-range-declaration.
11323 StmtResult ActOnCXXForRangeStmt(
11324 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11325 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11326 SourceLocation RParenLoc, BuildForRangeKind Kind,
11327 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11328
11329 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11330 StmtResult BuildCXXForRangeStmt(
11331 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11332 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11333 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11334 BuildForRangeKind Kind,
11335 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11336
11337 /// Set the type of a for-range declaration whose for-range or expansion
11338 /// initialiser is dependent.
11339 void ActOnDependentForRangeInitializer(VarDecl *LoopVar,
11340 BuildForRangeKind BFRK);
11341
11342 /// Holds the 'begin' and 'end' variables of a range-based for loop or
11343 /// expansion statement; begin-expr and end-expr are also provided; the
11344 /// latter are used in some diagnostics.
11345 struct ForRangeBeginEndInfo {
11346 VarDecl *BeginVar = nullptr;
11347 VarDecl *EndVar = nullptr;
11348 Expr *BeginExpr = nullptr;
11349 Expr *EndExpr = nullptr;
11350 bool isValid() const { return BeginVar != nullptr && EndVar != nullptr; }
11351 };
11352
11353 /// Determine begin-expr and end-expr and build variable declarations for
11354 /// them as per [stmt.ranged].
11355 ForRangeBeginEndInfo BuildCXXForRangeBeginEndVars(
11356 Scope *S, VarDecl *RangeVar, SourceLocation ColonLoc,
11357 SourceLocation CoawaitLoc,
11358 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps,
11359 BuildForRangeKind Kind, bool IsConstexpr,
11360 StmtResult *RebuildResult = nullptr,
11361 llvm::function_ref<StmtResult()> RebuildWithDereference = {},
11362 IdentifierInfo *BeginName = nullptr, IdentifierInfo *EndName = nullptr);
11363
11364 /// Helper used by the expansion statements and for-range code to build
11365 /// a variable declaration for e.g. 'begin' and 'end'.
11366 VarDecl *BuildForRangeVarDecl(SourceLocation Loc, QualType Type,
11367 IdentifierInfo *Name, bool IsConstexpr);
11368
11369 /// Build the range variable of a range-based for loop or iterating
11370 /// expansion statement and return its DeclStmt.
11371 StmtResult BuildCXXForRangeRangeVar(Scope *S, Expr *Range, QualType Type,
11372 bool IsConstexpr = false);
11373
11374 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11375 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11376 /// body cannot be performed until after the type of the range variable is
11377 /// determined.
11378 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11379
11380 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11381 LabelDecl *TheDecl);
11382 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11383 SourceLocation StarLoc, Expr *DestExp);
11384 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11385 LabelDecl *Label, SourceLocation LabelLoc);
11386 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11387 LabelDecl *Label, SourceLocation LabelLoc);
11388
11389 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11390 void ActOnDeferStmtError(Scope *CurScope);
11391 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11392
11393 struct NamedReturnInfo {
11394 const VarDecl *Candidate;
11395
11396 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11397 Status S;
11398
11399 bool isMoveEligible() const { return S != None; };
11400 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11401 };
11402 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11403
11404 /// Determine whether the given expression might be move-eligible or
11405 /// copy-elidable in either a (co_)return statement or throw expression,
11406 /// without considering function return type, if applicable.
11407 ///
11408 /// \param E The expression being returned from the function or block,
11409 /// being thrown, or being co_returned from a coroutine. This expression
11410 /// might be modified by the implementation.
11411 ///
11412 /// \param Mode Overrides detection of current language mode
11413 /// and uses the rules for C++23.
11414 ///
11415 /// \returns An aggregate which contains the Candidate and isMoveEligible
11416 /// and isCopyElidable methods. If Candidate is non-null, it means
11417 /// isMoveEligible() would be true under the most permissive language
11418 /// standard.
11419 NamedReturnInfo getNamedReturnInfo(
11420 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11421
11422 /// Determine whether the given NRVO candidate variable is move-eligible or
11423 /// copy-elidable, without considering function return type.
11424 ///
11425 /// \param VD The NRVO candidate variable.
11426 ///
11427 /// \returns An aggregate which contains the Candidate and isMoveEligible
11428 /// and isCopyElidable methods. If Candidate is non-null, it means
11429 /// isMoveEligible() would be true under the most permissive language
11430 /// standard.
11431 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11432
11433 /// Updates given NamedReturnInfo's move-eligible and
11434 /// copy-elidable statuses, considering the function
11435 /// return type criteria as applicable to return statements.
11436 ///
11437 /// \param Info The NamedReturnInfo object to update.
11438 ///
11439 /// \param ReturnType This is the return type of the function.
11440 /// \returns The copy elision candidate, in case the initial return expression
11441 /// was copy elidable, or nullptr otherwise.
11442 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11443 QualType ReturnType);
11444
11445 /// Perform the initialization of a potentially-movable value, which
11446 /// is the result of return value.
11447 ///
11448 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11449 /// treat returned lvalues as rvalues in certain cases (to prefer move
11450 /// construction), then falls back to treating them as lvalues if that failed.
11451 ExprResult
11452 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11453 const NamedReturnInfo &NRInfo, Expr *Value,
11454 bool SupressSimplerImplicitMoves = false);
11455
11456 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11457
11458 /// Deduce the return type for a function from a returned expression, per
11459 /// C++1y [dcl.spec.auto]p6.
11460 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11461 SourceLocation ReturnLoc, Expr *RetExpr,
11462 const AutoType *AT);
11463
11464 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11465 Scope *CurScope);
11466 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11467 bool AllowRecovery = false);
11468
11469 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11470 /// for capturing scopes.
11471 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11472 NamedReturnInfo &NRInfo,
11473 bool SupressSimplerImplicitMoves);
11474
11475 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11476 /// and creates a proper catch handler from them.
11477 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11478 Stmt *HandlerBlock);
11479
11480 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11481 /// handlers and creates a try statement from them.
11482 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11483 ArrayRef<Stmt *> Handlers);
11484
11485 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11486
11487 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11488 SourceLocation TryLoc, Stmt *TryBlock,
11489 Stmt *Handler);
11490 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11491 Stmt *Block);
11492 void ActOnStartSEHFinallyBlock();
11493 void ActOnAbortSEHFinallyBlock();
11494 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11495 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11496
11497 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11498 bool IsIfExists,
11499 NestedNameSpecifierLoc QualifierLoc,
11500 DeclarationNameInfo NameInfo,
11501 Stmt *Nested);
11502 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11503 bool IsIfExists, CXXScopeSpec &SS,
11504 UnqualifiedId &Name, Stmt *Nested);
11505
11506 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11507 CapturedRegionKind Kind, unsigned NumParams);
11508 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11509 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11510 CapturedRegionKind Kind,
11511 ArrayRef<CapturedParamNameType> Params,
11512 unsigned OpenMPCaptureLevel = 0);
11513 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11514 void ActOnCapturedRegionError();
11515 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11516 SourceLocation Loc,
11517 unsigned NumParams);
11518
11519 void ApplyForRangeOrExpansionStatementLifetimeExtension(
11520 VarDecl *RangeVar, ArrayRef<MaterializeTemporaryExpr *> Temporaries);
11521
11522private:
11523 /// Check whether the given statement can have musttail applied to it,
11524 /// issuing a diagnostic and returning false if not.
11525 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11526
11527 ///@}
11528
11529 //
11530 //
11531 // -------------------------------------------------------------------------
11532 //
11533 //
11534
11535 /// \name `inline asm` Statement
11536 /// Implementations are in SemaStmtAsm.cpp
11537 ///@{
11538
11539public:
11540 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel,
11541 bool IsConstexpr = false);
11542 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11543 bool IsVolatile, unsigned NumOutputs,
11544 unsigned NumInputs, IdentifierInfo **Names,
11545 MultiExprArg Constraints, MultiExprArg Exprs,
11546 Expr *AsmString, MultiExprArg Clobbers,
11547 unsigned NumLabels, SourceLocation RParenLoc);
11548
11549 void FillInlineAsmIdentifierInfo(Expr *Res,
11550 llvm::InlineAsmIdentifierInfo &Info);
11551 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11552 SourceLocation TemplateKWLoc,
11553 UnqualifiedId &Id,
11554 bool IsUnevaluatedContext);
11555 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11556 SourceLocation AsmLoc);
11557 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11558 SourceLocation AsmLoc);
11559 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11560 ArrayRef<Token> AsmToks, StringRef AsmString,
11561 unsigned NumOutputs, unsigned NumInputs,
11562 ArrayRef<StringRef> Constraints,
11563 ArrayRef<StringRef> Clobbers,
11564 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11565 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11566 SourceLocation Location, bool AlwaysCreate);
11567
11568 ///@}
11569
11570 //
11571 //
11572 // -------------------------------------------------------------------------
11573 //
11574 //
11575
11576 /// \name Statement Attribute Handling
11577 /// Implementations are in SemaStmtAttr.cpp
11578 ///@{
11579
11580public:
11581 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11582 const AttributeCommonInfo &A);
11583 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11584 const AttributeCommonInfo &A);
11585
11586 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11587 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11588
11589 /// Process the attributes before creating an attributed statement. Returns
11590 /// the semantic attributes that have been processed.
11591 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11592 SmallVectorImpl<const Attr *> &OutAttrs);
11593
11594 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11595 SourceRange Range);
11596 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11597 const IdentifierInfo *AttrName,
11598 SourceRange Range);
11599
11600 ///@}
11601
11602 //
11603 //
11604 // -------------------------------------------------------------------------
11605 //
11606 //
11607
11608 /// \name C++ Templates
11609 /// Implementations are in SemaTemplate.cpp
11610 ///@{
11611
11612public:
11613 // Saves the current floating-point pragma stack and clear it in this Sema.
11614 class FpPragmaStackSaveRAII {
11615 public:
11616 FpPragmaStackSaveRAII(Sema &S)
11617 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11618 S.FpPragmaStack.Stack.clear();
11619 }
11620 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11621 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11622 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11623
11624 private:
11625 Sema &S;
11626 PragmaStack<FPOptionsOverride> SavedStack;
11627 };
11628
11629 void resetFPOptions(FPOptions FPO) {
11630 CurFPFeatures = FPO;
11631 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11632 }
11633
11634 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11635 return llvm::ArrayRef(InventedParameterInfos.begin() +
11636 InventedParameterInfosStart,
11637 InventedParameterInfos.end());
11638 }
11639
11640 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11641 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11642 FunctionScopes.end());
11643 }
11644
11645 typedef llvm::MapVector<const FunctionDecl *,
11646 std::unique_ptr<LateParsedTemplate>>
11647 LateParsedTemplateMapT;
11648 LateParsedTemplateMapT LateParsedTemplateMap;
11649
11650 /// Determine the number of levels of enclosing template parameters. This is
11651 /// only usable while parsing. Note that this does not include dependent
11652 /// contexts in which no template parameters have yet been declared, such as
11653 /// in a terse function template or generic lambda before the first 'auto' is
11654 /// encountered.
11655 unsigned getTemplateDepth(Scope *S) const;
11656
11657 void FilterAcceptableTemplateNames(LookupResult &R,
11658 bool AllowFunctionTemplates = true,
11659 bool AllowDependent = true);
11660 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11661 bool AllowFunctionTemplates = true,
11662 bool AllowDependent = true,
11663 bool AllowNonTemplateFunctions = false);
11664 /// Try to interpret the lookup result D as a template-name.
11665 ///
11666 /// \param D A declaration found by name lookup.
11667 /// \param AllowFunctionTemplates Whether function templates should be
11668 /// considered valid results.
11669 /// \param AllowDependent Whether unresolved using declarations (that might
11670 /// name templates) should be considered valid results.
11671 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11672 bool AllowFunctionTemplates = true,
11673 bool AllowDependent = true);
11674
11675 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11676 /// Whether and why a template name is required in this lookup.
11677 class RequiredTemplateKind {
11678 public:
11679 /// Template name is required if TemplateKWLoc is valid.
11680 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11681 : TemplateKW(TemplateKWLoc) {}
11682 /// Template name is unconditionally required.
11683 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11684
11685 SourceLocation getTemplateKeywordLoc() const {
11686 return TemplateKW.value_or(u: SourceLocation());
11687 }
11688 bool hasTemplateKeyword() const {
11689 return getTemplateKeywordLoc().isValid();
11690 }
11691 bool isRequired() const { return TemplateKW != SourceLocation(); }
11692 explicit operator bool() const { return isRequired(); }
11693
11694 private:
11695 std::optional<SourceLocation> TemplateKW;
11696 };
11697
11698 enum class AssumedTemplateKind {
11699 /// This is not assumed to be a template name.
11700 None,
11701 /// This is assumed to be a template name because lookup found nothing.
11702 FoundNothing,
11703 /// This is assumed to be a template name because lookup found one or more
11704 /// functions (but no function templates).
11705 FoundFunctions,
11706 };
11707
11708 bool
11709 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11710 QualType ObjectType, bool EnteringContext,
11711 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11712 AssumedTemplateKind *ATK = nullptr,
11713 bool AllowTypoCorrection = true);
11714
11715 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11716 bool hasTemplateKeyword,
11717 const UnqualifiedId &Name,
11718 ParsedType ObjectType, bool EnteringContext,
11719 TemplateTy &Template,
11720 bool &MemberOfUnknownSpecialization,
11721 bool AllowTypoCorrection = true);
11722
11723 /// Try to resolve an undeclared template name as a type template.
11724 ///
11725 /// Sets II to the identifier corresponding to the template name, and updates
11726 /// Name to a corresponding (typo-corrected) type template name and TNK to
11727 /// the corresponding kind, if possible.
11728 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11729 TemplateNameKind &TNK,
11730 SourceLocation NameLoc,
11731 IdentifierInfo *&II);
11732
11733 /// Determine whether a particular identifier might be the name in a C++1z
11734 /// deduction-guide declaration.
11735 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11736 SourceLocation NameLoc, CXXScopeSpec &SS,
11737 ParsedTemplateTy *Template = nullptr);
11738
11739 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11740 SourceLocation IILoc, Scope *S,
11741 const CXXScopeSpec *SS,
11742 TemplateTy &SuggestedTemplate,
11743 TemplateNameKind &SuggestedKind);
11744
11745 /// Determine whether we would be unable to instantiate this template (because
11746 /// it either has no definition, or is in the process of being instantiated).
11747 bool DiagnoseUninstantiableTemplate(
11748 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11749 bool InstantiatedFromMember, const NamedDecl *Pattern,
11750 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11751 bool Complain = true, bool *Unreachable = nullptr);
11752
11753 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11754 /// that the template parameter 'PrevDecl' is being shadowed by a new
11755 /// declaration at location Loc. Returns true to indicate that this is
11756 /// an error, and false otherwise.
11757 ///
11758 /// \param Loc The location of the declaration that shadows a template
11759 /// parameter.
11760 ///
11761 /// \param PrevDecl The template parameter that the declaration shadows.
11762 ///
11763 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11764 /// a warning for compatibility with older versions of clang.
11765 /// Ignored when MSVC compatibility is enabled.
11766 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11767 bool SupportedForCompatibility = false);
11768
11769 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11770 /// the parameter D to reference the templated declaration and return a
11771 /// pointer to the template declaration. Otherwise, do nothing to D and return
11772 /// null.
11773 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11774
11775 /// ActOnTypeParameter - Called when a C++ template type parameter
11776 /// (e.g., "typename T") has been parsed. Typename specifies whether
11777 /// the keyword "typename" was used to declare the type parameter
11778 /// (otherwise, "class" was used), and KeyLoc is the location of the
11779 /// "class" or "typename" keyword. ParamName is the name of the
11780 /// parameter (NULL indicates an unnamed template parameter) and
11781 /// ParamNameLoc is the location of the parameter name (if any).
11782 /// If the type parameter has a default argument, it will be added
11783 /// later via ActOnTypeParameterDefault.
11784 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11785 SourceLocation EllipsisLoc,
11786 SourceLocation KeyLoc,
11787 IdentifierInfo *ParamName,
11788 SourceLocation ParamNameLoc, unsigned Depth,
11789 unsigned Position, SourceLocation EqualLoc,
11790 ParsedType DefaultArg, bool HasTypeConstraint);
11791
11792 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11793
11794 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11795 TemplateIdAnnotation *TypeConstraint,
11796 TemplateTypeParmDecl *ConstrainedParameter,
11797 SourceLocation EllipsisLoc);
11798 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11799 TemplateIdAnnotation *TypeConstraint,
11800 TemplateTypeParmDecl *ConstrainedParameter,
11801 SourceLocation EllipsisLoc,
11802 bool AllowUnexpandedPack);
11803
11804 /// Attach a type-constraint to a template parameter.
11805 /// \returns true if an error occurred. This can happen if the
11806 /// immediately-declared constraint could not be formed (e.g. incorrect number
11807 /// of arguments for the named concept).
11808 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11809 DeclarationNameInfo NameInfo,
11810 TemplateName NamedConcept, NamedDecl *FoundDecl,
11811 const TemplateArgumentListInfo *TemplateArgs,
11812 TemplateTypeParmDecl *ConstrainedParameter,
11813 SourceLocation EllipsisLoc);
11814
11815 bool AttachTypeConstraint(AutoTypeLoc TL,
11816 NonTypeTemplateParmDecl *NewConstrainedParm,
11817 NonTypeTemplateParmDecl *OrigConstrainedParm,
11818 SourceLocation EllipsisLoc);
11819
11820 /// Require the given type to be a structural type, and diagnose if it is not.
11821 ///
11822 /// \return \c true if an error was produced.
11823 bool RequireStructuralType(QualType T, SourceLocation Loc);
11824
11825 /// Check that the type of a non-type template parameter is
11826 /// well-formed.
11827 ///
11828 /// \returns the (possibly-promoted) parameter type if valid;
11829 /// otherwise, produces a diagnostic and returns a NULL type.
11830 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11831 SourceLocation Loc);
11832 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11833
11834 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11835 unsigned Depth, unsigned Position,
11836 SourceLocation EqualLoc,
11837 Expr *DefaultArg);
11838
11839 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11840 /// parameter (e.g. T in template <template \<typename> class T> class array)
11841 /// has been parsed. S is the current scope.
11842 NamedDecl *ActOnTemplateTemplateParameter(
11843 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11844 bool TypenameKeyword, TemplateParameterList *Params,
11845 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11846 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11847 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11848
11849 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11850 /// constrained by RequiresClause, that contains the template parameters in
11851 /// Params.
11852 TemplateParameterList *ActOnTemplateParameterList(
11853 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11854 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11855 SourceLocation RAngleLoc, Expr *RequiresClause);
11856
11857 /// The context in which we are checking a template parameter list.
11858 enum TemplateParamListContext {
11859 // For this context, Class, Variable, TypeAlias, and non-pack Template
11860 // Template Parameters are treated uniformly.
11861 TPC_Other,
11862
11863 TPC_FunctionTemplate,
11864 TPC_ClassTemplateMember,
11865 TPC_FriendClassTemplate,
11866 TPC_FriendFunctionTemplate,
11867 TPC_FriendFunctionTemplateDefinition,
11868 TPC_TemplateTemplateParameterPack,
11869 };
11870
11871 /// Checks the validity of a template parameter list, possibly
11872 /// considering the template parameter list from a previous
11873 /// declaration.
11874 ///
11875 /// If an "old" template parameter list is provided, it must be
11876 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11877 /// template parameter list.
11878 ///
11879 /// \param NewParams Template parameter list for a new template
11880 /// declaration. This template parameter list will be updated with any
11881 /// default arguments that are carried through from the previous
11882 /// template parameter list.
11883 ///
11884 /// \param OldParams If provided, template parameter list from a
11885 /// previous declaration of the same template. Default template
11886 /// arguments will be merged from the old template parameter list to
11887 /// the new template parameter list.
11888 ///
11889 /// \param TPC Describes the context in which we are checking the given
11890 /// template parameter list.
11891 ///
11892 /// \param SkipBody If we might have already made a prior merged definition
11893 /// of this template visible, the corresponding body-skipping information.
11894 /// Default argument redefinition is not an error when skipping such a body,
11895 /// because (under the ODR) we can assume the default arguments are the same
11896 /// as the prior merged definition.
11897 ///
11898 /// \returns true if an error occurred, false otherwise.
11899 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11900 TemplateParameterList *OldParams,
11901 TemplateParamListContext TPC,
11902 SkipBodyInfo *SkipBody = nullptr);
11903
11904 /// Match the given template parameter lists to the given scope
11905 /// specifier, returning the template parameter list that applies to the
11906 /// name.
11907 ///
11908 /// \param DeclStartLoc the start of the declaration that has a scope
11909 /// specifier or a template parameter list.
11910 ///
11911 /// \param DeclLoc The location of the declaration itself.
11912 ///
11913 /// \param SS the scope specifier that will be matched to the given template
11914 /// parameter lists. This scope specifier precedes a qualified name that is
11915 /// being declared.
11916 ///
11917 /// \param TemplateId The template-id following the scope specifier, if there
11918 /// is one. Used to check for a missing 'template<>'.
11919 ///
11920 /// \param ParamLists the template parameter lists, from the outermost to the
11921 /// innermost template parameter lists.
11922 ///
11923 /// \param IsFriend Whether to apply the slightly different rules for
11924 /// matching template parameters to scope specifiers in friend
11925 /// declarations.
11926 ///
11927 /// \param IsMemberSpecialization will be set true if the scope specifier
11928 /// denotes a fully-specialized type, and therefore this is a declaration of
11929 /// a member specialization.
11930 ///
11931 /// \returns the template parameter list, if any, that corresponds to the
11932 /// name that is preceded by the scope specifier @p SS. This template
11933 /// parameter list may have template parameters (if we're declaring a
11934 /// template) or may have no template parameters (if we're declaring a
11935 /// template specialization), or may be NULL (if what we're declaring isn't
11936 /// itself a template).
11937 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11938 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11939 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11940 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11941 bool &IsMemberSpecialization, bool &Invalid,
11942 bool SuppressDiagnostic = false);
11943
11944 /// Returns the template parameter list with all default template argument
11945 /// information.
11946 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11947
11948 DeclResult CheckClassTemplate(
11949 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11950 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11951 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11952 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11953 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11954 TemplateParameterList **OuterTemplateParamLists,
11955 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11956
11957 /// Translates template arguments as provided by the parser
11958 /// into template arguments used by semantic analysis.
11959 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11960 TemplateArgumentListInfo &Out);
11961
11962 /// Convert a parsed type into a parsed template argument. This is mostly
11963 /// trivial, except that we may have parsed a C++17 deduced class template
11964 /// specialization type, in which case we should form a template template
11965 /// argument instead of a type template argument.
11966 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11967
11968 void NoteAllFoundTemplates(TemplateName Name);
11969
11970 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11971 TemplateName Template,
11972 SourceLocation TemplateLoc,
11973 TemplateArgumentListInfo &TemplateArgs,
11974 Scope *Scope, bool ForNestedNameSpecifier);
11975
11976 TypeResult
11977 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11978 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11979 SourceLocation TemplateKWLoc, TemplateTy Template,
11980 const IdentifierInfo *TemplateII,
11981 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11982 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11983 bool IsCtorOrDtorName = false, bool IsClassName = false,
11984 ImplicitTypenameContext AllowImplicitTypename =
11985 ImplicitTypenameContext::No);
11986
11987 /// Parsed an elaborated-type-specifier that refers to a template-id,
11988 /// such as \c class T::template apply<U>.
11989 TypeResult ActOnTagTemplateIdType(
11990 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11991 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11992 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11993 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11994
11995 DeclResult ActOnVarTemplateSpecialization(
11996 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11997 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11998 StorageClass SC, bool IsPartialSpecialization);
11999
12000 /// Get the specialization of the given variable template corresponding to
12001 /// the specified argument list, or a null-but-valid result if the arguments
12002 /// are dependent.
12003 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
12004 SourceLocation TemplateLoc,
12005 SourceLocation TemplateNameLoc,
12006 const TemplateArgumentListInfo &TemplateArgs,
12007 bool SetWrittenArgs);
12008
12009 /// Form a reference to the specialization of the given variable template
12010 /// corresponding to the specified argument list, or a null-but-valid result
12011 /// if the arguments are dependent.
12012 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
12013 const DeclarationNameInfo &NameInfo,
12014 VarTemplateDecl *Template, NamedDecl *FoundD,
12015 SourceLocation TemplateLoc,
12016 const TemplateArgumentListInfo *TemplateArgs);
12017
12018 ExprResult CheckVarOrConceptTemplateTemplateId(
12019 const DeclarationNameInfo &NameInfo, TemplateName Template,
12020 const TemplateArgumentListInfo *TemplateArgs);
12021
12022 ExprResult
12023 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12024 const DeclarationNameInfo &ConceptNameInfo,
12025 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
12026 const TemplateArgumentListInfo *TemplateArgs,
12027 bool DoCheckConstraintSatisfaction = true);
12028
12029 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
12030 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
12031 bool TemplateKeyword, TemplateDecl *TD,
12032 SourceLocation Loc);
12033
12034 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
12035 SourceLocation TemplateKWLoc, LookupResult &R,
12036 bool RequiresADL,
12037 const TemplateArgumentListInfo *TemplateArgs);
12038
12039 // We actually only call this from template instantiation.
12040 ExprResult
12041 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12042 const DeclarationNameInfo &NameInfo,
12043 const TemplateArgumentListInfo *TemplateArgs,
12044 bool IsAddressOfOperand);
12045
12046 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
12047 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
12048 }
12049
12050 TemplateArgument
12051 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
12052 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
12053 if (Arg.isPackExpansion())
12054 Arg = Arg.getPackExpansionPattern();
12055 return Arg;
12056 }
12057
12058 ExprResult
12059 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
12060 QualType ParamType, SourceLocation loc,
12061 TemplateArgument Replacement,
12062 UnsignedOrNone PackIndex, bool Final);
12063
12064 /// Form a template name from a name that is syntactically required to name a
12065 /// template, either due to use of the 'template' keyword or because a name in
12066 /// this syntactic context is assumed to name a template (C++
12067 /// [temp.names]p2-4).
12068 ///
12069 /// This action forms a template name given the name of the template and its
12070 /// optional scope specifier. This is used when the 'template' keyword is used
12071 /// or when the parsing context unambiguously treats a following '<' as
12072 /// introducing a template argument list. Note that this may produce a
12073 /// non-dependent template name if we can perform the lookup now and identify
12074 /// the named template.
12075 ///
12076 /// For example, given "x.MetaFun::template apply", the scope specifier
12077 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
12078 /// of the "template" keyword, and "apply" is the \p Name.
12079 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
12080 SourceLocation TemplateKWLoc,
12081 const UnqualifiedId &Name,
12082 ParsedType ObjectType,
12083 bool EnteringContext, TemplateTy &Template,
12084 bool AllowInjectedClassName = false);
12085
12086 DeclResult ActOnClassTemplateSpecialization(
12087 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
12088 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
12089 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
12090 MultiTemplateParamsArg TemplateParameterLists,
12091 SkipBodyInfo *SkipBody = nullptr);
12092
12093 /// Check the non-type template arguments of a class template
12094 /// partial specialization according to C++ [temp.class.spec]p9.
12095 ///
12096 /// \param TemplateNameLoc the location of the template name.
12097 /// \param PrimaryTemplate the template parameters of the primary class
12098 /// template.
12099 /// \param NumExplicit the number of explicitly-specified template arguments.
12100 /// \param TemplateArgs the template arguments of the class template
12101 /// partial specialization.
12102 ///
12103 /// \returns \c true if there was an error, \c false otherwise.
12104 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
12105 TemplateDecl *PrimaryTemplate,
12106 unsigned NumExplicitArgs,
12107 ArrayRef<TemplateArgument> Args);
12108 void CheckTemplatePartialSpecialization(
12109 ClassTemplatePartialSpecializationDecl *Partial);
12110 void CheckTemplatePartialSpecialization(
12111 VarTemplatePartialSpecializationDecl *Partial);
12112
12113 Decl *ActOnTemplateDeclarator(Scope *S,
12114 MultiTemplateParamsArg TemplateParameterLists,
12115 Declarator &D);
12116
12117 /// Diagnose cases where we have an explicit template specialization
12118 /// before/after an explicit template instantiation, producing diagnostics
12119 /// for those cases where they are required and determining whether the
12120 /// new specialization/instantiation will have any effect.
12121 ///
12122 /// \param NewLoc the location of the new explicit specialization or
12123 /// instantiation.
12124 ///
12125 /// \param NewTSK the kind of the new explicit specialization or
12126 /// instantiation.
12127 ///
12128 /// \param PrevDecl the previous declaration of the entity.
12129 ///
12130 /// \param PrevTSK the kind of the old explicit specialization or
12131 /// instantiatin.
12132 ///
12133 /// \param PrevPointOfInstantiation if valid, indicates where the previous
12134 /// declaration was instantiated (either implicitly or explicitly).
12135 ///
12136 /// \param HasNoEffect will be set to true to indicate that the new
12137 /// specialization or instantiation has no effect and should be ignored.
12138 ///
12139 /// \returns true if there was an error that should prevent the introduction
12140 /// of the new declaration into the AST, false otherwise.
12141 bool CheckSpecializationInstantiationRedecl(
12142 SourceLocation NewLoc,
12143 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
12144 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
12145 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
12146
12147 /// Perform semantic analysis for the given dependent function
12148 /// template specialization.
12149 ///
12150 /// The only possible way to get a dependent function template specialization
12151 /// is with a friend declaration, like so:
12152 ///
12153 /// \code
12154 /// template \<class T> void foo(T);
12155 /// template \<class T> class A {
12156 /// friend void foo<>(T);
12157 /// };
12158 /// \endcode
12159 ///
12160 /// There really isn't any useful analysis we can do here, so we
12161 /// just store the information.
12162 bool CheckDependentFunctionTemplateSpecialization(
12163 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
12164 LookupResult &Previous);
12165
12166 /// Perform semantic analysis for the given function template
12167 /// specialization.
12168 ///
12169 /// This routine performs all of the semantic analysis required for an
12170 /// explicit function template specialization. On successful completion,
12171 /// the function declaration \p FD will become a function template
12172 /// specialization.
12173 ///
12174 /// \param FD the function declaration, which will be updated to become a
12175 /// function template specialization.
12176 ///
12177 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
12178 /// if any. Note that this may be valid info even when 0 arguments are
12179 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
12180 /// as it anyway contains info on the angle brackets locations.
12181 ///
12182 /// \param Previous the set of declarations that may be specialized by
12183 /// this function specialization.
12184 ///
12185 /// \param QualifiedFriend whether this is a lookup for a qualified friend
12186 /// declaration with no explicit template argument list that might be
12187 /// befriending a function template specialization.
12188 bool CheckFunctionTemplateSpecialization(
12189 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
12190 LookupResult &Previous, bool QualifiedFriend = false);
12191
12192 /// Perform semantic analysis for the given non-template member
12193 /// specialization.
12194 ///
12195 /// This routine performs all of the semantic analysis required for an
12196 /// explicit member function specialization. On successful completion,
12197 /// the function declaration \p FD will become a member function
12198 /// specialization.
12199 ///
12200 /// \param Member the member declaration, which will be updated to become a
12201 /// specialization.
12202 ///
12203 /// \param Previous the set of declarations, one of which may be specialized
12204 /// by this function specialization; the set will be modified to contain the
12205 /// redeclared member.
12206 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12207 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12208
12209 // Explicit instantiation of a class template specialization
12210 DeclResult ActOnExplicitInstantiation(
12211 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12212 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12213 TemplateTy Template, SourceLocation TemplateNameLoc,
12214 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12215 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12216
12217 // Explicit instantiation of a member class of a class template.
12218 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12219 SourceLocation TemplateLoc,
12220 unsigned TagSpec, SourceLocation KWLoc,
12221 CXXScopeSpec &SS, IdentifierInfo *Name,
12222 SourceLocation NameLoc,
12223 const ParsedAttributesView &Attr);
12224
12225 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12226 SourceLocation TemplateLoc,
12227 Declarator &D);
12228
12229 /// If the given template parameter has a default template
12230 /// argument, substitute into that default template argument and
12231 /// return the corresponding template argument.
12232 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12233 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12234 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12235 ArrayRef<TemplateArgument> SugaredConverted,
12236 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12237
12238 /// Returns the top most location responsible for the definition of \p N.
12239 /// If \p N is a a template specialization, this is the location
12240 /// of the top of the instantiation stack.
12241 /// Otherwise, the location of \p N is returned.
12242 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12243
12244 /// Specifies the context in which a particular template
12245 /// argument is being checked.
12246 enum CheckTemplateArgumentKind {
12247 /// The template argument was specified in the code or was
12248 /// instantiated with some deduced template arguments.
12249 CTAK_Specified,
12250
12251 /// The template argument was deduced via template argument
12252 /// deduction.
12253 CTAK_Deduced,
12254
12255 /// The template argument was deduced from an array bound
12256 /// via template argument deduction.
12257 CTAK_DeducedFromArrayBound
12258 };
12259
12260 struct CheckTemplateArgumentInfo {
12261 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12262 bool MatchingTTP = false)
12263 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12264 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12265 CheckTemplateArgumentInfo &
12266 operator=(const CheckTemplateArgumentInfo &) = delete;
12267
12268 /// The checked, converted argument will be added to the
12269 /// end of these vectors.
12270 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12271
12272 /// The check is being performed in the context of partial ordering.
12273 bool PartialOrdering;
12274
12275 /// If true, assume these template arguments are
12276 /// the injected template arguments for a template template parameter.
12277 /// This will relax the requirement that all its possible uses are valid:
12278 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12279 /// during instantiation.
12280 bool MatchingTTP;
12281
12282 /// Is set to true when, in the context of TTP matching, a pack parameter
12283 /// matches non-pack arguments.
12284 bool StrictPackMatch = false;
12285 };
12286
12287 /// Check that the given template argument corresponds to the given
12288 /// template parameter.
12289 ///
12290 /// \param Param The template parameter against which the argument will be
12291 /// checked.
12292 ///
12293 /// \param Arg The template argument, which may be updated due to conversions.
12294 ///
12295 /// \param Template The template in which the template argument resides.
12296 ///
12297 /// \param TemplateLoc The location of the template name for the template
12298 /// whose argument list we're matching.
12299 ///
12300 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12301 /// the template argument list.
12302 ///
12303 /// \param ArgumentPackIndex The index into the argument pack where this
12304 /// argument will be placed. Only valid if the parameter is a parameter pack.
12305 ///
12306 /// \param CTAK Describes how we arrived at this particular template argument:
12307 /// explicitly written, deduced, etc.
12308 ///
12309 /// \returns true on error, false otherwise.
12310 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12311 NamedDecl *Template, SourceLocation TemplateLoc,
12312 SourceLocation RAngleLoc,
12313 unsigned ArgumentPackIndex,
12314 CheckTemplateArgumentInfo &CTAI,
12315 CheckTemplateArgumentKind CTAK);
12316
12317 /// Check that the given template arguments can be provided to
12318 /// the given template, converting the arguments along the way.
12319 ///
12320 /// \param Template The template to which the template arguments are being
12321 /// provided.
12322 ///
12323 /// \param TemplateLoc The location of the template name in the source.
12324 ///
12325 /// \param TemplateArgs The list of template arguments. If the template is
12326 /// a template template parameter, this function may extend the set of
12327 /// template arguments to also include substituted, defaulted template
12328 /// arguments.
12329 ///
12330 /// \param PartialTemplateArgs True if the list of template arguments is
12331 /// intentionally partial, e.g., because we're checking just the initial
12332 /// set of template arguments.
12333 ///
12334 /// \param Converted Will receive the converted, canonicalized template
12335 /// arguments.
12336 ///
12337 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12338 /// contain the converted forms of the template arguments as written.
12339 /// Otherwise, \p TemplateArgs will not be modified.
12340 ///
12341 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12342 /// receive true if the cause for the error is the associated constraints of
12343 /// the template not being satisfied by the template arguments.
12344 ///
12345 /// \param DefaultArgs any default arguments from template specialization
12346 /// deduction.
12347 ///
12348 /// \returns true if an error occurred, false otherwise.
12349 bool CheckTemplateArgumentList(TemplateDecl *Template,
12350 SourceLocation TemplateLoc,
12351 TemplateArgumentListInfo &TemplateArgs,
12352 const DefaultArguments &DefaultArgs,
12353 bool PartialTemplateArgs,
12354 CheckTemplateArgumentInfo &CTAI,
12355 bool UpdateArgsWithConversions = true,
12356 bool *ConstraintsNotSatisfied = nullptr);
12357
12358 bool CheckTemplateArgumentList(
12359 TemplateDecl *Template, TemplateParameterList *Params,
12360 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12361 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12362 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12363 bool *ConstraintsNotSatisfied = nullptr);
12364
12365 bool CheckTemplateTypeArgument(
12366 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12367 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12368 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12369
12370 /// Check a template argument against its corresponding
12371 /// template type parameter.
12372 ///
12373 /// This routine implements the semantics of C++ [temp.arg.type]. It
12374 /// returns true if an error occurred, and false otherwise.
12375 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12376
12377 /// Check a template argument against its corresponding
12378 /// non-type template parameter.
12379 ///
12380 /// This routine implements the semantics of C++ [temp.arg.nontype].
12381 /// If an error occurred, it returns ExprError(); otherwise, it
12382 /// returns the converted template argument. \p ParamType is the
12383 /// type of the non-type template parameter after it has been instantiated.
12384 ExprResult CheckTemplateArgument(NamedDecl *Param,
12385 QualType InstantiatedParamType, Expr *Arg,
12386 TemplateArgument &SugaredConverted,
12387 TemplateArgument &CanonicalConverted,
12388 bool StrictCheck,
12389 CheckTemplateArgumentKind CTAK);
12390
12391 /// Check a template argument against its corresponding
12392 /// template template parameter.
12393 ///
12394 /// This routine implements the semantics of C++ [temp.arg.template].
12395 /// It returns true if an error occurred, and false otherwise.
12396 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12397 TemplateParameterList *Params,
12398 TemplateArgumentLoc &Arg,
12399 bool PartialOrdering,
12400 bool *StrictPackMatch);
12401
12402 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12403 TemplateTemplateParmDecl *Param,
12404 const TemplateArgumentLoc &Arg);
12405
12406 void NoteTemplateLocation(const NamedDecl &Decl,
12407 std::optional<SourceRange> ParamRange = {});
12408 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12409
12410 /// Given a non-type template argument that refers to a
12411 /// declaration and the type of its corresponding non-type template
12412 /// parameter, produce an expression that properly refers to that
12413 /// declaration.
12414 /// FIXME: This is used in some contexts where the resulting expression
12415 /// doesn't need to live too long. It would be useful if this function
12416 /// could return a temporary expression.
12417 ExprResult BuildExpressionFromDeclTemplateArgument(
12418 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12419 ExprResult
12420 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12421 SourceLocation Loc);
12422
12423 /// Enumeration describing how template parameter lists are compared
12424 /// for equality.
12425 enum TemplateParameterListEqualKind {
12426 /// We are matching the template parameter lists of two templates
12427 /// that might be redeclarations.
12428 ///
12429 /// \code
12430 /// template<typename T> struct X;
12431 /// template<typename T> struct X;
12432 /// \endcode
12433 TPL_TemplateMatch,
12434
12435 /// We are matching the template parameter lists of two template
12436 /// template parameters as part of matching the template parameter lists
12437 /// of two templates that might be redeclarations.
12438 ///
12439 /// \code
12440 /// template<template<int I> class TT> struct X;
12441 /// template<template<int Value> class Other> struct X;
12442 /// \endcode
12443 TPL_TemplateTemplateParmMatch,
12444
12445 /// We are determining whether the template-parameters are equivalent
12446 /// according to C++ [temp.over.link]/6. This comparison does not consider
12447 /// constraints.
12448 ///
12449 /// \code
12450 /// template<C1 T> void f(T);
12451 /// template<C2 T> void f(T);
12452 /// \endcode
12453 TPL_TemplateParamsEquivalent,
12454 };
12455
12456 // A struct to represent the 'new' declaration, which is either itself just
12457 // the named decl, or the important information we need about it in order to
12458 // do constraint comparisons.
12459 class TemplateCompareNewDeclInfo {
12460 const NamedDecl *ND = nullptr;
12461 const DeclContext *DC = nullptr;
12462 const DeclContext *LexicalDC = nullptr;
12463 SourceLocation Loc;
12464
12465 public:
12466 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12467 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12468 const DeclContext *LexicalDeclCtx,
12469 SourceLocation Loc)
12470
12471 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12472 assert(DC && LexicalDC &&
12473 "Constructor only for cases where we have the information to put "
12474 "in here");
12475 }
12476
12477 // If this was constructed with no information, we cannot do substitution
12478 // for constraint comparison, so make sure we can check that.
12479 bool isInvalid() const { return !ND && !DC; }
12480
12481 const NamedDecl *getDecl() const { return ND; }
12482
12483 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12484
12485 const DeclContext *getLexicalDeclContext() const {
12486 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12487 }
12488
12489 const DeclContext *getDeclContext() const {
12490 return ND ? ND->getDeclContext() : DC;
12491 }
12492
12493 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12494 };
12495
12496 /// Determine whether the given template parameter lists are
12497 /// equivalent.
12498 ///
12499 /// \param New The new template parameter list, typically written in the
12500 /// source code as part of a new template declaration.
12501 ///
12502 /// \param Old The old template parameter list, typically found via
12503 /// name lookup of the template declared with this template parameter
12504 /// list.
12505 ///
12506 /// \param Complain If true, this routine will produce a diagnostic if
12507 /// the template parameter lists are not equivalent.
12508 ///
12509 /// \param Kind describes how we are to match the template parameter lists.
12510 ///
12511 /// \param TemplateArgLoc If this source location is valid, then we
12512 /// are actually checking the template parameter list of a template
12513 /// argument (New) against the template parameter list of its
12514 /// corresponding template template parameter (Old). We produce
12515 /// slightly different diagnostics in this scenario.
12516 ///
12517 /// \returns True if the template parameter lists are equal, false
12518 /// otherwise.
12519 bool TemplateParameterListsAreEqual(
12520 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12521 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12522 TemplateParameterListEqualKind Kind,
12523 SourceLocation TemplateArgLoc = SourceLocation());
12524
12525 bool TemplateParameterListsAreEqual(
12526 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12527 TemplateParameterListEqualKind Kind,
12528 SourceLocation TemplateArgLoc = SourceLocation()) {
12529 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12530 Kind, TemplateArgLoc);
12531 }
12532
12533 /// Check whether a template can be declared within this scope.
12534 ///
12535 /// If the template declaration is valid in this scope, returns
12536 /// false. Otherwise, issues a diagnostic and returns true.
12537 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12538
12539 /// Called when the parser has parsed a C++ typename
12540 /// specifier, e.g., "typename T::type".
12541 ///
12542 /// \param S The scope in which this typename type occurs.
12543 /// \param TypenameLoc the location of the 'typename' keyword
12544 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12545 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12546 /// \param IdLoc the location of the identifier.
12547 /// \param IsImplicitTypename context where T::type refers to a type.
12548 TypeResult ActOnTypenameType(
12549 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12550 const IdentifierInfo &II, SourceLocation IdLoc,
12551 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12552
12553 /// Called when the parser has parsed a C++ typename
12554 /// specifier that ends in a template-id, e.g.,
12555 /// "typename MetaFun::template apply<T1, T2>".
12556 ///
12557 /// \param S The scope in which this typename type occurs.
12558 /// \param TypenameLoc the location of the 'typename' keyword
12559 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12560 /// \param TemplateLoc the location of the 'template' keyword, if any.
12561 /// \param TemplateName The template name.
12562 /// \param TemplateII The identifier used to name the template.
12563 /// \param TemplateIILoc The location of the template name.
12564 /// \param LAngleLoc The location of the opening angle bracket ('<').
12565 /// \param TemplateArgs The template arguments.
12566 /// \param RAngleLoc The location of the closing angle bracket ('>').
12567 TypeResult
12568 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12569 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12570 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12571 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12572 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12573
12574 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12575 SourceLocation KeywordLoc,
12576 NestedNameSpecifierLoc QualifierLoc,
12577 const IdentifierInfo &II, SourceLocation IILoc,
12578 TypeSourceInfo **TSI, bool DeducedTSTContext);
12579
12580 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12581 SourceLocation KeywordLoc,
12582 NestedNameSpecifierLoc QualifierLoc,
12583 const IdentifierInfo &II, SourceLocation IILoc,
12584 bool DeducedTSTContext = true);
12585
12586 /// Rebuilds a type within the context of the current instantiation.
12587 ///
12588 /// The type \p T is part of the type of an out-of-line member definition of
12589 /// a class template (or class template partial specialization) that was
12590 /// parsed and constructed before we entered the scope of the class template
12591 /// (or partial specialization thereof). This routine will rebuild that type
12592 /// now that we have entered the declarator's scope, which may produce
12593 /// different canonical types, e.g.,
12594 ///
12595 /// \code
12596 /// template<typename T>
12597 /// struct X {
12598 /// typedef T* pointer;
12599 /// pointer data();
12600 /// };
12601 ///
12602 /// template<typename T>
12603 /// typename X<T>::pointer X<T>::data() { ... }
12604 /// \endcode
12605 ///
12606 /// Here, the type "typename X<T>::pointer" will be created as a
12607 /// DependentNameType, since we do not know that we can look into X<T> when we
12608 /// parsed the type. This function will rebuild the type, performing the
12609 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12610 /// canonical type is the same as the canonical type of T*, allowing the
12611 /// return types of the out-of-line definition and the declaration to match.
12612 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12613 SourceLocation Loc,
12614 DeclarationName Name);
12615 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12616
12617 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12618
12619 /// Rebuild the template parameters now that we know we're in a current
12620 /// instantiation.
12621 bool
12622 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12623
12624 /// Produces a formatted string that describes the binding of
12625 /// template parameters to template arguments.
12626 std::string
12627 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12628 const TemplateArgumentList &Args);
12629
12630 std::string
12631 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12632 const TemplateArgument *Args,
12633 unsigned NumArgs);
12634
12635 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12636 SourceLocation Less,
12637 SourceLocation Greater);
12638
12639 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12640 /// was just parsed. This is only possible with an explicit scope
12641 /// specifier naming a dependent type.
12642 ExprResult ActOnDependentIdExpression(
12643 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12644 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12645 const TemplateArgumentListInfo *TemplateArgs);
12646
12647 ExprResult
12648 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12649 SourceLocation TemplateKWLoc,
12650 const DeclarationNameInfo &NameInfo,
12651 const TemplateArgumentListInfo *TemplateArgs);
12652
12653 // Calculates whether the expression Constraint depends on an enclosing
12654 // template, for the purposes of [temp.friend] p9.
12655 // TemplateDepth is the 'depth' of the friend function, which is used to
12656 // compare whether a declaration reference is referring to a containing
12657 // template, or just the current friend function. A 'lower' TemplateDepth in
12658 // the AST refers to a 'containing' template. As the constraint is
12659 // uninstantiated, this is relative to the 'top' of the TU.
12660 bool
12661 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12662 unsigned TemplateDepth,
12663 const Expr *Constraint);
12664
12665 /// Find the failed Boolean condition within a given Boolean
12666 /// constant expression, and describe it with a string.
12667 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12668
12669 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12670
12671 ConceptDecl *ActOnStartConceptDefinition(
12672 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12673 const IdentifierInfo *Name, SourceLocation NameLoc);
12674
12675 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12676 Expr *ConstraintExpr,
12677 const ParsedAttributesView &Attrs);
12678
12679 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12680 bool &AddToScope);
12681 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12682
12683 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12684 const CXXScopeSpec &SS,
12685 const IdentifierInfo *Name,
12686 SourceLocation TagLoc, SourceLocation NameLoc);
12687
12688 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12689 CachedTokens &Toks);
12690 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12691 bool IsInsideALocalClassWithinATemplateFunction();
12692
12693 /// We've found a use of a templated declaration that would trigger an
12694 /// implicit instantiation. Check that any relevant explicit specializations
12695 /// and partial specializations are visible/reachable, and diagnose if not.
12696 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12697 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12698
12699 ///@}
12700
12701 //
12702 //
12703 // -------------------------------------------------------------------------
12704 //
12705 //
12706
12707 /// \name C++ Template Argument Deduction
12708 /// Implementations are in SemaTemplateDeduction.cpp
12709 ///@{
12710
12711public:
12712 class SFINAETrap;
12713
12714 struct SFINAEContextBase {
12715 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12716 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12717
12718 protected:
12719 Sema &S;
12720 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12721 SFINAEContextBase(const SFINAEContextBase &) = delete;
12722 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12723
12724 private:
12725 SFINAETrap *Prev;
12726 };
12727
12728 struct NonSFINAEContext : SFINAEContextBase {
12729 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12730 };
12731
12732 /// RAII class used to determine whether SFINAE has
12733 /// trapped any errors that occur during template argument
12734 /// deduction.
12735 class SFINAETrap : SFINAEContextBase {
12736 bool HasErrorOcurred = false;
12737 bool WithAccessChecking = false;
12738 bool PrevLastDiagnosticIgnored =
12739 S.getDiagnostics().isLastDiagnosticIgnored();
12740 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12741
12742 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12743 bool WithAccessChecking)
12744 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12745 DeductionInfo(Info) {}
12746
12747 public:
12748 /// \param WithAccessChecking If true, discard all diagnostics (from the
12749 /// immediate context) instead of adding them to the currently active
12750 /// \ref TemplateDeductionInfo.
12751 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12752 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12753
12754 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12755 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12756
12757 ~SFINAETrap() {
12758 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12759 }
12760
12761 SFINAETrap(const SFINAETrap &) = delete;
12762 SFINAETrap &operator=(const SFINAETrap &) = delete;
12763
12764 sema::TemplateDeductionInfo *getDeductionInfo() const {
12765 return DeductionInfo;
12766 }
12767
12768 /// Determine whether any SFINAE errors have been trapped.
12769 bool hasErrorOccurred() const { return HasErrorOcurred; }
12770 void setErrorOccurred() { HasErrorOcurred = true; }
12771
12772 bool withAccessChecking() const { return WithAccessChecking; }
12773 };
12774
12775 /// RAII class used to indicate that we are performing provisional
12776 /// semantic analysis to determine the validity of a construct, so
12777 /// typo-correction and diagnostics in the immediate context (not within
12778 /// implicitly-instantiated templates) should be suppressed.
12779 class TentativeAnalysisScope {
12780 Sema &SemaRef;
12781 // FIXME: Using a SFINAETrap for this is a hack.
12782 SFINAETrap Trap;
12783 bool PrevDisableTypoCorrection;
12784
12785 public:
12786 explicit TentativeAnalysisScope(Sema &SemaRef)
12787 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12788 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12789 SemaRef.DisableTypoCorrection = true;
12790 }
12791 ~TentativeAnalysisScope() {
12792 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12793 }
12794
12795 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12796 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12797 };
12798
12799 /// For each declaration that involved template argument deduction, the
12800 /// set of diagnostics that were suppressed during that template argument
12801 /// deduction.
12802 ///
12803 /// FIXME: Serialize this structure to the AST file.
12804 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12805 SuppressedDiagnosticsMap;
12806 SuppressedDiagnosticsMap SuppressedDiagnostics;
12807
12808 /// Compare types for equality with respect to possibly compatible
12809 /// function types (noreturn adjustment, implicit calling conventions). If any
12810 /// of parameter and argument is not a function, just perform type comparison.
12811 ///
12812 /// \param P the template parameter type.
12813 ///
12814 /// \param A the argument type.
12815 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12816
12817 /// Allocate a TemplateArgumentLoc where all locations have
12818 /// been initialized to the given location.
12819 ///
12820 /// \param Arg The template argument we are producing template argument
12821 /// location information for.
12822 ///
12823 /// \param NTTPType For a declaration template argument, the type of
12824 /// the non-type template parameter that corresponds to this template
12825 /// argument. Can be null if no type sugar is available to add to the
12826 /// type from the template argument.
12827 ///
12828 /// \param Loc The source location to use for the resulting template
12829 /// argument.
12830 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
12831 QualType NTTPType,
12832 SourceLocation Loc);
12833
12834 /// Get a template argument mapping the given template parameter to itself,
12835 /// e.g. for X in \c template<int X>, this would return an expression template
12836 /// argument referencing X.
12837 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12838 SourceLocation Location);
12839
12840 /// Adjust the type \p ArgFunctionType to match the calling convention,
12841 /// noreturn, and optionally the exception specification of \p FunctionType.
12842 /// Deduction often wants to ignore these properties when matching function
12843 /// types.
12844 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12845 bool AdjustExceptionSpec = false);
12846
12847 TemplateDeductionResult
12848 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12849 ArrayRef<TemplateArgument> TemplateArgs,
12850 sema::TemplateDeductionInfo &Info);
12851
12852 TemplateDeductionResult
12853 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12854 ArrayRef<TemplateArgument> TemplateArgs,
12855 sema::TemplateDeductionInfo &Info);
12856
12857 /// Deduce the template arguments of the given template from \p FromType.
12858 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12859 /// [over.match.class.deduct]p4.
12860 ///
12861 /// It only supports class or type alias templates.
12862 TemplateDeductionResult
12863 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12864 sema::TemplateDeductionInfo &Info);
12865
12866 TemplateDeductionResult DeduceTemplateArguments(
12867 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12868 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12869 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12870 bool NumberOfArgumentsMustMatch);
12871
12872 /// Substitute the explicitly-provided template arguments into the
12873 /// given function template according to C++ [temp.arg.explicit].
12874 ///
12875 /// \param FunctionTemplate the function template into which the explicit
12876 /// template arguments will be substituted.
12877 ///
12878 /// \param ExplicitTemplateArgs the explicitly-specified template
12879 /// arguments.
12880 ///
12881 /// \param Deduced the deduced template arguments, which will be populated
12882 /// with the converted and checked explicit template arguments.
12883 ///
12884 /// \param ParamTypes will be populated with the instantiated function
12885 /// parameters.
12886 ///
12887 /// \param FunctionType if non-NULL, the result type of the function template
12888 /// will also be instantiated and the pointed-to value will be updated with
12889 /// the instantiated function type.
12890 ///
12891 /// \param Info if substitution fails for any reason, this object will be
12892 /// populated with more information about the failure.
12893 ///
12894 /// \returns TemplateDeductionResult::Success if substitution was successful,
12895 /// or some failure condition.
12896 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12897 FunctionTemplateDecl *FunctionTemplate,
12898 TemplateArgumentListInfo &ExplicitTemplateArgs,
12899 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12900 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12901 sema::TemplateDeductionInfo &Info);
12902
12903 /// brief A function argument from which we performed template argument
12904 // deduction for a call.
12905 struct OriginalCallArg {
12906 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12907 unsigned ArgIdx, QualType OriginalArgType)
12908 : OriginalParamType(OriginalParamType),
12909 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12910 OriginalArgType(OriginalArgType) {}
12911
12912 QualType OriginalParamType;
12913 bool DecomposedParam;
12914 unsigned ArgIdx;
12915 QualType OriginalArgType;
12916 };
12917
12918 /// Finish template argument deduction for a function template,
12919 /// checking the deduced template arguments for completeness and forming
12920 /// the function template specialization.
12921 ///
12922 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12923 /// which the deduced argument types should be compared.
12924 /// \param CheckNonDependent Callback before substituting into the declaration
12925 /// with the deduced template arguments.
12926 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12927 /// some breakages introduced by CWG2369, where non-user-defined conversions
12928 /// are checked first before the constraints.
12929 TemplateDeductionResult FinishTemplateArgumentDeduction(
12930 FunctionTemplateDecl *FunctionTemplate,
12931 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12932 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12933 sema::TemplateDeductionInfo &Info,
12934 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12935 bool PartialOverloading, bool PartialOrdering,
12936 bool ForOverloadSetAddressResolution,
12937 llvm::function_ref<bool(bool)> CheckNonDependent =
12938 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12939 return false;
12940 });
12941
12942 /// Perform [temp.friend] p5 template argument deduction for a dependent
12943 /// friend declaration and a candidate class template specialization.
12944 bool DeduceTemplateArguments(FriendTemplateDecl *FTD,
12945 ClassTemplateDecl *PatternCTD,
12946 ClassTemplateDecl *CandidateCTD,
12947 ArrayRef<TemplateParameterList *> TPLs,
12948 ArrayRef<TemplateArgument> PatternArgs,
12949 ArrayRef<TemplateArgument> CandidateArgs,
12950 SourceLocation Loc,
12951 TemplateSpecCandidateSet *FailedTSC,
12952 MultiLevelTemplateArgumentList &DeducedArgs);
12953
12954 /// Perform template argument deduction from a function call
12955 /// (C++ [temp.deduct.call]).
12956 ///
12957 /// \param FunctionTemplate the function template for which we are performing
12958 /// template argument deduction.
12959 ///
12960 /// \param ExplicitTemplateArgs the explicit template arguments provided
12961 /// for this call.
12962 ///
12963 /// \param Args the function call arguments
12964 ///
12965 /// \param Specialization if template argument deduction was successful,
12966 /// this will be set to the function template specialization produced by
12967 /// template argument deduction.
12968 ///
12969 /// \param Info the argument will be updated to provide additional information
12970 /// about template argument deduction.
12971 ///
12972 /// \param CheckNonDependent A callback to invoke to check conversions for
12973 /// non-dependent parameters, between deduction and substitution, per DR1391.
12974 /// If this returns true, substitution will be skipped and we return
12975 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12976 /// passed the parameter types (after substituting explicit template
12977 /// arguments).
12978 ///
12979 /// \returns the result of template argument deduction.
12980 TemplateDeductionResult DeduceTemplateArguments(
12981 FunctionTemplateDecl *FunctionTemplate,
12982 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12983 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12984 bool PartialOverloading, bool AggregateDeductionCandidate,
12985 bool PartialOrdering, QualType ObjectType,
12986 Expr::Classification ObjectClassification,
12987 bool ForOverloadSetAddressResolution,
12988 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12989
12990 /// Deduce template arguments when taking the address of a function
12991 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12992 /// a template.
12993 ///
12994 /// \param FunctionTemplate the function template for which we are performing
12995 /// template argument deduction.
12996 ///
12997 /// \param ExplicitTemplateArgs the explicitly-specified template
12998 /// arguments.
12999 ///
13000 /// \param ArgFunctionType the function type that will be used as the
13001 /// "argument" type (A) when performing template argument deduction from the
13002 /// function template's function type. This type may be NULL, if there is no
13003 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
13004 ///
13005 /// \param Specialization if template argument deduction was successful,
13006 /// this will be set to the function template specialization produced by
13007 /// template argument deduction.
13008 ///
13009 /// \param Info the argument will be updated to provide additional information
13010 /// about template argument deduction.
13011 ///
13012 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
13013 /// the address of a function template per [temp.deduct.funcaddr] and
13014 /// [over.over]. If \c false, we are looking up a function template
13015 /// specialization based on its signature, per [temp.deduct.decl].
13016 ///
13017 /// \returns the result of template argument deduction.
13018 TemplateDeductionResult DeduceTemplateArguments(
13019 FunctionTemplateDecl *FunctionTemplate,
13020 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
13021 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
13022 bool IsAddressOfFunction = false);
13023
13024 /// Deduce template arguments for a templated conversion
13025 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
13026 /// conversion function template specialization.
13027 TemplateDeductionResult DeduceTemplateArguments(
13028 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
13029 Expr::Classification ObjectClassification, QualType ToType,
13030 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
13031
13032 /// Deduce template arguments for a function template when there is
13033 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
13034 ///
13035 /// \param FunctionTemplate the function template for which we are performing
13036 /// template argument deduction.
13037 ///
13038 /// \param ExplicitTemplateArgs the explicitly-specified template
13039 /// arguments.
13040 ///
13041 /// \param Specialization if template argument deduction was successful,
13042 /// this will be set to the function template specialization produced by
13043 /// template argument deduction.
13044 ///
13045 /// \param Info the argument will be updated to provide additional information
13046 /// about template argument deduction.
13047 ///
13048 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
13049 /// the address of a function template in a context where we do not have a
13050 /// target type, per [over.over]. If \c false, we are looking up a function
13051 /// template specialization based on its signature, which only happens when
13052 /// deducing a function parameter type from an argument that is a template-id
13053 /// naming a function template specialization.
13054 ///
13055 /// \returns the result of template argument deduction.
13056 TemplateDeductionResult
13057 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
13058 TemplateArgumentListInfo *ExplicitTemplateArgs,
13059 FunctionDecl *&Specialization,
13060 sema::TemplateDeductionInfo &Info,
13061 bool IsAddressOfFunction = false);
13062
13063 /// Substitute Replacement for \p auto in \p TypeWithAuto
13064 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
13065 /// Substitute Replacement for auto in TypeWithAuto
13066 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
13067 QualType Replacement);
13068
13069 // Substitute auto in TypeWithAuto for a Dependent auto type
13070 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
13071
13072 // Substitute auto in TypeWithAuto for a Dependent auto type
13073 TypeSourceInfo *
13074 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
13075
13076 /// Completely replace the \c auto in \p TypeWithAuto by
13077 /// \p Replacement. This does not retain any \c auto type sugar.
13078 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
13079 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
13080 QualType Replacement);
13081
13082 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
13083 ///
13084 /// Note that this is done even if the initializer is dependent. (This is
13085 /// necessary to support partial ordering of templates using 'auto'.)
13086 /// A dependent type will be produced when deducing from a dependent type.
13087 ///
13088 /// \param Type the type pattern using the auto type-specifier.
13089 /// \param Init the initializer for the variable whose type is to be deduced.
13090 /// \param Result if type deduction was successful, this will be set to the
13091 /// deduced type.
13092 /// \param Info the argument will be updated to provide additional information
13093 /// about template argument deduction.
13094 /// \param DependentDeduction Set if we should permit deduction in
13095 /// dependent cases. This is necessary for template partial ordering
13096 /// with 'auto' template parameters. The template parameter depth to be
13097 /// used should be specified in the 'Info' parameter.
13098 /// \param IgnoreConstraints Set if we should not fail if the deduced type
13099 /// does not satisfy the type-constraint in the auto
13100 /// type.
13101 TemplateDeductionResult
13102 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
13103 sema::TemplateDeductionInfo &Info,
13104 bool DependentDeduction = false,
13105 bool IgnoreConstraints = false,
13106 TemplateSpecCandidateSet *FailedTSC = nullptr);
13107 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
13108 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
13109 bool Diagnose = true);
13110
13111 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
13112 SourceLocation Loc);
13113
13114 /// Returns the more specialized class template partial specialization
13115 /// according to the rules of partial ordering of class template partial
13116 /// specializations (C++ [temp.class.order]).
13117 ///
13118 /// \param PS1 the first class template partial specialization
13119 ///
13120 /// \param PS2 the second class template partial specialization
13121 ///
13122 /// \returns the more specialized class template partial specialization. If
13123 /// neither partial specialization is more specialized, returns NULL.
13124 ClassTemplatePartialSpecializationDecl *
13125 getMoreSpecializedPartialSpecialization(
13126 ClassTemplatePartialSpecializationDecl *PS1,
13127 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
13128
13129 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
13130 sema::TemplateDeductionInfo &Info);
13131
13132 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
13133 VarTemplatePartialSpecializationDecl *PS1,
13134 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
13135
13136 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
13137 sema::TemplateDeductionInfo &Info);
13138
13139 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
13140 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
13141 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
13142 bool PartialOrdering, bool *StrictPackMatch);
13143
13144 /// Determine the declared type of the constant template parameter that \p Arg
13145 /// names, if any.
13146 static QualType
13147 getTypeOfConstantTemplateParameter(const TemplateArgument &Arg);
13148
13149 /// Mark which template parameters are used in a given expression.
13150 ///
13151 /// \param E the expression from which template parameters will be deduced.
13152 ///
13153 /// \param Used a bit vector whose elements will be set to \c true
13154 /// to indicate when the corresponding template parameter will be
13155 /// deduced.
13156 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
13157 unsigned Depth, llvm::SmallBitVector &Used);
13158
13159 /// Mark which template parameters are named in a given expression.
13160 ///
13161 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
13162 /// are used but not directly named by an expression - i.e. it excludes
13163 /// any template parameter that denotes the type of a referenced NTTP.
13164 ///
13165 /// \param Used a bit vector whose elements will be set to \c true
13166 /// to indicate when the corresponding template parameter will be
13167 /// deduced.
13168 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
13169 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
13170
13171 /// Mark which template parameters can be deduced from a given
13172 /// template argument list.
13173 ///
13174 /// \param TemplateArgs the template argument list from which template
13175 /// parameters will be deduced.
13176 ///
13177 /// \param Used a bit vector whose elements will be set to \c true
13178 /// to indicate when the corresponding template parameter will be
13179 /// deduced.
13180 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
13181 bool OnlyDeduced, unsigned Depth,
13182 llvm::SmallBitVector &Used);
13183
13184 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
13185 bool OnlyDeduced, unsigned Depth,
13186 llvm::SmallBitVector &Used);
13187
13188 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
13189 unsigned Depth, llvm::SmallBitVector &Used);
13190
13191 void
13192 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
13193 llvm::SmallBitVector &Deduced) {
13194 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
13195 }
13196
13197 /// Marks all of the template parameters that will be deduced by a
13198 /// call to the given function template.
13199 static void
13200 MarkDeducedTemplateParameters(ASTContext &Ctx,
13201 const FunctionTemplateDecl *FunctionTemplate,
13202 llvm::SmallBitVector &Deduced);
13203
13204 /// Returns the more specialized function template according
13205 /// to the rules of function template partial ordering (C++
13206 /// [temp.func.order]).
13207 ///
13208 /// \param FT1 the first function template
13209 ///
13210 /// \param FT2 the second function template
13211 ///
13212 /// \param TPOC the context in which we are performing partial ordering of
13213 /// function templates.
13214 ///
13215 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13216 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13217 /// when calling a member function.
13218 ///
13219 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13220 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13221 /// template from a member function
13222 ///
13223 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13224 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13225 /// template from a member function
13226 ///
13227 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13228 /// candidate with a reversed parameter order. In this case, the corresponding
13229 /// P/A pairs between FT1 and FT2 are reversed.
13230 ///
13231 /// \returns the more specialized function template. If neither
13232 /// template is more specialized, returns NULL.
13233 FunctionTemplateDecl *getMoreSpecializedTemplate(
13234 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13235 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13236 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13237 bool PartialOverloading = false);
13238
13239 /// Retrieve the most specialized of the given function template
13240 /// specializations.
13241 ///
13242 /// \param SpecBegin the start iterator of the function template
13243 /// specializations that we will be comparing.
13244 ///
13245 /// \param SpecEnd the end iterator of the function template
13246 /// specializations, paired with \p SpecBegin.
13247 ///
13248 /// \param Loc the location where the ambiguity or no-specializations
13249 /// diagnostic should occur.
13250 ///
13251 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13252 /// no matching candidates.
13253 ///
13254 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13255 /// occurs.
13256 ///
13257 /// \param CandidateDiag partial diagnostic used for each function template
13258 /// specialization that is a candidate in the ambiguous ordering. One
13259 /// parameter in this diagnostic should be unbound, which will correspond to
13260 /// the string describing the template arguments for the function template
13261 /// specialization.
13262 ///
13263 /// \returns the most specialized function template specialization, if
13264 /// found. Otherwise, returns SpecEnd.
13265 UnresolvedSetIterator
13266 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13267 TemplateSpecCandidateSet &FailedCandidates,
13268 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13269 const PartialDiagnostic &AmbigDiag,
13270 const PartialDiagnostic &CandidateDiag,
13271 bool Complain = true, QualType TargetType = QualType());
13272
13273 /// Returns the more constrained function according to the rules of
13274 /// partial ordering by constraints (C++ [temp.constr.order]).
13275 ///
13276 /// \param FD1 the first function
13277 ///
13278 /// \param FD2 the second function
13279 ///
13280 /// \returns the more constrained function. If neither function is
13281 /// more constrained, returns NULL.
13282 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13283 FunctionDecl *FD2);
13284
13285 ///@}
13286
13287 //
13288 //
13289 // -------------------------------------------------------------------------
13290 //
13291 //
13292
13293 /// \name C++ Template Deduction Guide
13294 /// Implementations are in SemaTemplateDeductionGuide.cpp
13295 ///@{
13296
13297 /// Declare implicit deduction guides for a class template if we've
13298 /// not already done so.
13299 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13300 SourceLocation Loc);
13301
13302 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13303 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13304 SourceLocation Loc);
13305
13306 ///@}
13307
13308 //
13309 //
13310 // -------------------------------------------------------------------------
13311 //
13312 //
13313
13314 /// \name C++ Template Instantiation
13315 /// Implementations are in SemaTemplateInstantiate.cpp
13316 ///@{
13317
13318public:
13319 /// A helper class for building up ExtParameterInfos.
13320 class ExtParameterInfoBuilder {
13321 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13322 bool HasInteresting = false;
13323
13324 public:
13325 /// Set the ExtParameterInfo for the parameter at the given index,
13326 ///
13327 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13328 assert(Infos.size() <= index);
13329 Infos.resize(N: index);
13330 Infos.push_back(Elt: info);
13331
13332 if (!HasInteresting)
13333 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13334 }
13335
13336 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13337 /// ExtParameterInfo array we've built up.
13338 const FunctionProtoType::ExtParameterInfo *
13339 getPointerOrNull(unsigned numParams) {
13340 if (!HasInteresting)
13341 return nullptr;
13342 Infos.resize(N: numParams);
13343 return Infos.data();
13344 }
13345 };
13346
13347 /// The current instantiation scope used to store local
13348 /// variables.
13349 LocalInstantiationScope *CurrentInstantiationScope;
13350
13351 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13352 UnparsedDefaultArgInstantiationsMap;
13353
13354 /// A mapping from parameters with unparsed default arguments to the
13355 /// set of instantiations of each parameter.
13356 ///
13357 /// This mapping is a temporary data structure used when parsing
13358 /// nested class templates or nested classes of class templates,
13359 /// where we might end up instantiating an inner class before the
13360 /// default arguments of its methods have been parsed.
13361 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13362
13363 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13364
13365 struct RecursiveInstGuard {
13366 enum class Kind {
13367 Template,
13368 DefaultArgument,
13369 ExceptionSpec,
13370 };
13371
13372 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13373 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13374 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13375 if (!Created)
13376 Key = {};
13377 }
13378
13379 ~RecursiveInstGuard() {
13380 if (Key.getOpaqueValue()) {
13381 [[maybe_unused]] bool Erased =
13382 S.InstantiatingSpecializations.erase(V: Key);
13383 assert(Erased);
13384 }
13385 }
13386
13387 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13388 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13389
13390 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13391
13392 private:
13393 Sema &S;
13394 Sema::InstantiatingSpecializationsKey Key;
13395 };
13396
13397 /// A context in which code is being synthesized (where a source location
13398 /// alone is not sufficient to identify the context). This covers template
13399 /// instantiation and various forms of implicitly-generated functions.
13400 struct CodeSynthesisContext {
13401 /// The kind of template instantiation we are performing
13402 enum SynthesisKind {
13403 /// We are instantiating a template declaration. The entity is
13404 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13405 TemplateInstantiation,
13406
13407 /// We are instantiating a default argument for a template
13408 /// parameter. The Entity is the template parameter whose argument is
13409 /// being instantiated, the Template is the template, and the
13410 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13411 /// specified.
13412 DefaultTemplateArgumentInstantiation,
13413
13414 /// We are instantiating a default argument for a function.
13415 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13416 /// provides the template arguments as specified.
13417 DefaultFunctionArgumentInstantiation,
13418
13419 /// We are substituting explicit template arguments provided for
13420 /// a function template. The entity is a FunctionTemplateDecl.
13421 ExplicitTemplateArgumentSubstitution,
13422
13423 /// We are substituting template argument determined as part of
13424 /// template argument deduction for either a class template
13425 /// partial specialization or a function template. The
13426 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13427 /// a TemplateDecl.
13428 DeducedTemplateArgumentSubstitution,
13429
13430 /// We are substituting into a lambda expression.
13431 LambdaExpressionSubstitution,
13432
13433 /// We are substituting prior template arguments into a new
13434 /// template parameter. The template parameter itself is either a
13435 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13436 PriorTemplateArgumentSubstitution,
13437
13438 /// We are checking the validity of a default template argument that
13439 /// has been used when naming a template-id.
13440 DefaultTemplateArgumentChecking,
13441
13442 /// We are computing the exception specification for a defaulted special
13443 /// member function.
13444 ExceptionSpecEvaluation,
13445
13446 /// We are instantiating the exception specification for a function
13447 /// template which was deferred until it was needed.
13448 ExceptionSpecInstantiation,
13449
13450 /// We are instantiating a requirement of a requires expression.
13451 RequirementInstantiation,
13452
13453 /// We are checking the satisfaction of a nested requirement of a requires
13454 /// expression.
13455 NestedRequirementConstraintsCheck,
13456
13457 /// We are declaring an implicit special member function.
13458 DeclaringSpecialMember,
13459
13460 /// We are declaring an implicit 'operator==' for a defaulted
13461 /// 'operator<=>'.
13462 DeclaringImplicitEqualityComparison,
13463
13464 /// We are defining a synthesized function (such as a defaulted special
13465 /// member).
13466 DefiningSynthesizedFunction,
13467
13468 // We are checking the constraints associated with a constrained entity or
13469 // the constraint expression of a concept. This includes the checks that
13470 // atomic constraints have the type 'bool' and that they can be constant
13471 // evaluated.
13472 ConstraintsCheck,
13473
13474 // We are substituting template arguments into a constraint expression.
13475 ConstraintSubstitution,
13476
13477 // Instantiating a Requires Expression parameter clause.
13478 RequirementParameterInstantiation,
13479
13480 // We are substituting into the parameter mapping of an atomic constraint
13481 // during normalization.
13482 ParameterMappingSubstitution,
13483
13484 /// We are rewriting a comparison operator in terms of an operator<=>.
13485 RewritingOperatorAsSpaceship,
13486
13487 /// We are initializing a structured binding.
13488 InitializingStructuredBinding,
13489
13490 /// We are marking a class as __dllexport.
13491 MarkingClassDllexported,
13492
13493 /// We are building an implied call from __builtin_dump_struct. The
13494 /// arguments are in CallArgs.
13495 BuildingBuiltinDumpStructCall,
13496
13497 /// Added for Template instantiation observation.
13498 /// Memoization means we are _not_ instantiating a template because
13499 /// it is already instantiated (but we entered a context where we
13500 /// would have had to if it was not already instantiated).
13501 Memoization,
13502
13503 /// We are building deduction guides for a class.
13504 BuildingDeductionGuides,
13505
13506 /// We are instantiating a type alias template declaration.
13507 TypeAliasTemplateInstantiation,
13508
13509 /// We are performing partial ordering for template template parameters.
13510 PartialOrderingTTP,
13511
13512 /// We are performing name lookup for a function template or variable
13513 /// template named 'sycl_kernel_launch'.
13514 SYCLKernelLaunchLookup,
13515
13516 /// We are performing overload resolution for a call to a function
13517 /// template or variable template named 'sycl_kernel_launch'.
13518 SYCLKernelLaunchOverloadResolution,
13519
13520 /// We are instantiating an expansion statement.
13521 ExpansionStmtInstantiation,
13522 } Kind;
13523
13524 /// Whether we're substituting into constraints.
13525 bool InConstraintSubstitution;
13526
13527 /// Whether we're substituting into the parameter mapping of a constraint.
13528 bool InParameterMappingSubstitution;
13529
13530 /// The point of instantiation or synthesis within the source code.
13531 SourceLocation PointOfInstantiation;
13532
13533 /// The entity that is being synthesized.
13534 Decl *Entity;
13535
13536 /// The template (or partial specialization) in which we are
13537 /// performing the instantiation, for substitutions of prior template
13538 /// arguments.
13539 NamedDecl *Template;
13540
13541 union {
13542 /// The list of template arguments we are substituting, if they
13543 /// are not part of the entity.
13544 const TemplateArgument *TemplateArgs;
13545
13546 /// The list of argument expressions in a synthesized call.
13547 const Expr *const *CallArgs;
13548 };
13549
13550 // FIXME: Wrap this union around more members, or perhaps store the
13551 // kind-specific members in the RAII object owning the context.
13552 union {
13553 /// The number of template arguments in TemplateArgs.
13554 unsigned NumTemplateArgs;
13555
13556 /// The number of expressions in CallArgs.
13557 unsigned NumCallArgs;
13558
13559 /// The special member being declared or defined.
13560 CXXSpecialMemberKind SpecialMember;
13561 };
13562
13563 ArrayRef<TemplateArgument> template_arguments() const {
13564 assert(Kind != DeclaringSpecialMember);
13565 return {TemplateArgs, NumTemplateArgs};
13566 }
13567
13568 /// The source range that covers the construct that cause
13569 /// the instantiation, e.g., the template-id that causes a class
13570 /// template instantiation.
13571 SourceRange InstantiationRange;
13572
13573 CodeSynthesisContext()
13574 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13575 InParameterMappingSubstitution(false), Entity(nullptr),
13576 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13577
13578 /// Determines whether this template is an actual instantiation
13579 /// that should be counted toward the maximum instantiation depth.
13580 bool isInstantiationRecord() const;
13581 };
13582
13583 /// A stack object to be created when performing template
13584 /// instantiation.
13585 ///
13586 /// Construction of an object of type \c InstantiatingTemplate
13587 /// pushes the current instantiation onto the stack of active
13588 /// instantiations. If the size of this stack exceeds the maximum
13589 /// number of recursive template instantiations, construction
13590 /// produces an error and evaluates true.
13591 ///
13592 /// Destruction of this object will pop the named instantiation off
13593 /// the stack.
13594 struct InstantiatingTemplate {
13595 /// Note that we are instantiating a class template,
13596 /// function template, variable template, alias template,
13597 /// or a member thereof.
13598 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13599 Decl *Entity,
13600 SourceRange InstantiationRange = SourceRange());
13601
13602 struct ExceptionSpecification {};
13603 /// Note that we are instantiating an exception specification
13604 /// of a function template.
13605 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13606 FunctionDecl *Entity, ExceptionSpecification,
13607 SourceRange InstantiationRange = SourceRange());
13608
13609 /// Note that we are instantiating a type alias template declaration.
13610 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13611 TypeAliasTemplateDecl *Entity,
13612 ArrayRef<TemplateArgument> TemplateArgs,
13613 SourceRange InstantiationRange = SourceRange());
13614
13615 /// Note that we are instantiating a default argument in a
13616 /// template-id.
13617 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13618 TemplateParameter Param, TemplateDecl *Template,
13619 ArrayRef<TemplateArgument> TemplateArgs,
13620 SourceRange InstantiationRange = SourceRange());
13621
13622 /// Note that we are substituting either explicitly-specified or
13623 /// deduced template arguments during function template argument deduction.
13624 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13625 FunctionTemplateDecl *FunctionTemplate,
13626 ArrayRef<TemplateArgument> TemplateArgs,
13627 CodeSynthesisContext::SynthesisKind Kind,
13628 SourceRange InstantiationRange = SourceRange());
13629
13630 /// Note that we are instantiating as part of template
13631 /// argument deduction for a class template declaration.
13632 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13633 TemplateDecl *Template,
13634 ArrayRef<TemplateArgument> TemplateArgs,
13635 SourceRange InstantiationRange = SourceRange());
13636
13637 /// Note that we are instantiating as part of template
13638 /// argument deduction for a class template partial
13639 /// specialization.
13640 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13641 ClassTemplatePartialSpecializationDecl *PartialSpec,
13642 ArrayRef<TemplateArgument> TemplateArgs,
13643 SourceRange InstantiationRange = SourceRange());
13644
13645 /// Note that we are instantiating as part of template
13646 /// argument deduction for a variable template partial
13647 /// specialization.
13648 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13649 VarTemplatePartialSpecializationDecl *PartialSpec,
13650 ArrayRef<TemplateArgument> TemplateArgs,
13651 SourceRange InstantiationRange = SourceRange());
13652
13653 /// Note that we are instantiating a default argument for a function
13654 /// parameter.
13655 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13656 ParmVarDecl *Param,
13657 ArrayRef<TemplateArgument> TemplateArgs,
13658 SourceRange InstantiationRange = SourceRange());
13659
13660 /// Note that we are substituting prior template arguments into a
13661 /// non-type parameter.
13662 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13663 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13664 ArrayRef<TemplateArgument> TemplateArgs,
13665 SourceRange InstantiationRange);
13666
13667 /// Note that we are substituting prior template arguments into a
13668 /// template template parameter.
13669 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13670 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13671 ArrayRef<TemplateArgument> TemplateArgs,
13672 SourceRange InstantiationRange);
13673
13674 /// Note that we are checking the default template argument
13675 /// against the template parameter for a given template-id.
13676 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13677 TemplateDecl *Template, NamedDecl *Param,
13678 ArrayRef<TemplateArgument> TemplateArgs,
13679 SourceRange InstantiationRange);
13680
13681 struct ConstraintsCheck {};
13682 /// \brief Note that we are checking the constraints associated with some
13683 /// constrained entity (a concept declaration or a template with associated
13684 /// constraints).
13685 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13686 ConstraintsCheck, NamedDecl *Template,
13687 ArrayRef<TemplateArgument> TemplateArgs,
13688 SourceRange InstantiationRange);
13689
13690 struct ConstraintSubstitution {};
13691 /// \brief Note that we are checking a constraint expression associated
13692 /// with a template declaration or as part of the satisfaction check of a
13693 /// concept.
13694 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13695 ConstraintSubstitution, NamedDecl *Template,
13696 SourceRange InstantiationRange);
13697
13698 struct ParameterMappingSubstitution {};
13699 /// \brief Note that we are subtituting into the parameter mapping of an
13700 /// atomic constraint during constraint normalization.
13701 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13702 ParameterMappingSubstitution, NamedDecl *Template,
13703 SourceRange InstantiationRange);
13704
13705 /// \brief Note that we are substituting template arguments into a part of
13706 /// a requirement of a requires expression.
13707 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13708 concepts::Requirement *Req,
13709 SourceRange InstantiationRange = SourceRange());
13710
13711 /// \brief Note that we are substituting the body of an expansion statement.
13712 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13713 CXXExpansionStmtPattern *ExpansionStmt,
13714 ArrayRef<TemplateArgument> TArgs,
13715 SourceRange InstantiationRange);
13716
13717 /// \brief Note that we are checking the satisfaction of the constraint
13718 /// expression inside of a nested requirement.
13719 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13720 concepts::NestedRequirement *Req, ConstraintsCheck,
13721 SourceRange InstantiationRange = SourceRange());
13722
13723 /// \brief Note that we are checking a requires clause.
13724 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13725 const RequiresExpr *E,
13726 SourceRange InstantiationRange);
13727
13728 struct BuildingDeductionGuidesTag {};
13729 /// \brief Note that we are building deduction guides.
13730 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13731 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13732 SourceRange InstantiationRange = SourceRange());
13733
13734 struct PartialOrderingTTP {};
13735 /// \brief Note that we are partial ordering template template parameters.
13736 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13737 PartialOrderingTTP, TemplateDecl *PArg,
13738 SourceRange InstantiationRange = SourceRange());
13739
13740 /// Note that we have finished instantiating this template.
13741 void Clear();
13742
13743 ~InstantiatingTemplate() { Clear(); }
13744
13745 /// Determines whether we have exceeded the maximum
13746 /// recursive template instantiations.
13747 bool isInvalid() const { return Invalid; }
13748
13749 private:
13750 Sema &SemaRef;
13751 bool Invalid;
13752
13753 InstantiatingTemplate(Sema &SemaRef,
13754 CodeSynthesisContext::SynthesisKind Kind,
13755 SourceLocation PointOfInstantiation,
13756 SourceRange InstantiationRange, Decl *Entity,
13757 NamedDecl *Template = nullptr,
13758 ArrayRef<TemplateArgument> TemplateArgs = {});
13759
13760 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13761
13762 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13763 };
13764
13765 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13766 const MultiLevelTemplateArgumentList &TemplateArgs,
13767 TemplateArgumentLoc &Output,
13768 SourceLocation Loc = {},
13769 const DeclarationName &Entity = {});
13770 bool
13771 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13772 const MultiLevelTemplateArgumentList &TemplateArgs,
13773 TemplateArgumentListInfo &Outputs);
13774
13775 /// Substitute concept template arguments in the constraint expression
13776 /// of a concept-id. This is used to implement [temp.constr.normal].
13777 ExprResult
13778 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13779 const Expr *ConstraintExpr,
13780 const MultiLevelTemplateArgumentList &MLTAL);
13781
13782 bool SubstTemplateArgumentsInParameterMapping(
13783 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13784 const MultiLevelTemplateArgumentList &TemplateArgs,
13785 TemplateArgumentListInfo &Out);
13786
13787 /// Retrieve the template argument list(s) that should be used to
13788 /// instantiate the definition of the given declaration.
13789 ///
13790 /// \param ND the declaration for which we are computing template
13791 /// instantiation arguments.
13792 ///
13793 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13794 /// the decl context where it will be created. In this case, the `Innermost`
13795 /// should likely be provided. If ND is non-null, this is ignored.
13796 ///
13797 /// \param Innermost if non-NULL, specifies a template argument list for the
13798 /// template declaration passed as ND.
13799 ///
13800 /// \param RelativeToPrimary true if we should get the template
13801 /// arguments relative to the primary template, even when we're
13802 /// dealing with a specialization. This is only relevant for function
13803 /// template specializations.
13804 ///
13805 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13806 /// instantiating the definition of the given declaration, \p ND. This is
13807 /// used to determine the proper set of template instantiation arguments for
13808 /// friend function template specializations.
13809 ///
13810 /// \param ForConstraintInstantiation when collecting arguments,
13811 /// ForConstraintInstantiation indicates we should continue looking when
13812 /// encountering a lambda generic call operator, and continue looking for
13813 /// arguments on an enclosing class template.
13814 ///
13815 /// \param SkipForSpecialization when specified, any template specializations
13816 /// in a traversal would be ignored.
13817 ///
13818 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13819 /// when encountering a specialized member function template, rather than
13820 /// returning immediately.
13821 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13822 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13823 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13824 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13825 bool ForConstraintInstantiation = false,
13826 bool SkipForSpecialization = false,
13827 bool ForDefaultArgumentSubstitution = false);
13828
13829 /// RAII object to handle the state changes required to synthesize
13830 /// a function body.
13831 class SynthesizedFunctionScope {
13832 Sema &S;
13833 Sema::ContextRAII SavedContext;
13834 bool PushedCodeSynthesisContext = false;
13835
13836 public:
13837 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13838 : S(S), SavedContext(S, DC) {
13839 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13840 S.PushFunctionScope();
13841 S.PushExpressionEvaluationContextForFunction(
13842 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13843 if (FD)
13844 FD->setWillHaveBody(true);
13845 else
13846 assert(isa<ObjCMethodDecl>(DC));
13847 }
13848
13849 void addContextNote(SourceLocation UseLoc) {
13850 assert(!PushedCodeSynthesisContext);
13851
13852 Sema::CodeSynthesisContext Ctx;
13853 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13854 Ctx.PointOfInstantiation = UseLoc;
13855 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13856 S.pushCodeSynthesisContext(Ctx);
13857
13858 PushedCodeSynthesisContext = true;
13859 }
13860
13861 ~SynthesizedFunctionScope() {
13862 if (PushedCodeSynthesisContext)
13863 S.popCodeSynthesisContext();
13864 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13865 FD->setWillHaveBody(false);
13866 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13867 }
13868 S.PopExpressionEvaluationContext();
13869 S.PopFunctionScopeInfo();
13870 }
13871
13872 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13873 SynthesizedFunctionScope &
13874 operator=(const SynthesizedFunctionScope &) = delete;
13875 };
13876
13877 /// RAII object to ensure that a code synthesis context is popped on scope
13878 /// exit.
13879 class ScopedCodeSynthesisContext {
13880 Sema &S;
13881
13882 public:
13883 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13884 : S(S) {
13885 S.pushCodeSynthesisContext(Ctx);
13886 }
13887
13888 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13889 ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &) = delete;
13890 ScopedCodeSynthesisContext &
13891 operator=(const ScopedCodeSynthesisContext &) = delete;
13892 };
13893
13894 /// List of active code synthesis contexts.
13895 ///
13896 /// This vector is treated as a stack. As synthesis of one entity requires
13897 /// synthesis of another, additional contexts are pushed onto the stack.
13898 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13899
13900 /// Specializations whose definitions are currently being instantiated.
13901 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13902
13903 /// Non-dependent types used in templates that have already been instantiated
13904 /// by some template instantiation.
13905 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13906
13907 /// Extra modules inspected when performing a lookup during a template
13908 /// instantiation. Computed lazily.
13909 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13910
13911 /// Cache of additional modules that should be used for name lookup
13912 /// within the current template instantiation. Computed lazily; use
13913 /// getLookupModules() to get a complete set.
13914 llvm::DenseSet<Module *> LookupModulesCache;
13915
13916 /// Map from the most recent declaration of a namespace to the most
13917 /// recent visible declaration of that namespace.
13918 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13919
13920 SFINAETrap *CurrentSFINAEContext = nullptr;
13921
13922 /// The number of \p CodeSynthesisContexts that are not template
13923 /// instantiations and, therefore, should not be counted as part of the
13924 /// instantiation depth.
13925 ///
13926 /// When the instantiation depth reaches the user-configurable limit
13927 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13928 // FIXME: Should we have a similar limit for other forms of synthesis?
13929 unsigned NonInstantiationEntries;
13930
13931 /// The depth of the context stack at the point when the most recent
13932 /// error or warning was produced.
13933 ///
13934 /// This value is used to suppress printing of redundant context stacks
13935 /// when there are multiple errors or warnings in the same instantiation.
13936 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13937 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13938
13939 /// The current index into pack expansion arguments that will be
13940 /// used for substitution of parameter packs.
13941 ///
13942 /// The pack expansion index will be none to indicate that parameter packs
13943 /// should be instantiated as themselves. Otherwise, the index specifies
13944 /// which argument within the parameter pack will be used for substitution.
13945 UnsignedOrNone ArgPackSubstIndex;
13946
13947 /// RAII object used to change the argument pack substitution index
13948 /// within a \c Sema object.
13949 ///
13950 /// See \c ArgPackSubstIndex for more information.
13951 class ArgPackSubstIndexRAII {
13952 Sema &Self;
13953 UnsignedOrNone OldSubstIndex;
13954
13955 public:
13956 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13957 : Self(Self),
13958 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13959
13960 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13961 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13962 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13963 };
13964
13965 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13966 void popCodeSynthesisContext();
13967
13968 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13969 if (!CodeSynthesisContexts.empty() &&
13970 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13971 PrintInstantiationStack(DiagFunc);
13972 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13973 }
13974 if (PragmaAttributeCurrentTargetDecl)
13975 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13976 }
13977 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13978 /// Prints the current instantiation stack through a series of
13979 /// notes.
13980 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13981 void PrintInstantiationStack() {
13982 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13983 }
13984
13985 /// Returns a pointer to the current SFINAE context, if any.
13986 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13987 return CurrentSFINAEContext;
13988 }
13989 [[nodiscard]] bool isSFINAEContext() const {
13990 return CurrentSFINAEContext != nullptr;
13991 }
13992
13993 /// Perform substitution on the type T with a given set of template
13994 /// arguments.
13995 ///
13996 /// This routine substitutes the given template arguments into the
13997 /// type T and produces the instantiated type.
13998 ///
13999 /// \param T the type into which the template arguments will be
14000 /// substituted. If this type is not dependent, it will be returned
14001 /// immediately.
14002 ///
14003 /// \param Args the template arguments that will be
14004 /// substituted for the top-level template parameters within T.
14005 ///
14006 /// \param Loc the location in the source code where this substitution
14007 /// is being performed. It will typically be the location of the
14008 /// declarator (if we're instantiating the type of some declaration)
14009 /// or the location of the type in the source code (if, e.g., we're
14010 /// instantiating the type of a cast expression).
14011 ///
14012 /// \param Entity the name of the entity associated with a declaration
14013 /// being instantiated (if any). May be empty to indicate that there
14014 /// is no such entity (if, e.g., this is a type that occurs as part of
14015 /// a cast expression) or that the entity has no name (e.g., an
14016 /// unnamed function parameter).
14017 ///
14018 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
14019 /// acceptable as the top level type of the result.
14020 ///
14021 /// \param IsIncompleteSubstitution If provided, the pointee will be set
14022 /// whenever substitution would perform a replacement with a null or
14023 /// non-existent template argument.
14024 ///
14025 /// \returns If the instantiation succeeds, the instantiated
14026 /// type. Otherwise, produces diagnostics and returns a NULL type.
14027 TypeSourceInfo *SubstType(TypeSourceInfo *T,
14028 const MultiLevelTemplateArgumentList &TemplateArgs,
14029 SourceLocation Loc, DeclarationName Entity,
14030 bool AllowDeducedTST = false);
14031
14032 QualType SubstType(QualType T,
14033 const MultiLevelTemplateArgumentList &TemplateArgs,
14034 SourceLocation Loc, DeclarationName Entity,
14035 bool *IsIncompleteSubstitution = nullptr);
14036
14037 TypeSourceInfo *SubstType(TypeLoc TL,
14038 const MultiLevelTemplateArgumentList &TemplateArgs,
14039 SourceLocation Loc, DeclarationName Entity);
14040
14041 TypeSourceInfo *
14042 SubstFriendType(TypeSourceInfo *TSI,
14043 const MultiLevelTemplateArgumentList &TemplateArgs,
14044 SourceLocation Loc, DeclarationName Entity);
14045
14046 /// A form of SubstType intended specifically for instantiating the
14047 /// type of a FunctionDecl. Its purpose is solely to force the
14048 /// instantiation of default-argument expressions and to avoid
14049 /// instantiating an exception-specification.
14050 TypeSourceInfo *SubstFunctionDeclType(
14051 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
14052 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
14053 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
14054 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
14055 const MultiLevelTemplateArgumentList &Args);
14056 bool SubstExceptionSpec(SourceLocation Loc,
14057 FunctionProtoType::ExceptionSpecInfo &ESI,
14058 SmallVectorImpl<QualType> &ExceptionStorage,
14059 const MultiLevelTemplateArgumentList &Args);
14060 /// An attribute whose instantiation is deferred, together with the
14061 /// instantiation scope to instantiate it in.
14062 struct LateInstantiatedAttribute {
14063 const Attr *TmplAttr;
14064 LocalInstantiationScope *Scope;
14065 Decl *NewDecl;
14066
14067 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14068 Decl *D)
14069 : TmplAttr(A), Scope(S), NewDecl(D) {}
14070 };
14071 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14072
14073 /// Substitute into a function parameter. If \p LateAttrs is given, its
14074 /// late-parsed attributes are deferred there, since they may name a
14075 /// parameter that is not substituted yet; see \ref InstantiateLateAttrs.
14076 ParmVarDecl *
14077 SubstParmVarDecl(ParmVarDecl *D,
14078 const MultiLevelTemplateArgumentList &TemplateArgs,
14079 int indexAdjustment, UnsignedOrNone NumExpansions,
14080 bool ExpectParameterPack, bool EvaluateConstraints = true,
14081 LateInstantiatedAttrVec *LateAttrs = nullptr);
14082
14083 /// Substitute the given template arguments into the given set of
14084 /// parameters, producing the set of parameter types that would be generated
14085 /// from such a substitution. If there is a parameter with no ParmVarDecl to
14086 /// substitute (a null entry of \p Params, as from a typedef'd function
14087 /// type), its type needs to come from \p OldParamTypes instead, which must
14088 /// then be passed, and \p OutParams gets null for it.
14089 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
14090 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
14091 const MultiLevelTemplateArgumentList &TemplateArgs,
14092 SmallVectorImpl<QualType> &ParamTypes,
14093 SmallVectorImpl<ParmVarDecl *> *OutParams,
14094 ExtParameterInfoBuilder &ParamInfos,
14095 const QualType *OldParamTypes = nullptr,
14096 bool EvaluateConstraints = true);
14097
14098 /// Substitute the given template arguments into the default argument.
14099 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
14100 const MultiLevelTemplateArgumentList &TemplateArgs,
14101 bool ForCallExpr = false);
14102 ExprResult SubstExpr(Expr *E,
14103 const MultiLevelTemplateArgumentList &TemplateArgs);
14104 /// Substitute an expression as if it is a address-of-operand, which makes it
14105 /// act like a CXXIdExpression rather than an attempt to call.
14106 ExprResult SubstCXXIdExpr(Expr *E,
14107 const MultiLevelTemplateArgumentList &TemplateArgs);
14108
14109 // Must be used instead of SubstExpr at 'constraint checking' time.
14110 ExprResult
14111 SubstConstraintExpr(Expr *E,
14112 const MultiLevelTemplateArgumentList &TemplateArgs);
14113 // Unlike the above, this does not evaluate constraints.
14114 ExprResult SubstConstraintExprWithoutSatisfaction(
14115 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
14116
14117 /// Substitute the given template arguments into a list of
14118 /// expressions, expanding pack expansions if required.
14119 ///
14120 /// \param Exprs The list of expressions to substitute into.
14121 ///
14122 /// \param IsCall Whether this is some form of call, in which case
14123 /// default arguments will be dropped.
14124 ///
14125 /// \param TemplateArgs The set of template arguments to substitute.
14126 ///
14127 /// \param Outputs Will receive all of the substituted arguments.
14128 ///
14129 /// \returns true if an error occurred, false otherwise.
14130 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
14131 const MultiLevelTemplateArgumentList &TemplateArgs,
14132 SmallVectorImpl<Expr *> &Outputs);
14133
14134 StmtResult SubstStmt(Stmt *S,
14135 const MultiLevelTemplateArgumentList &TemplateArgs);
14136
14137 ExprResult
14138 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
14139 bool CXXDirectInit);
14140
14141 /// Perform substitution on the base class specifiers of the
14142 /// given class template specialization.
14143 ///
14144 /// Produces a diagnostic and returns true on error, returns false and
14145 /// attaches the instantiated base classes to the class template
14146 /// specialization if successful.
14147 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14148 const MultiLevelTemplateArgumentList &TemplateArgs);
14149
14150 /// Instantiate the definition of a class from a given pattern.
14151 ///
14152 /// \param PointOfInstantiation The point of instantiation within the
14153 /// source code.
14154 ///
14155 /// \param Instantiation is the declaration whose definition is being
14156 /// instantiated. This will be either a class template specialization
14157 /// or a member class of a class template specialization.
14158 ///
14159 /// \param Pattern is the pattern from which the instantiation
14160 /// occurs. This will be either the declaration of a class template or
14161 /// the declaration of a member class of a class template.
14162 ///
14163 /// \param TemplateArgs The template arguments to be substituted into
14164 /// the pattern.
14165 ///
14166 /// \param TSK the kind of implicit or explicit instantiation to perform.
14167 ///
14168 /// \param Complain whether to complain if the class cannot be instantiated
14169 /// due to the lack of a definition.
14170 ///
14171 /// \returns true if an error occurred, false otherwise.
14172 bool InstantiateClass(SourceLocation PointOfInstantiation,
14173 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
14174 const MultiLevelTemplateArgumentList &TemplateArgs,
14175 TemplateSpecializationKind TSK, bool Complain = true);
14176
14177private:
14178 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
14179 CXXRecordDecl *Instantiation,
14180 CXXRecordDecl *Pattern,
14181 const MultiLevelTemplateArgumentList &TemplateArgs,
14182 TemplateSpecializationKind TSK, bool Complain);
14183
14184public:
14185 /// Instantiate the definition of an enum from a given pattern.
14186 ///
14187 /// \param PointOfInstantiation The point of instantiation within the
14188 /// source code.
14189 /// \param Instantiation is the declaration whose definition is being
14190 /// instantiated. This will be a member enumeration of a class
14191 /// temploid specialization, or a local enumeration within a
14192 /// function temploid specialization.
14193 /// \param Pattern The templated declaration from which the instantiation
14194 /// occurs.
14195 /// \param TemplateArgs The template arguments to be substituted into
14196 /// the pattern.
14197 /// \param TSK The kind of implicit or explicit instantiation to perform.
14198 ///
14199 /// \return \c true if an error occurred, \c false otherwise.
14200 bool InstantiateEnum(SourceLocation PointOfInstantiation,
14201 EnumDecl *Instantiation, EnumDecl *Pattern,
14202 const MultiLevelTemplateArgumentList &TemplateArgs,
14203 TemplateSpecializationKind TSK);
14204
14205 /// Instantiate the definition of a field from the given pattern.
14206 ///
14207 /// \param PointOfInstantiation The point of instantiation within the
14208 /// source code.
14209 /// \param Instantiation is the declaration whose definition is being
14210 /// instantiated. This will be a class of a class temploid
14211 /// specialization, or a local enumeration within a function temploid
14212 /// specialization.
14213 /// \param Pattern The templated declaration from which the instantiation
14214 /// occurs.
14215 /// \param TemplateArgs The template arguments to be substituted into
14216 /// the pattern.
14217 ///
14218 /// \return \c true if an error occurred, \c false otherwise.
14219 bool InstantiateInClassInitializer(
14220 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
14221 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
14222
14223 bool usesPartialOrExplicitSpecialization(
14224 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14225
14226 bool InstantiateClassTemplateSpecialization(
14227 SourceLocation PointOfInstantiation,
14228 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14229 TemplateSpecializationKind TSK, bool Complain,
14230 bool PrimaryStrictPackMatch);
14231
14232 /// Instantiates the definitions of all of the member
14233 /// of the given class, which is an instantiation of a class template
14234 /// or a member class of a template.
14235 void
14236 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14237 CXXRecordDecl *Instantiation,
14238 const MultiLevelTemplateArgumentList &TemplateArgs,
14239 TemplateSpecializationKind TSK);
14240
14241 /// Instantiate the definitions of all of the members of the
14242 /// given class template specialization, which was named as part of an
14243 /// explicit instantiation.
14244 void InstantiateClassTemplateSpecializationMembers(
14245 SourceLocation PointOfInstantiation,
14246 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14247 TemplateSpecializationKind TSK);
14248
14249 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14250 NestedNameSpecifierLoc NNS,
14251 const MultiLevelTemplateArgumentList &TemplateArgs);
14252
14253 /// Do template substitution on declaration name info.
14254 DeclarationNameInfo
14255 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14256 const MultiLevelTemplateArgumentList &TemplateArgs);
14257 TemplateName
14258 SubstTemplateName(SourceLocation TemplateKWLoc,
14259 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14260 SourceLocation NameLoc,
14261 const MultiLevelTemplateArgumentList &TemplateArgs);
14262
14263 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14264 const MultiLevelTemplateArgumentList &TemplateArgs,
14265 bool EvaluateConstraint);
14266
14267 /// Determine whether we are currently performing template instantiation.
14268 bool inTemplateInstantiation() const {
14269 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14270 }
14271
14272 /// Determine whether we are currently performing constraint substitution.
14273 bool inConstraintSubstitution() const {
14274 return !CodeSynthesisContexts.empty() &&
14275 CodeSynthesisContexts.back().InConstraintSubstitution;
14276 }
14277
14278 bool inParameterMappingSubstitution() const {
14279 return !CodeSynthesisContexts.empty() &&
14280 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14281 !inConstraintSubstitution();
14282 }
14283
14284 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14285
14286 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14287 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14288 concepts::Requirement::SubstitutionDiagnostic *
14289 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14290
14291 ///@}
14292
14293 //
14294 //
14295 // -------------------------------------------------------------------------
14296 //
14297 //
14298
14299 /// \name C++ Template Declaration Instantiation
14300 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14301 ///@{
14302
14303public:
14304 /// An entity for which implicit template instantiation is required.
14305 ///
14306 /// The source location associated with the declaration is the first place in
14307 /// the source code where the declaration was "used". It is not necessarily
14308 /// the point of instantiation (which will be either before or after the
14309 /// namespace-scope declaration that triggered this implicit instantiation),
14310 /// However, it is the location that diagnostics should generally refer to,
14311 /// because users will need to know what code triggered the instantiation.
14312 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14313
14314 /// The queue of implicit template instantiations that are required
14315 /// but have not yet been performed.
14316 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14317
14318 /// Queue of implicit template instantiations that cannot be performed
14319 /// eagerly.
14320 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14321
14322 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14323 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14324 SavedPendingInstantiations;
14325
14326 /// The queue of implicit template instantiations that are required
14327 /// and must be performed within the current local scope.
14328 ///
14329 /// This queue is only used for member functions of local classes in
14330 /// templates, which must be instantiated in the same scope as their
14331 /// enclosing function, so that they can reference function-local
14332 /// types, static variables, enumerators, etc.
14333 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14334
14335 class LocalEagerInstantiationScope {
14336 public:
14337 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14338 : S(S), AtEndOfTU(AtEndOfTU) {
14339 SavedPendingLocalImplicitInstantiations.swap(
14340 x&: S.PendingLocalImplicitInstantiations);
14341 }
14342
14343 void perform() {
14344 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14345 /*AtEndOfTU=*/AtEndOfTU);
14346 }
14347
14348 ~LocalEagerInstantiationScope() {
14349 assert(S.PendingLocalImplicitInstantiations.empty() &&
14350 "there shouldn't be any pending local implicit instantiations");
14351 SavedPendingLocalImplicitInstantiations.swap(
14352 x&: S.PendingLocalImplicitInstantiations);
14353 }
14354
14355 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14356 LocalEagerInstantiationScope &
14357 operator=(const LocalEagerInstantiationScope &) = delete;
14358
14359 private:
14360 Sema &S;
14361 bool AtEndOfTU;
14362 std::deque<PendingImplicitInstantiation>
14363 SavedPendingLocalImplicitInstantiations;
14364 };
14365
14366 /// Records and restores the CurFPFeatures state on entry/exit of compound
14367 /// statements.
14368 class FPFeaturesStateRAII {
14369 public:
14370 FPFeaturesStateRAII(Sema &S);
14371 ~FPFeaturesStateRAII();
14372 FPFeaturesStateRAII(const FPFeaturesStateRAII &) = delete;
14373 FPFeaturesStateRAII &operator=(const FPFeaturesStateRAII &) = delete;
14374 FPOptionsOverride getOverrides() { return OldOverrides; }
14375
14376 private:
14377 Sema &S;
14378 FPOptions OldFPFeaturesState;
14379 FPOptionsOverride OldOverrides;
14380 LangOptions::FPEvalMethodKind OldEvalMethod;
14381 SourceLocation OldFPPragmaLocation;
14382 };
14383
14384 class GlobalEagerInstantiationScope {
14385 public:
14386 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14387 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14388 if (!Enabled)
14389 return;
14390
14391 S.SavedPendingInstantiations.emplace_back();
14392 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14393
14394 S.SavedVTableUses.emplace_back();
14395 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14396 }
14397
14398 void perform() {
14399 if (Enabled) {
14400 S.DefineUsedVTables();
14401 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14402 /*AtEndOfTU=*/AtEndOfTU);
14403 }
14404 }
14405
14406 ~GlobalEagerInstantiationScope() {
14407 if (!Enabled)
14408 return;
14409
14410 // Restore the set of pending vtables.
14411 assert(S.VTableUses.empty() &&
14412 "VTableUses should be empty before it is discarded.");
14413 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14414 S.SavedVTableUses.pop_back();
14415
14416 // Restore the set of pending implicit instantiations.
14417 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14418 AtEndOfTU) {
14419 assert(S.PendingInstantiations.empty() &&
14420 "PendingInstantiations should be empty before it is discarded.");
14421 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14422 S.SavedPendingInstantiations.pop_back();
14423 } else {
14424 // Template instantiations in the PCH may be delayed until the TU.
14425 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14426 S.PendingInstantiations.insert(
14427 position: S.PendingInstantiations.end(),
14428 first: S.SavedPendingInstantiations.back().begin(),
14429 last: S.SavedPendingInstantiations.back().end());
14430 S.SavedPendingInstantiations.pop_back();
14431 }
14432 }
14433
14434 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14435 delete;
14436 GlobalEagerInstantiationScope &
14437 operator=(const GlobalEagerInstantiationScope &) = delete;
14438
14439 private:
14440 Sema &S;
14441 bool Enabled;
14442 bool AtEndOfTU;
14443 };
14444
14445 ExplicitSpecifier instantiateExplicitSpecifier(
14446 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14447
14448 /// Recheck instantiated thread-safety attributes that could not be validated
14449 /// on the dependent pattern declaration.
14450 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14451
14452 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14453 const Decl *Pattern, Decl *Inst,
14454 LateInstantiatedAttrVec *LateAttrs = nullptr,
14455 LocalInstantiationScope *OuterMostScope = nullptr);
14456
14457 /// Instantiate the attributes that \ref InstantiateAttrs deferred to \p
14458 /// LateAttrs, and attach them to their declarations. They are instantiated
14459 /// in the scopes saved with them, which extend \p OuterMostScope, the
14460 /// current scope.
14461 void InstantiateLateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14462 LateInstantiatedAttrVec &LateAttrs,
14463 LocalInstantiationScope *OuterMostScope);
14464
14465 /// Update instantiation attributes after template was late parsed.
14466 ///
14467 /// Some attributes are evaluated based on the body of template. If it is
14468 /// late parsed, such attributes cannot be evaluated when declaration is
14469 /// instantiated. This function is used to update instantiation attributes
14470 /// when template definition is ready.
14471 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14472
14473 void
14474 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14475 const Decl *Pattern, Decl *Inst,
14476 LateInstantiatedAttrVec *LateAttrs = nullptr,
14477 LocalInstantiationScope *OuterMostScope = nullptr);
14478
14479 bool BuildCtorClosureDefaultArgs(SourceLocation Loc, CXXConstructorDecl *Ctor,
14480 bool IsCopy = false);
14481
14482 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14483 ParmVarDecl *Param);
14484 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14485 FunctionDecl *Function);
14486
14487 /// Instantiate (or find existing instantiation of) a function template with a
14488 /// given set of template arguments.
14489 ///
14490 /// Usually this should not be used, and template argument deduction should be
14491 /// used in its place.
14492 FunctionDecl *InstantiateFunctionDeclaration(
14493 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14494 SourceLocation Loc,
14495 CodeSynthesisContext::SynthesisKind CSC =
14496 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14497
14498 /// Instantiate the definition of the given function from its
14499 /// template.
14500 ///
14501 /// \param PointOfInstantiation the point at which the instantiation was
14502 /// required. Note that this is not precisely a "point of instantiation"
14503 /// for the function, but it's close.
14504 ///
14505 /// \param Function the already-instantiated declaration of a
14506 /// function template specialization or member function of a class template
14507 /// specialization.
14508 ///
14509 /// \param Recursive if true, recursively instantiates any functions that
14510 /// are required by this instantiation.
14511 ///
14512 /// \param DefinitionRequired if true, then we are performing an explicit
14513 /// instantiation where the body of the function is required. Complain if
14514 /// there is no such body.
14515 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14516 FunctionDecl *Function,
14517 bool Recursive = false,
14518 bool DefinitionRequired = false,
14519 bool AtEndOfTU = false);
14520 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14521 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14522 const TemplateArgumentList *PartialSpecArgs,
14523 SmallVectorImpl<TemplateArgument> &Converted,
14524 SourceLocation PointOfInstantiation,
14525 LateInstantiatedAttrVec *LateAttrs = nullptr,
14526 LocalInstantiationScope *StartingScope = nullptr);
14527
14528 /// Instantiates a variable template specialization by completing it
14529 /// with appropriate type information and initializer.
14530 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14531 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14532 const MultiLevelTemplateArgumentList &TemplateArgs);
14533
14534 /// BuildVariableInstantiation - Used after a new variable has been created.
14535 /// Sets basic variable data and decides whether to postpone the
14536 /// variable instantiation.
14537 void
14538 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14539 const MultiLevelTemplateArgumentList &TemplateArgs,
14540 LateInstantiatedAttrVec *LateAttrs,
14541 DeclContext *Owner,
14542 LocalInstantiationScope *StartingScope,
14543 bool InstantiatingVarTemplate = false,
14544 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14545
14546 /// Instantiate the initializer of a variable.
14547 void InstantiateVariableInitializer(
14548 VarDecl *Var, VarDecl *OldVar,
14549 const MultiLevelTemplateArgumentList &TemplateArgs);
14550
14551 /// Instantiate the definition of the given variable from its
14552 /// template.
14553 ///
14554 /// \param PointOfInstantiation the point at which the instantiation was
14555 /// required. Note that this is not precisely a "point of instantiation"
14556 /// for the variable, but it's close.
14557 ///
14558 /// \param Var the already-instantiated declaration of a templated variable.
14559 ///
14560 /// \param Recursive if true, recursively instantiates any functions that
14561 /// are required by this instantiation.
14562 ///
14563 /// \param DefinitionRequired if true, then we are performing an explicit
14564 /// instantiation where a definition of the variable is required. Complain
14565 /// if there is no such definition.
14566 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14567 VarDecl *Var, bool Recursive = false,
14568 bool DefinitionRequired = false,
14569 bool AtEndOfTU = false);
14570
14571 void InstantiateMemInitializers(
14572 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14573 const MultiLevelTemplateArgumentList &TemplateArgs);
14574
14575 /// Find the instantiation of the given declaration within the
14576 /// current instantiation.
14577 ///
14578 /// This routine is intended to be used when \p D is a declaration
14579 /// referenced from within a template, that needs to mapped into the
14580 /// corresponding declaration within an instantiation. For example,
14581 /// given:
14582 ///
14583 /// \code
14584 /// template<typename T>
14585 /// struct X {
14586 /// enum Kind {
14587 /// KnownValue = sizeof(T)
14588 /// };
14589 ///
14590 /// bool getKind() const { return KnownValue; }
14591 /// };
14592 ///
14593 /// template struct X<int>;
14594 /// \endcode
14595 ///
14596 /// In the instantiation of X<int>::getKind(), we need to map the \p
14597 /// EnumConstantDecl for \p KnownValue (which refers to
14598 /// X<T>::<Kind>::KnownValue) to its instantiation
14599 /// (X<int>::<Kind>::KnownValue).
14600 /// \p FindInstantiatedDecl performs this mapping from within the
14601 /// instantiation of X<int>.
14602 NamedDecl *
14603 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14604 const MultiLevelTemplateArgumentList &TemplateArgs,
14605 bool FindingInstantiatedContext = false);
14606
14607 /// Finds the instantiation of the given declaration context
14608 /// within the current instantiation.
14609 ///
14610 /// \returns NULL if there was an error
14611 DeclContext *
14612 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14613 const MultiLevelTemplateArgumentList &TemplateArgs);
14614
14615 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14616 const MultiLevelTemplateArgumentList &TemplateArgs);
14617
14618 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14619 /// an implicit 'operator=='.
14620 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14621 FunctionDecl *Spaceship);
14622
14623 /// Performs template instantiation for all implicit template
14624 /// instantiations we have seen until this point.
14625 void PerformPendingInstantiations(bool LocalOnly = false,
14626 bool AtEndOfTU = true);
14627
14628 TemplateParameterList *
14629 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14630 const MultiLevelTemplateArgumentList &TemplateArgs,
14631 bool EvaluateConstraints = true);
14632
14633 void PerformDependentDiagnostics(
14634 const DeclContext *Pattern,
14635 const MultiLevelTemplateArgumentList &TemplateArgs);
14636
14637private:
14638 /// Introduce the instantiated local variables into the local
14639 /// instantiation scope.
14640 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14641 const FunctionDecl *PatternDecl,
14642 LocalInstantiationScope &Scope);
14643 /// Introduce the instantiated function parameters into the local
14644 /// instantiation scope, and set the parameter names to those used
14645 /// in the template.
14646 bool addInstantiatedParametersToScope(
14647 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14648 LocalInstantiationScope &Scope,
14649 const MultiLevelTemplateArgumentList &TemplateArgs);
14650
14651 /// Introduce the instantiated captures of the lambda into the local
14652 /// instantiation scope.
14653 bool addInstantiatedCapturesToScope(
14654 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14655 LocalInstantiationScope &Scope,
14656 const MultiLevelTemplateArgumentList &TemplateArgs);
14657
14658 int ParsingClassDepth = 0;
14659
14660 class SavePendingParsedClassStateRAII {
14661 public:
14662 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14663
14664 ~SavePendingParsedClassStateRAII() {
14665 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14666 "there shouldn't be any pending delayed exception spec checks");
14667 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14668 "there shouldn't be any pending delayed exception spec checks");
14669 swapSavedState();
14670 }
14671
14672 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14673 delete;
14674 SavePendingParsedClassStateRAII &
14675 operator=(const SavePendingParsedClassStateRAII &) = delete;
14676
14677 private:
14678 Sema &S;
14679 decltype(DelayedOverridingExceptionSpecChecks)
14680 SavedOverridingExceptionSpecChecks;
14681 decltype(DelayedEquivalentExceptionSpecChecks)
14682 SavedEquivalentExceptionSpecChecks;
14683
14684 void swapSavedState() {
14685 SavedOverridingExceptionSpecChecks.swap(
14686 RHS&: S.DelayedOverridingExceptionSpecChecks);
14687 SavedEquivalentExceptionSpecChecks.swap(
14688 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14689 }
14690 };
14691
14692 ///@}
14693
14694 //
14695 //
14696 // -------------------------------------------------------------------------
14697 //
14698 //
14699
14700 /// \name C++ Variadic Templates
14701 /// Implementations are in SemaTemplateVariadic.cpp
14702 ///@{
14703
14704public:
14705 /// Determine whether an unexpanded parameter pack might be permitted in this
14706 /// location. Useful for error recovery.
14707 bool isUnexpandedParameterPackPermitted();
14708
14709 /// The context in which an unexpanded parameter pack is
14710 /// being diagnosed.
14711 ///
14712 /// Note that the values of this enumeration line up with the first
14713 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14714 enum UnexpandedParameterPackContext {
14715 /// An arbitrary expression.
14716 UPPC_Expression = 0,
14717
14718 /// The base type of a class type.
14719 UPPC_BaseType,
14720
14721 /// The type of an arbitrary declaration.
14722 UPPC_DeclarationType,
14723
14724 /// The type of a data member.
14725 UPPC_DataMemberType,
14726
14727 /// The size of a bit-field.
14728 UPPC_BitFieldWidth,
14729
14730 /// The expression in a static assertion.
14731 UPPC_StaticAssertExpression,
14732
14733 /// The fixed underlying type of an enumeration.
14734 UPPC_FixedUnderlyingType,
14735
14736 /// The enumerator value.
14737 UPPC_EnumeratorValue,
14738
14739 /// A using declaration.
14740 UPPC_UsingDeclaration,
14741
14742 /// A friend declaration.
14743 UPPC_FriendDeclaration,
14744
14745 /// A declaration qualifier.
14746 UPPC_DeclarationQualifier,
14747
14748 /// An initializer.
14749 UPPC_Initializer,
14750
14751 /// A default argument.
14752 UPPC_DefaultArgument,
14753
14754 /// The type of a non-type template parameter.
14755 UPPC_NonTypeTemplateParameterType,
14756
14757 /// The type of an exception.
14758 UPPC_ExceptionType,
14759
14760 /// Explicit specialization.
14761 UPPC_ExplicitSpecialization,
14762
14763 /// Partial specialization.
14764 UPPC_PartialSpecialization,
14765
14766 /// Microsoft __if_exists.
14767 UPPC_IfExists,
14768
14769 /// Microsoft __if_not_exists.
14770 UPPC_IfNotExists,
14771
14772 /// Lambda expression.
14773 UPPC_Lambda,
14774
14775 /// Block expression.
14776 UPPC_Block,
14777
14778 /// A type constraint.
14779 UPPC_TypeConstraint,
14780
14781 // A requirement in a requires-expression.
14782 UPPC_Requirement,
14783
14784 // A requires-clause.
14785 UPPC_RequiresClause,
14786 };
14787
14788 /// Diagnose unexpanded parameter packs.
14789 ///
14790 /// \param Loc The location at which we should emit the diagnostic.
14791 ///
14792 /// \param UPPC The context in which we are diagnosing unexpanded
14793 /// parameter packs.
14794 ///
14795 /// \param Unexpanded the set of unexpanded parameter packs.
14796 ///
14797 /// \returns true if an error occurred, false otherwise.
14798 bool DiagnoseUnexpandedParameterPacks(
14799 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14800 ArrayRef<UnexpandedParameterPack> Unexpanded);
14801
14802 /// If the given type contains an unexpanded parameter pack,
14803 /// diagnose the error.
14804 ///
14805 /// \param Loc The source location where a diagnostc should be emitted.
14806 ///
14807 /// \param T The type that is being checked for unexpanded parameter
14808 /// packs.
14809 ///
14810 /// \returns true if an error occurred, false otherwise.
14811 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14812 UnexpandedParameterPackContext UPPC);
14813
14814 /// If the given expression contains an unexpanded parameter
14815 /// pack, diagnose the error.
14816 ///
14817 /// \param E The expression that is being checked for unexpanded
14818 /// parameter packs.
14819 ///
14820 /// \returns true if an error occurred, false otherwise.
14821 bool DiagnoseUnexpandedParameterPack(
14822 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14823
14824 /// If the given requirees-expression contains an unexpanded reference to one
14825 /// of its own parameter packs, diagnose the error.
14826 ///
14827 /// \param RE The requiress-expression that is being checked for unexpanded
14828 /// parameter packs.
14829 ///
14830 /// \returns true if an error occurred, false otherwise.
14831 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14832
14833 /// If the given nested-name-specifier contains an unexpanded
14834 /// parameter pack, diagnose the error.
14835 ///
14836 /// \param SS The nested-name-specifier that is being checked for
14837 /// unexpanded parameter packs.
14838 ///
14839 /// \returns true if an error occurred, false otherwise.
14840 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14841 UnexpandedParameterPackContext UPPC);
14842
14843 /// If the given name contains an unexpanded parameter pack,
14844 /// diagnose the error.
14845 ///
14846 /// \param NameInfo The name (with source location information) that
14847 /// is being checked for unexpanded parameter packs.
14848 ///
14849 /// \returns true if an error occurred, false otherwise.
14850 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14851 UnexpandedParameterPackContext UPPC);
14852
14853 /// If the given template name contains an unexpanded parameter pack,
14854 /// diagnose the error.
14855 ///
14856 /// \param Loc The location of the template name.
14857 ///
14858 /// \param Template The template name that is being checked for unexpanded
14859 /// parameter packs.
14860 ///
14861 /// \returns true if an error occurred, false otherwise.
14862 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14863 TemplateName Template,
14864 UnexpandedParameterPackContext UPPC);
14865
14866 /// If the given template argument contains an unexpanded parameter
14867 /// pack, diagnose the error.
14868 ///
14869 /// \param Arg The template argument that is being checked for unexpanded
14870 /// parameter packs.
14871 ///
14872 /// \returns true if an error occurred, false otherwise.
14873 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14874 UnexpandedParameterPackContext UPPC);
14875
14876 /// Collect the set of unexpanded parameter packs within the given
14877 /// template argument.
14878 ///
14879 /// \param Arg The template argument that will be traversed to find
14880 /// unexpanded parameter packs.
14881 void collectUnexpandedParameterPacks(
14882 TemplateArgument Arg,
14883 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14884
14885 /// Collect the set of unexpanded parameter packs within the given
14886 /// template argument.
14887 ///
14888 /// \param Arg The template argument that will be traversed to find
14889 /// unexpanded parameter packs.
14890 void collectUnexpandedParameterPacks(
14891 TemplateArgumentLoc Arg,
14892 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14893
14894 /// Collect the set of unexpanded parameter packs within the given
14895 /// type.
14896 ///
14897 /// \param T The type that will be traversed to find
14898 /// unexpanded parameter packs.
14899 void collectUnexpandedParameterPacks(
14900 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14901
14902 /// Collect the set of unexpanded parameter packs within the given
14903 /// template name.
14904 ///
14905 /// \param Template The template name that will be traversed to find
14906 /// unexpanded parameter packs.
14907 void collectUnexpandedParameterPacks(
14908 TemplateName Template,
14909 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14910
14911 /// Collect the set of unexpanded parameter packs within the given
14912 /// type.
14913 ///
14914 /// \param TL The type that will be traversed to find
14915 /// unexpanded parameter packs.
14916 void collectUnexpandedParameterPacks(
14917 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14918
14919 /// Collect the set of unexpanded parameter packs within the given
14920 /// nested-name-specifier.
14921 ///
14922 /// \param NNS The nested-name-specifier that will be traversed to find
14923 /// unexpanded parameter packs.
14924 void collectUnexpandedParameterPacks(
14925 NestedNameSpecifierLoc NNS,
14926 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14927
14928 /// Collect the set of unexpanded parameter packs within the given
14929 /// name.
14930 ///
14931 /// \param NameInfo The name that will be traversed to find
14932 /// unexpanded parameter packs.
14933 void collectUnexpandedParameterPacks(
14934 const DeclarationNameInfo &NameInfo,
14935 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14936
14937 /// Collect the set of unexpanded parameter packs within the given
14938 /// expression.
14939 static void collectUnexpandedParameterPacks(
14940 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14941
14942 /// Invoked when parsing a template argument.
14943 ///
14944 /// \param Arg the template argument, which may already be invalid.
14945 ///
14946 /// If it is followed by ellipsis, this function is called before
14947 /// `ActOnPackExpansion`.
14948 ParsedTemplateArgument
14949 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14950
14951 /// Invoked when parsing a template argument followed by an
14952 /// ellipsis, which creates a pack expansion.
14953 ///
14954 /// \param Arg The template argument preceding the ellipsis, which
14955 /// may already be invalid.
14956 ///
14957 /// \param EllipsisLoc The location of the ellipsis.
14958 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14959 SourceLocation EllipsisLoc);
14960
14961 /// Invoked when parsing a type followed by an ellipsis, which
14962 /// creates a pack expansion.
14963 ///
14964 /// \param Type The type preceding the ellipsis, which will become
14965 /// the pattern of the pack expansion.
14966 ///
14967 /// \param EllipsisLoc The location of the ellipsis.
14968 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14969
14970 /// Construct a pack expansion type from the pattern of the pack
14971 /// expansion.
14972 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14973 SourceLocation EllipsisLoc,
14974 UnsignedOrNone NumExpansions);
14975
14976 /// Construct a pack expansion type from the pattern of the pack
14977 /// expansion.
14978 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14979 SourceLocation EllipsisLoc,
14980 UnsignedOrNone NumExpansions);
14981
14982 /// Invoked when parsing an expression followed by an ellipsis, which
14983 /// creates a pack expansion.
14984 ///
14985 /// \param Pattern The expression preceding the ellipsis, which will become
14986 /// the pattern of the pack expansion.
14987 ///
14988 /// \param EllipsisLoc The location of the ellipsis.
14989 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14990
14991 /// Invoked when parsing an expression followed by an ellipsis, which
14992 /// creates a pack expansion.
14993 ///
14994 /// \param Pattern The expression preceding the ellipsis, which will become
14995 /// the pattern of the pack expansion.
14996 ///
14997 /// \param EllipsisLoc The location of the ellipsis.
14998 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14999 UnsignedOrNone NumExpansions);
15000
15001 /// Determine whether we could expand a pack expansion with the
15002 /// given set of parameter packs into separate arguments by repeatedly
15003 /// transforming the pattern.
15004 ///
15005 /// \param EllipsisLoc The location of the ellipsis that identifies the
15006 /// pack expansion.
15007 ///
15008 /// \param PatternRange The source range that covers the entire pattern of
15009 /// the pack expansion.
15010 ///
15011 /// \param Unexpanded The set of unexpanded parameter packs within the
15012 /// pattern.
15013 ///
15014 /// \param ShouldExpand Will be set to \c true if the transformer should
15015 /// expand the corresponding pack expansions into separate arguments. When
15016 /// set, \c NumExpansions must also be set.
15017 ///
15018 /// \param RetainExpansion Whether the caller should add an unexpanded
15019 /// pack expansion after all of the expanded arguments. This is used
15020 /// when extending explicitly-specified template argument packs per
15021 /// C++0x [temp.arg.explicit]p9.
15022 ///
15023 /// \param NumExpansions The number of separate arguments that will be in
15024 /// the expanded form of the corresponding pack expansion. This is both an
15025 /// input and an output parameter, which can be set by the caller if the
15026 /// number of expansions is known a priori (e.g., due to a prior substitution)
15027 /// and will be set by the callee when the number of expansions is known.
15028 /// The callee must set this value when \c ShouldExpand is \c true; it may
15029 /// set this value in other cases.
15030 ///
15031 /// \returns true if an error occurred (e.g., because the parameter packs
15032 /// are to be instantiated with arguments of different lengths), false
15033 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
15034 /// must be set.
15035 bool CheckParameterPacksForExpansion(
15036 SourceLocation EllipsisLoc, SourceRange PatternRange,
15037 ArrayRef<UnexpandedParameterPack> Unexpanded,
15038 const MultiLevelTemplateArgumentList &TemplateArgs,
15039 bool FailOnPackProducingTemplates, bool &ShouldExpand,
15040 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
15041 bool Diagnose = true);
15042
15043 /// Determine the number of arguments in the given pack expansion
15044 /// type.
15045 ///
15046 /// This routine assumes that the number of arguments in the expansion is
15047 /// consistent across all of the unexpanded parameter packs in its pattern.
15048 ///
15049 /// Returns an empty Optional if the type can't be expanded.
15050 UnsignedOrNone getNumArgumentsInExpansion(
15051 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
15052
15053 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
15054 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
15055 const MultiLevelTemplateArgumentList &TemplateArgs);
15056
15057 /// Determine whether the given declarator contains any unexpanded
15058 /// parameter packs.
15059 ///
15060 /// This routine is used by the parser to disambiguate function declarators
15061 /// with an ellipsis prior to the ')', e.g.,
15062 ///
15063 /// \code
15064 /// void f(T...);
15065 /// \endcode
15066 ///
15067 /// To determine whether we have an (unnamed) function parameter pack or
15068 /// a variadic function.
15069 ///
15070 /// \returns true if the declarator contains any unexpanded parameter packs,
15071 /// false otherwise.
15072 bool containsUnexpandedParameterPacks(Declarator &D);
15073
15074 /// Returns the pattern of the pack expansion for a template argument.
15075 ///
15076 /// \param OrigLoc The template argument to expand.
15077 ///
15078 /// \param Ellipsis Will be set to the location of the ellipsis.
15079 ///
15080 /// \param NumExpansions Will be set to the number of expansions that will
15081 /// be generated from this pack expansion, if known a priori.
15082 TemplateArgumentLoc
15083 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
15084 SourceLocation &Ellipsis,
15085 UnsignedOrNone &NumExpansions) const;
15086
15087 /// Given a template argument that contains an unexpanded parameter pack, but
15088 /// which has already been substituted, attempt to determine the number of
15089 /// elements that will be produced once this argument is fully-expanded.
15090 ///
15091 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
15092 /// avoid actually expanding the pack where possible.
15093 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
15094
15095 /// Called when an expression computing the size of a parameter pack
15096 /// is parsed.
15097 ///
15098 /// \code
15099 /// template<typename ...Types> struct count {
15100 /// static const unsigned value = sizeof...(Types);
15101 /// };
15102 /// \endcode
15103 ///
15104 //
15105 /// \param OpLoc The location of the "sizeof" keyword.
15106 /// \param Name The name of the parameter pack whose size will be determined.
15107 /// \param NameLoc The source location of the name of the parameter pack.
15108 /// \param RParenLoc The location of the closing parentheses.
15109 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
15110 IdentifierInfo &Name,
15111 SourceLocation NameLoc,
15112 SourceLocation RParenLoc);
15113
15114 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
15115 SourceLocation EllipsisLoc,
15116 SourceLocation LSquareLoc, Expr *IndexExpr,
15117 SourceLocation RSquareLoc);
15118
15119 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
15120 SourceLocation EllipsisLoc, Expr *IndexExpr,
15121 SourceLocation RSquareLoc,
15122 ArrayRef<Expr *> ExpandedExprs = {},
15123 bool FullySubstituted = false);
15124
15125 TemplateName ActOnPackIndexingTemplateName(TemplateName Pattern,
15126 SourceLocation NameLoc,
15127 Expr *IndexExpr);
15128
15129 TemplateName
15130 BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr,
15131 bool FullySubstituted = false,
15132 ArrayRef<TemplateName> Expansions = {});
15133
15134 TypeResult
15135 ActOnPackIndexingDeducedTemplateSpecializationType(TemplateName Name,
15136 SourceLocation NameLoc);
15137
15138 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
15139 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
15140 tok::TokenKind Operator,
15141 SourceLocation EllipsisLoc, Expr *RHS,
15142 SourceLocation RParenLoc);
15143 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
15144 SourceLocation LParenLoc, Expr *LHS,
15145 BinaryOperatorKind Operator,
15146 SourceLocation EllipsisLoc, Expr *RHS,
15147 SourceLocation RParenLoc,
15148 UnsignedOrNone NumExpansions);
15149 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
15150 BinaryOperatorKind Operator);
15151
15152 ///@}
15153
15154 //
15155 //
15156 // -------------------------------------------------------------------------
15157 //
15158 //
15159
15160 /// \name Constraints and Concepts
15161 /// Implementations are in SemaConcept.cpp
15162 ///@{
15163
15164public:
15165 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
15166
15167 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
15168 TypeSourceInfo *TSI);
15169
15170public:
15171 void PushSatisfactionStackEntry(const NamedDecl *D,
15172 const llvm::FoldingSetNodeID &ID) {
15173 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
15174 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
15175 }
15176
15177 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
15178
15179 bool SatisfactionStackContains(const NamedDecl *D,
15180 const llvm::FoldingSetNodeID &ID) const {
15181 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
15182 return llvm::is_contained(Range: SatisfactionStack,
15183 Element: SatisfactionStackEntryTy{Can, ID});
15184 }
15185
15186 using SatisfactionStackEntryTy =
15187 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
15188
15189 // Resets the current SatisfactionStack for cases where we are instantiating
15190 // constraints as a 'side effect' of normal instantiation in a way that is not
15191 // indicative of recursive definition.
15192 class SatisfactionStackResetRAII {
15193 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
15194 Sema &SemaRef;
15195
15196 public:
15197 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
15198 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15199 }
15200
15201 ~SatisfactionStackResetRAII() {
15202 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
15203 }
15204
15205 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
15206 SatisfactionStackResetRAII &
15207 operator=(const SatisfactionStackResetRAII &) = delete;
15208 };
15209
15210 void SwapSatisfactionStack(
15211 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
15212 SatisfactionStack.swap(RHS&: NewSS);
15213 }
15214
15215 using ConstrainedDeclOrNestedRequirement =
15216 llvm::PointerUnion<const NamedDecl *,
15217 const concepts::NestedRequirement *>;
15218
15219 /// Check whether the given expression is a valid constraint expression.
15220 /// A diagnostic is emitted if it is not, false is returned, and
15221 /// PossibleNonPrimary will be set to true if the failure might be due to a
15222 /// non-primary expression being used as an atomic constraint.
15223 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
15224 bool *PossibleNonPrimary = nullptr,
15225 bool IsTrailingRequiresClause = false);
15226
15227 /// \brief Check whether the given list of constraint expressions are
15228 /// satisfied (as if in a 'conjunction') given template arguments.
15229 /// \param Template the template-like entity that triggered the constraints
15230 /// check (either a concept or a constrained entity).
15231 /// \param ConstraintExprs a list of constraint expressions, treated as if
15232 /// they were 'AND'ed together.
15233 /// \param TemplateArgLists the list of template arguments to substitute into
15234 /// the constraint expression.
15235 /// \param TemplateIDRange The source range of the template id that
15236 /// caused the constraints check.
15237 /// \param Satisfaction if true is returned, will contain details of the
15238 /// satisfaction, with enough information to diagnose an unsatisfied
15239 /// expression.
15240 /// \returns true if an error occurred and satisfaction could not be checked,
15241 /// false otherwise.
15242 bool CheckConstraintSatisfaction(
15243 ConstrainedDeclOrNestedRequirement Entity,
15244 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15245 const MultiLevelTemplateArgumentList &TemplateArgLists,
15246 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15247 const ConceptReference *TopLevelConceptId = nullptr,
15248 Expr **ConvertedExpr = nullptr);
15249
15250 /// Check whether the given function decl's trailing requires clause is
15251 /// satisfied, if any. Returns false and updates Satisfaction with the
15252 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15253 /// an error occurred and satisfaction could not be determined.
15254 ///
15255 /// \returns true if an error occurred, false otherwise.
15256 bool CheckFunctionConstraints(const FunctionDecl *FD,
15257 ConstraintSatisfaction &Satisfaction,
15258 SourceLocation UsageLoc = SourceLocation(),
15259 bool ForOverloadResolution = false);
15260
15261 // Calculates whether two constraint expressions are equal irrespective of a
15262 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15263 // 'New', which are the "source" of the constraint, since this is necessary
15264 // for figuring out the relative 'depth' of the constraint. The depth of the
15265 // 'primary template' and the 'instantiated from' templates aren't necessarily
15266 // the same, such as a case when one is a 'friend' defined in a class.
15267 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15268 const Expr *OldConstr,
15269 const TemplateCompareNewDeclInfo &New,
15270 const Expr *NewConstr);
15271
15272 // Calculates whether the friend function depends on an enclosing template for
15273 // the purposes of [temp.friend] p9.
15274 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15275
15276 /// \brief Ensure that the given template arguments satisfy the constraints
15277 /// associated with the given template, emitting a diagnostic if they do not.
15278 ///
15279 /// \param Template The template to which the template arguments are being
15280 /// provided.
15281 ///
15282 /// \param TemplateArgs The converted, canonicalized template arguments.
15283 ///
15284 /// \param TemplateIDRange The source range of the template id that
15285 /// caused the constraints check.
15286 ///
15287 /// \returns true if the constrains are not satisfied or could not be checked
15288 /// for satisfaction, false if the constraints are satisfied.
15289 bool EnsureTemplateArgumentListConstraints(
15290 TemplateDecl *Template,
15291 const MultiLevelTemplateArgumentList &TemplateArgs,
15292 SourceRange TemplateIDRange);
15293
15294 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15295 FunctionDecl *Decl,
15296 ArrayRef<TemplateArgument> TemplateArgs,
15297 ConstraintSatisfaction &Satisfaction);
15298
15299 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15300 /// unsatisfied.
15301 /// \param First whether this is the first time an unsatisfied constraint is
15302 /// diagnosed for this error.
15303 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15304 SourceLocation Loc = {},
15305 bool First = true);
15306
15307 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15308 /// unsatisfied.
15309 void
15310 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15311 bool First = true);
15312
15313 void DiagnoseUnsatisfiedRequiresExpr(const RequiresExpr *RequiresExpr,
15314 bool First = true);
15315
15316 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15317 ConstrainedDeclOrNestedRequirement Entity,
15318 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15319
15320 /// \brief Check whether the given declaration's associated constraints are
15321 /// at least as constrained than another declaration's according to the
15322 /// partial ordering of constraints.
15323 ///
15324 /// \param Result If no error occurred, receives the result of true if D1 is
15325 /// at least constrained than D2, and false otherwise.
15326 ///
15327 /// \returns true if an error occurred, false otherwise.
15328 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15329 MutableArrayRef<AssociatedConstraint> AC1,
15330 const NamedDecl *D2,
15331 MutableArrayRef<AssociatedConstraint> AC2,
15332 bool &Result);
15333
15334 /// If D1 was not at least as constrained as D2, but would've been if a pair
15335 /// of atomic constraints involved had been declared in a concept and not
15336 /// repeated in two separate places in code.
15337 /// \returns true if such a diagnostic was emitted, false otherwise.
15338 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15339 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15340 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15341
15342private:
15343 friend class ConstraintSatisfactionChecker;
15344 friend class SubstituteParameterMappings;
15345
15346 UnsignedOrNone EvaluateFoldExpandedConstraintSize(
15347 const Expr *Pattern, const MultiLevelTemplateArgumentList &MLTAL);
15348
15349 /// Cache the satisfaction of an atomic constraint.
15350 /// The key is based on the unsubstituted expression and the parameter
15351 /// mapping. This lets us not substituting the mapping more than once,
15352 /// which is (very!) expensive.
15353 llvm::DenseMap<llvm::FoldingSetNodeIDRef,
15354 UnsubstitutedConstraintSatisfactionCacheResult>
15355 UnsubstitutedConstraintSatisfactionCache;
15356
15357 /// Cache the instantiation results of template parameter mappings within
15358 /// concepts. Substituting into normalized concepts can be extremely expensive
15359 /// due to the redundancy of template parameters. This cache is intended for
15360 /// use by TemplateInstantiator to avoid redundant semantic checking.
15361 llvm::DenseMap<llvm::FoldingSetNodeIDRef, TemplateArgumentLoc>
15362 *CurrentCachedTemplateArgs = nullptr;
15363
15364 /// Caches pairs of template-like decls whose associated constraints were
15365 /// checked for subsumption and whether or not the first's constraints did in
15366 /// fact subsume the second's.
15367 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15368 SubsumptionCache;
15369 /// Caches the normal form of constraint expressions (and their pack
15370 /// substitution index). These are shared by e.g. the members of all
15371 /// specializations of a class template. If an error occurred while
15372 /// normalizing an expression, nullptr will be cached here.
15373 llvm::DenseMap<std::pair<const Expr *, unsigned>, NormalizedConstraint *>
15374 NormalizedConstraintExprCache;
15375
15376 /// Cache whether the associated constraint of a declaration
15377 /// is satisfied.
15378 llvm::DenseMap<llvm::FoldingSetNodeIDRef, ConstraintSatisfaction *>
15379 SatisfactionCache;
15380
15381 // The current stack of constraint satisfactions, so we can exit-early.
15382 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15383
15384 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15385 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15386 /// use LambdaScopeForCallOperatorInstantiationRAII.
15387 bool
15388 SetupConstraintScope(FunctionDecl *FD,
15389 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15390 const MultiLevelTemplateArgumentList &MLTAL,
15391 LocalInstantiationScope &Scope);
15392
15393 /// Used during constraint checking, sets up the constraint template argument
15394 /// lists, and calls SetupConstraintScope to set up the
15395 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15396 std::optional<MultiLevelTemplateArgumentList>
15397 SetupConstraintCheckingTemplateArgumentsAndScope(
15398 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15399 LocalInstantiationScope &Scope);
15400
15401 ///@}
15402
15403 //
15404 //
15405 // -------------------------------------------------------------------------
15406 //
15407 //
15408
15409 /// \name Types
15410 /// Implementations are in SemaType.cpp
15411 ///@{
15412
15413public:
15414 /// A mapping that describes the nullability we've seen in each header file.
15415 FileNullabilityMap NullabilityMap;
15416
15417 static int getPrintable(int I) { return I; }
15418 static unsigned getPrintable(unsigned I) { return I; }
15419 static bool getPrintable(bool B) { return B; }
15420 static const char *getPrintable(const char *S) { return S; }
15421 static StringRef getPrintable(StringRef S) { return S; }
15422 static const std::string &getPrintable(const std::string &S) { return S; }
15423 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15424 return II;
15425 }
15426 static DeclarationName getPrintable(DeclarationName N) { return N; }
15427 static QualType getPrintable(QualType T) { return T; }
15428 static SourceRange getPrintable(SourceRange R) { return R; }
15429 static SourceRange getPrintable(SourceLocation L) { return L; }
15430 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15431 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15432
15433 enum class CompleteTypeKind {
15434 /// Apply the normal rules for complete types. In particular,
15435 /// treat all sizeless types as incomplete.
15436 Normal,
15437
15438 /// Relax the normal rules for complete types so that they include
15439 /// sizeless built-in types.
15440 AcceptSizeless,
15441
15442 // FIXME: Eventually we should flip the default to Normal and opt in
15443 // to AcceptSizeless rather than opt out of it.
15444 Default = AcceptSizeless
15445 };
15446
15447 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15448 const DeclSpec *DS = nullptr);
15449 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15450 const DeclSpec *DS = nullptr);
15451
15452 /// Build a pointer type.
15453 ///
15454 /// \param T The type to which we'll be building a pointer.
15455 ///
15456 /// \param Loc The location of the entity whose type involves this
15457 /// pointer type or, if there is no such entity, the location of the
15458 /// type that will have pointer type.
15459 ///
15460 /// \param Entity The name of the entity that involves the pointer
15461 /// type, if known.
15462 ///
15463 /// \returns A suitable pointer type, if there are no
15464 /// errors. Otherwise, returns a NULL type.
15465 QualType BuildPointerType(QualType T, SourceLocation Loc,
15466 DeclarationName Entity);
15467
15468 /// Build a reference type.
15469 ///
15470 /// \param T The type to which we'll be building a reference.
15471 ///
15472 /// \param Loc The location of the entity whose type involves this
15473 /// reference type or, if there is no such entity, the location of the
15474 /// type that will have reference type.
15475 ///
15476 /// \param Entity The name of the entity that involves the reference
15477 /// type, if known.
15478 ///
15479 /// \returns A suitable reference type, if there are no
15480 /// errors. Otherwise, returns a NULL type.
15481 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15482 DeclarationName Entity);
15483
15484 /// Build an array type.
15485 ///
15486 /// \param T The type of each element in the array.
15487 ///
15488 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15489 ///
15490 /// \param ArraySize Expression describing the size of the array.
15491 ///
15492 /// \param Brackets The range from the opening '[' to the closing ']'.
15493 ///
15494 /// \param Entity The name of the entity that involves the array
15495 /// type, if known.
15496 ///
15497 /// \returns A suitable array type, if there are no errors. Otherwise,
15498 /// returns a NULL type.
15499 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15500 unsigned Quals, SourceRange Brackets,
15501 DeclarationName Entity);
15502
15503 /// Diagnose an array of \p NumElements elements of type \p ElementType
15504 /// that is too large. Returns true if a diagnostic was emitted.
15505 bool checkArrayTooLarge(QualType ElementType, const llvm::APSInt &NumElements,
15506 SourceLocation Loc,
15507 SourceRange Range = SourceRange());
15508 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15509
15510 /// Build an ext-vector type.
15511 ///
15512 /// Run the required checks for the extended vector type.
15513 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15514 SourceLocation AttrLoc);
15515 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15516 SourceLocation AttrLoc);
15517
15518 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15519 Expr *CountExpr,
15520 bool CountInBytes,
15521 bool OrNull);
15522
15523 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15524 /// expression is uninstantiated. If instantiated it will apply the
15525 /// appropriate address space to the type. This function allows dependent
15526 /// template variables to be used in conjunction with the address_space
15527 /// attribute
15528 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15529 SourceLocation AttrLoc);
15530
15531 /// Same as above, but constructs the AddressSpace index if not provided.
15532 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15533 SourceLocation AttrLoc);
15534
15535 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15536
15537 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15538
15539 /// Build a function type.
15540 ///
15541 /// This routine checks the function type according to C++ rules and
15542 /// under the assumption that the result type and parameter types have
15543 /// just been instantiated from a template. It therefore duplicates
15544 /// some of the behavior of GetTypeForDeclarator, but in a much
15545 /// simpler form that is only suitable for this narrow use case.
15546 ///
15547 /// \param T The return type of the function.
15548 ///
15549 /// \param ParamTypes The parameter types of the function. This array
15550 /// will be modified to account for adjustments to the types of the
15551 /// function parameters.
15552 ///
15553 /// \param Loc The location of the entity whose type involves this
15554 /// function type or, if there is no such entity, the location of the
15555 /// type that will have function type.
15556 ///
15557 /// \param Entity The name of the entity that involves the function
15558 /// type, if known.
15559 ///
15560 /// \param EPI Extra information about the function type. Usually this will
15561 /// be taken from an existing function with the same prototype.
15562 ///
15563 /// \returns A suitable function type, if there are no errors. The
15564 /// unqualified type will always be a FunctionProtoType.
15565 /// Otherwise, returns a NULL type.
15566 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15567 SourceLocation Loc, DeclarationName Entity,
15568 const FunctionProtoType::ExtProtoInfo &EPI);
15569
15570 /// Build a member pointer type \c T Class::*.
15571 ///
15572 /// \param T the type to which the member pointer refers.
15573 /// \param Class the class type into which the member pointer points.
15574 /// \param Loc the location where this type begins
15575 /// \param Entity the name of the entity that will have this member pointer
15576 /// type
15577 ///
15578 /// \returns a member pointer type, if successful, or a NULL type if there was
15579 /// an error.
15580 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15581 CXXRecordDecl *Cls, SourceLocation Loc,
15582 DeclarationName Entity);
15583
15584 /// Build a block pointer type.
15585 ///
15586 /// \param T The type to which we'll be building a block pointer.
15587 ///
15588 /// \param Loc The source location, used for diagnostics.
15589 ///
15590 /// \param Entity The name of the entity that involves the block pointer
15591 /// type, if known.
15592 ///
15593 /// \returns A suitable block pointer type, if there are no
15594 /// errors. Otherwise, returns a NULL type.
15595 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15596 DeclarationName Entity);
15597
15598 /// Build a paren type including \p T.
15599 QualType BuildParenType(QualType T);
15600 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15601
15602 /// Build a Read-only Pipe type.
15603 ///
15604 /// \param T The type to which we'll be building a Pipe.
15605 ///
15606 /// \param Loc We do not use it for now.
15607 ///
15608 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15609 /// a NULL type.
15610 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15611
15612 /// Build a Write-only Pipe type.
15613 ///
15614 /// \param T The type to which we'll be building a Pipe.
15615 ///
15616 /// \param Loc We do not use it for now.
15617 ///
15618 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15619 /// a NULL type.
15620 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15621
15622 /// Build a bit-precise integer type.
15623 ///
15624 /// \param IsUnsigned Boolean representing the signedness of the type.
15625 ///
15626 /// \param BitWidth Size of this int type in bits, or an expression
15627 /// representing that.
15628 ///
15629 /// \param Loc Location of the keyword.
15630 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15631
15632 /// GetTypeForDeclarator - Convert the type for the specified
15633 /// declarator to Type instances.
15634 ///
15635 /// The result of this call will never be null, but the associated
15636 /// type may be a null type if there's an unrecoverable error.
15637 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15638 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15639
15640 /// Package the given type and TSI into a ParsedType.
15641 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15642 static QualType GetTypeFromParser(ParsedType Ty,
15643 TypeSourceInfo **TInfo = nullptr);
15644
15645 TypeResult ActOnTypeName(Declarator &D);
15646
15647 // Check whether the size of array element of type \p EltTy is a multiple of
15648 // its alignment and return false if it isn't.
15649 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15650
15651 void
15652 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15653 SourceLocation FallbackLoc,
15654 SourceLocation ConstQualLoc = SourceLocation(),
15655 SourceLocation VolatileQualLoc = SourceLocation(),
15656 SourceLocation RestrictQualLoc = SourceLocation(),
15657 SourceLocation AtomicQualLoc = SourceLocation(),
15658 SourceLocation UnalignedQualLoc = SourceLocation());
15659
15660 /// Retrieve the keyword associated
15661 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15662
15663 /// Adjust the calling convention of a method to be the ABI default if it
15664 /// wasn't specified explicitly. This handles method types formed from
15665 /// function type typedefs and typename template arguments.
15666 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15667 bool IsCtorOrDtor, SourceLocation Loc);
15668
15669 // Check if there is an explicit attribute, but only look through parens.
15670 // The intent is to look for an attribute on the current declarator, but not
15671 // one that came from a typedef.
15672 bool hasExplicitCallingConv(QualType T);
15673
15674 /// Check whether a nullability type specifier can be added to the given
15675 /// type through some means not written in source (e.g. API notes).
15676 ///
15677 /// \param Type The type to which the nullability specifier will be
15678 /// added. On success, this type will be updated appropriately.
15679 ///
15680 /// \param Nullability The nullability specifier to add.
15681 ///
15682 /// \param DiagLoc The location to use for diagnostics.
15683 ///
15684 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15685 /// array type (e.g., because it will decay to a pointer).
15686 ///
15687 /// \param OverrideExisting Whether to override an existing, locally-specified
15688 /// nullability specifier rather than complaining about the conflict.
15689 ///
15690 /// \returns true if nullability cannot be applied, false otherwise.
15691 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15692 NullabilityKind Nullability,
15693 SourceLocation DiagLoc,
15694 bool AllowArrayTypes,
15695 bool OverrideExisting);
15696
15697 /// Check whether the given variable declaration has a size that fits within
15698 /// the address space it is declared in. This issues a diagnostic if not.
15699 ///
15700 /// \param VD The variable declaration to check the size of.
15701 ///
15702 /// \param AS The address space to check the size of \p VD against.
15703 ///
15704 /// \returns true if the variable's size fits within the address space, false
15705 /// otherwise.
15706 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15707
15708 /// Get the type of expression E, triggering instantiation to complete the
15709 /// type if necessary -- that is, if the expression refers to a templated
15710 /// static data member of incomplete array type.
15711 ///
15712 /// May still return an incomplete type if instantiation was not possible or
15713 /// if the type is incomplete for a different reason. Use
15714 /// RequireCompleteExprType instead if a diagnostic is expected for an
15715 /// incomplete expression type.
15716 QualType getCompletedType(Expr *E);
15717
15718 void completeExprArrayBound(Expr *E);
15719
15720 /// Ensure that the type of the given expression is complete.
15721 ///
15722 /// This routine checks whether the expression \p E has a complete type. If
15723 /// the expression refers to an instantiable construct, that instantiation is
15724 /// performed as needed to complete its type. Furthermore
15725 /// Sema::RequireCompleteType is called for the expression's type (or in the
15726 /// case of a reference type, the referred-to type).
15727 ///
15728 /// \param E The expression whose type is required to be complete.
15729 /// \param Kind Selects which completeness rules should be applied.
15730 /// \param Diagnoser The object that will emit a diagnostic if the type is
15731 /// incomplete.
15732 ///
15733 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15734 /// otherwise.
15735 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15736 TypeDiagnoser &Diagnoser);
15737 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15738
15739 template <typename... Ts>
15740 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15741 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15742 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15743 }
15744
15745 // Returns the underlying type of a decltype with the given expression.
15746 QualType getDecltypeForExpr(Expr *E);
15747
15748 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15749 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15750 /// context, such as when building a type for decltype(auto).
15751 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15752
15753 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15754 SourceLocation Loc);
15755 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15756 SourceLocation Loc,
15757 bool FullySubstituted = false,
15758 ArrayRef<QualType> Expansions = {});
15759
15760 using UTTKind = UnaryTransformType::UTTKind;
15761 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15762 SourceLocation Loc);
15763 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15764 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15765 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15766 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15767 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15768 SourceLocation Loc);
15769 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15770 SourceLocation Loc);
15771 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15772 SourceLocation Loc);
15773
15774 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15775 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15776 }
15777
15778 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15779 SourceLocation Loc);
15780 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15781 SourceLocation Loc);
15782
15783 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15784
15785 /// Ensure that the type T is a literal type.
15786 ///
15787 /// This routine checks whether the type @p T is a literal type. If @p T is an
15788 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15789 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15790 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15791 /// it the type @p T), along with notes explaining why the type is not a
15792 /// literal type, and returns true.
15793 ///
15794 /// @param Loc The location in the source that the non-literal type
15795 /// diagnostic should refer to.
15796 ///
15797 /// @param T The type that this routine is examining for literalness.
15798 ///
15799 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15800 ///
15801 /// @returns @c true if @p T is not a literal type and a diagnostic was
15802 /// emitted, @c false otherwise.
15803 bool RequireLiteralType(SourceLocation Loc, QualType T,
15804 TypeDiagnoser &Diagnoser);
15805 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15806
15807 template <typename... Ts>
15808 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15809 const Ts &...Args) {
15810 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15811 return RequireLiteralType(Loc, T, Diagnoser);
15812 }
15813
15814 bool isCompleteType(SourceLocation Loc, QualType T,
15815 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15816 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15817 }
15818
15819 /// Ensure that the type T is a complete type.
15820 ///
15821 /// This routine checks whether the type @p T is complete in any
15822 /// context where a complete type is required. If @p T is a complete
15823 /// type, returns false. If @p T is a class template specialization,
15824 /// this routine then attempts to perform class template
15825 /// instantiation. If instantiation fails, or if @p T is incomplete
15826 /// and cannot be completed, issues the diagnostic @p diag (giving it
15827 /// the type @p T) and returns true.
15828 ///
15829 /// @param Loc The location in the source that the incomplete type
15830 /// diagnostic should refer to.
15831 ///
15832 /// @param T The type that this routine is examining for completeness.
15833 ///
15834 /// @param Kind Selects which completeness rules should be applied.
15835 ///
15836 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15837 /// @c false otherwise.
15838 bool RequireCompleteType(SourceLocation Loc, QualType T,
15839 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15840 bool RequireCompleteType(SourceLocation Loc, QualType T,
15841 CompleteTypeKind Kind, unsigned DiagID);
15842
15843 bool RequireCompleteType(SourceLocation Loc, QualType T,
15844 TypeDiagnoser &Diagnoser) {
15845 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15846 }
15847 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15848 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15849 }
15850
15851 template <typename... Ts>
15852 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15853 const Ts &...Args) {
15854 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15855 return RequireCompleteType(Loc, T, Diagnoser);
15856 }
15857
15858 /// Determine whether a declaration is visible to name lookup.
15859 bool isVisible(const NamedDecl *D) {
15860 return D->isUnconditionallyVisible() ||
15861 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15862 }
15863
15864 /// Determine whether a declaration is reachable.
15865 bool isReachable(const NamedDecl *D) {
15866 // All visible declarations are reachable.
15867 return D->isUnconditionallyVisible() ||
15868 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15869 }
15870
15871 /// Determine whether a declaration is acceptable (visible/reachable).
15872 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15873 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15874 }
15875
15876 /// Determine if \p D and \p Suggested have a structurally compatible
15877 /// layout as described in C11 6.2.7/1.
15878 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15879
15880 /// Determine if \p D has a visible definition. If not, suggest a declaration
15881 /// that should be made visible to expose the definition.
15882 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15883 bool OnlyNeedComplete = false);
15884 bool hasVisibleDefinition(const NamedDecl *D) {
15885 NamedDecl *Hidden;
15886 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15887 }
15888 /// Determine if \p D has a definition which allows we redefine it in current
15889 /// TU. \p Suggested is the definition that should be made visible to expose
15890 /// the definition.
15891 bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc,
15892 NamedDecl **Suggested, bool &Visible);
15893 bool isRedefinitionAllowedFor(const NamedDecl *D, SourceLocation NewLoc,
15894 bool &Visible) {
15895 NamedDecl *Hidden;
15896 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), NewDefinitionLoc: NewLoc, Suggested: &Hidden,
15897 Visible);
15898 }
15899
15900 /// Determine if \p D has a reachable definition. If not, suggest a
15901 /// declaration that should be made reachable to expose the definition.
15902 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15903 bool OnlyNeedComplete = false);
15904 bool hasReachableDefinition(NamedDecl *D) {
15905 NamedDecl *Hidden;
15906 return hasReachableDefinition(D, Suggested: &Hidden);
15907 }
15908
15909 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15910 AcceptableKind Kind,
15911 bool OnlyNeedComplete = false);
15912 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15913 NamedDecl *Hidden;
15914 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15915 }
15916
15917 /// Determine if a definition at \p NewLoc coincides with \p PrevD.
15918 ///
15919 /// Including the same header as a non-modular and a modular allows to process
15920 /// its content twice despite guards against multiple inclusions. To handle
15921 /// such cases this method allows to detect if a currently-parsed decl is at
15922 /// the same location as an existing decl imported from a module.
15923 bool isFromSameSingleIncludeHeader(const Decl *PrevD, SourceLocation NewLoc);
15924
15925 /// Try to parse the conditional expression attached to an effect attribute
15926 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15927 /// optional on error.
15928 std::optional<FunctionEffectMode>
15929 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15930
15931 void ActOnCleanupAttr(Decl *D, const Attr *A);
15932 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15933
15934private:
15935 /// The implementation of RequireCompleteType
15936 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15937 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15938
15939 /// Nullability type specifiers.
15940 IdentifierInfo *Ident__Nonnull = nullptr;
15941 IdentifierInfo *Ident__Nullable = nullptr;
15942 IdentifierInfo *Ident__Nullable_result = nullptr;
15943 IdentifierInfo *Ident__Null_unspecified = nullptr;
15944
15945 ///@}
15946
15947 //
15948 //
15949 // -------------------------------------------------------------------------
15950 //
15951 //
15952
15953 /// \name FixIt Helpers
15954 /// Implementations are in SemaFixItUtils.cpp
15955 ///@{
15956
15957public:
15958 /// Get a string to suggest for zero-initialization of a type.
15959 std::string getFixItZeroInitializerForType(QualType T,
15960 SourceLocation Loc) const;
15961 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15962
15963 ///@}
15964
15965 //
15966 //
15967 // -------------------------------------------------------------------------
15968 //
15969 //
15970
15971 /// \name Function Effects
15972 /// Implementations are in SemaFunctionEffects.cpp
15973 ///@{
15974public:
15975 struct FunctionEffectDiff {
15976 enum class Kind { Added, Removed, ConditionMismatch };
15977
15978 FunctionEffect::Kind EffectKind;
15979 Kind DiffKind;
15980 std::optional<FunctionEffectWithCondition>
15981 Old; // Invalid when 'Kind' is 'Added'.
15982 std::optional<FunctionEffectWithCondition>
15983 New; // Invalid when 'Kind' is 'Removed'.
15984
15985 StringRef effectName() const {
15986 if (Old)
15987 return Old.value().Effect.name();
15988 return New.value().Effect.name();
15989 }
15990
15991 /// Describes the result of effects differing between a base class's virtual
15992 /// method and an overriding method in a subclass.
15993 enum class OverrideResult {
15994 NoAction,
15995 Warn,
15996 Merge // Merge missing effect from base to derived.
15997 };
15998
15999 /// Return true if adding or removing the effect as part of a type
16000 /// conversion should generate a diagnostic.
16001 bool shouldDiagnoseConversion(QualType SrcType,
16002 const FunctionEffectsRef &SrcFX,
16003 QualType DstType,
16004 const FunctionEffectsRef &DstFX) const;
16005
16006 /// Return true if adding or removing the effect in a redeclaration should
16007 /// generate a diagnostic.
16008 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
16009 const FunctionEffectsRef &OldFX,
16010 const FunctionDecl &NewFunction,
16011 const FunctionEffectsRef &NewFX) const;
16012
16013 /// Return true if adding or removing the effect in a C++ virtual method
16014 /// override should generate a diagnostic.
16015 OverrideResult shouldDiagnoseMethodOverride(
16016 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
16017 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
16018 };
16019
16020 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
16021 /// Caller should short-circuit by checking for equality first.
16022 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
16023 const FunctionEffectsRef &New);
16024 };
16025
16026 /// All functions/lambdas/blocks which have bodies and which have a non-empty
16027 /// FunctionEffectsRef to be verified.
16028 SmallVector<const Decl *> DeclsWithEffectsToVerify;
16029
16030 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
16031 /// are all null.
16032 FunctionEffectKindSet AllEffectsToVerify;
16033
16034public:
16035 /// Warn and return true if adding a function effect to a set would create a
16036 /// conflict.
16037 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
16038 const FunctionEffectWithCondition &EC,
16039 SourceLocation NewAttrLoc);
16040
16041 // Report a failure to merge function effects between declarations due to a
16042 // conflict.
16043 void
16044 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
16045 SourceLocation NewLoc,
16046 SourceLocation OldLoc);
16047
16048 /// Inline checks from the start of maybeAddDeclWithEffects, to
16049 /// minimize performance impact on code not using effects.
16050 template <class FuncOrBlockDecl>
16051 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
16052 if (Context.hasAnyFunctionEffects())
16053 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
16054 maybeAddDeclWithEffects(D, FX);
16055 }
16056
16057 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
16058 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
16059
16060 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
16061 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
16062
16063 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
16064
16065 ///@}
16066
16067 //
16068 //
16069 // -------------------------------------------------------------------------
16070 //
16071 //
16072
16073 /// \name Expansion Statements
16074 /// Implementations are in SemaExpand.cpp
16075 ///@{
16076public:
16077 CXXExpansionStmtDecl *ActOnCXXExpansionStmtDecl(unsigned TemplateDepth,
16078 SourceLocation TemplateKWLoc);
16079
16080 CXXExpansionStmtDecl *
16081 BuildCXXExpansionStmtDecl(DeclContext *Ctx, SourceLocation TemplateKWLoc,
16082 NonTypeTemplateParmDecl *NTTP);
16083
16084 ExprResult ActOnCXXExpansionInitList(MultiExprArg SubExprs,
16085 SourceLocation LBraceLoc,
16086 SourceLocation RBraceLoc);
16087
16088 StmtResult ActOnCXXExpansionStmtPattern(
16089 CXXExpansionStmtDecl *ESD, Stmt *Init, Stmt *ExpansionVarStmt,
16090 Expr *ExpansionInitializer, SourceLocation LParenLoc,
16091 SourceLocation ColonLoc, SourceLocation RParenLoc,
16092 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps);
16093
16094 StmtResult FinishCXXExpansionStmt(Stmt *Expansion, Stmt *Body);
16095
16096 StmtResult BuildCXXEnumeratingExpansionStmtPattern(Decl *ESD, Stmt *Init,
16097 Stmt *ExpansionVar,
16098 SourceLocation LParenLoc,
16099 SourceLocation ColonLoc,
16100 SourceLocation RParenLoc);
16101
16102 StmtResult BuildNonEnumeratingCXXExpansionStmtPattern(
16103 CXXExpansionStmtDecl *ESD, Stmt *Init, DeclStmt *ExpansionVarStmt,
16104 Expr *ExpansionInitializer, SourceLocation LParenLoc,
16105 SourceLocation ColonLoc, SourceLocation RParenLoc,
16106 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
16107
16108 ExprResult BuildCXXExpansionSelectExpr(InitListExpr *Range, Expr *Idx);
16109
16110 std::optional<uint64_t>
16111 ComputeExpansionSize(CXXExpansionStmtPattern *Expansion);
16112 ///@}
16113};
16114
16115DeductionFailureInfo
16116MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
16117 sema::TemplateDeductionInfo &Info);
16118
16119/// Contains a late templated function.
16120/// Will be parsed at the end of the translation unit, used by Sema & Parser.
16121struct LateParsedTemplate {
16122 CachedTokens Toks;
16123 /// The template function declaration to be late parsed.
16124 Decl *D;
16125 /// Floating-point options in the point of definition.
16126 FPOptions FPO;
16127};
16128
16129template <>
16130void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
16131 PragmaMsStackAction Action,
16132 llvm::StringRef StackSlotLabel,
16133 AlignPackInfo Value);
16134
16135} // end namespace clang
16136
16137#endif
16138