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/Builtins.h"
39#include "clang/Basic/CapturedStmt.h"
40#include "clang/Basic/Cuda.h"
41#include "clang/Basic/DiagnosticSema.h"
42#include "clang/Basic/ExceptionSpecificationType.h"
43#include "clang/Basic/ExpressionTraits.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/Basic/TypeTraits.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/SemaRISCV.h"
71#include "clang/Sema/TypoCorrection.h"
72#include "clang/Sema/Weak.h"
73#include "llvm/ADT/APInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/BitmaskEnum.h"
76#include "llvm/ADT/DenseMap.h"
77#include "llvm/ADT/DenseSet.h"
78#include "llvm/ADT/FloatingPointMode.h"
79#include "llvm/ADT/FoldingSet.h"
80#include "llvm/ADT/MapVector.h"
81#include "llvm/ADT/PointerIntPair.h"
82#include "llvm/ADT/PointerUnion.h"
83#include "llvm/ADT/STLExtras.h"
84#include "llvm/ADT/STLForwardCompat.h"
85#include "llvm/ADT/STLFunctionalExtras.h"
86#include "llvm/ADT/SetVector.h"
87#include "llvm/ADT/SmallBitVector.h"
88#include "llvm/ADT/SmallPtrSet.h"
89#include "llvm/ADT/SmallSet.h"
90#include "llvm/ADT/SmallVector.h"
91#include "llvm/ADT/StringExtras.h"
92#include "llvm/ADT/StringMap.h"
93#include "llvm/ADT/TinyPtrVector.h"
94#include "llvm/Support/Allocator.h"
95#include "llvm/Support/Compiler.h"
96#include "llvm/Support/Error.h"
97#include "llvm/Support/ErrorHandling.h"
98#include <cassert>
99#include <climits>
100#include <cstddef>
101#include <cstdint>
102#include <deque>
103#include <functional>
104#include <iterator>
105#include <memory>
106#include <optional>
107#include <string>
108#include <tuple>
109#include <type_traits>
110#include <utility>
111#include <vector>
112
113namespace llvm {
114struct InlineAsmIdentifierInfo;
115} // namespace llvm
116
117namespace clang {
118class ADLResult;
119class APValue;
120struct ASTConstraintSatisfaction;
121class ASTConsumer;
122class ASTContext;
123class ASTDeclReader;
124class ASTMutationListener;
125class ASTReader;
126class ASTWriter;
127class CXXBasePath;
128class CXXBasePaths;
129class CXXFieldCollector;
130class CodeCompleteConsumer;
131enum class ComparisonCategoryType : unsigned char;
132class ConstraintSatisfaction;
133class DarwinSDKInfo;
134class DeclGroupRef;
135class DeducedTemplateArgument;
136struct DeductionFailureInfo;
137class DependentDiagnostic;
138class Designation;
139class IdentifierInfo;
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;
160class SemaAMDGPU;
161class SemaARM;
162class SemaAVR;
163class SemaBPF;
164class SemaCodeCompletion;
165class SemaCUDA;
166class SemaDirectX;
167class SemaHLSL;
168class SemaHexagon;
169class SemaLoongArch;
170class SemaM68k;
171class SemaMIPS;
172class SemaMSP430;
173class SemaNVPTX;
174class SemaObjC;
175class SemaOpenACC;
176class SemaOpenCL;
177class SemaOpenMP;
178class SemaPPC;
179class SemaPseudoObject;
180class SemaRISCV;
181class SemaSPIRV;
182class SemaSYCL;
183class SemaSwift;
184class SemaSystemZ;
185class SemaWasm;
186class SemaX86;
187class StandardConversionSequence;
188class TemplateArgument;
189class TemplateArgumentLoc;
190class TemplateInstantiationCallback;
191class TemplatePartialOrderingContext;
192class TemplateSpecCandidateSet;
193class Token;
194class TypeConstraint;
195class TypoCorrectionConsumer;
196class UnresolvedSetImpl;
197class UnresolvedSetIterator;
198class VisibleDeclConsumer;
199
200namespace sema {
201class BlockScopeInfo;
202class Capture;
203class CapturedRegionScopeInfo;
204class CapturingScopeInfo;
205class CompoundScopeInfo;
206class DelayedDiagnostic;
207class DelayedDiagnosticPool;
208class FunctionScopeInfo;
209class LambdaScopeInfo;
210class SemaPPCallbacks;
211class TemplateDeductionInfo;
212} // namespace sema
213
214// AssignmentAction - This is used by all the assignment diagnostic functions
215// to represent what is actually causing the operation
216enum class AssignmentAction {
217 Assigning,
218 Passing,
219 Returning,
220 Converting,
221 Initializing,
222 Sending,
223 Casting,
224 Passing_CFAudited
225};
226
227namespace threadSafety {
228class BeforeSet;
229void threadSafetyCleanup(BeforeSet *Cache);
230} // namespace threadSafety
231
232// FIXME: No way to easily map from TemplateTypeParmTypes to
233// TemplateTypeParmDecls, so we have this horrible PointerUnion.
234typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *,
235 const TemplateSpecializationType *,
236 const SubstBuiltinTemplatePackType *>,
237 SourceLocation>
238 UnexpandedParameterPack;
239
240/// Describes whether we've seen any nullability information for the given
241/// file.
242struct FileNullability {
243 /// The first pointer declarator (of any pointer kind) in the file that does
244 /// not have a corresponding nullability annotation.
245 SourceLocation PointerLoc;
246
247 /// The end location for the first pointer declarator in the file. Used for
248 /// placing fix-its.
249 SourceLocation PointerEndLoc;
250
251 /// Which kind of pointer declarator we saw.
252 uint8_t PointerKind;
253
254 /// Whether we saw any type nullability annotations in the given file.
255 bool SawTypeNullability = false;
256};
257
258/// A mapping from file IDs to a record of whether we've seen nullability
259/// information in that file.
260class FileNullabilityMap {
261 /// A mapping from file IDs to the nullability information for each file ID.
262 llvm::DenseMap<FileID, FileNullability> Map;
263
264 /// A single-element cache based on the file ID.
265 struct {
266 FileID File;
267 FileNullability Nullability;
268 } Cache;
269
270public:
271 FileNullability &operator[](FileID file) {
272 // Check the single-element cache.
273 if (file == Cache.File)
274 return Cache.Nullability;
275
276 // It's not in the single-element cache; flush the cache if we have one.
277 if (!Cache.File.isInvalid()) {
278 Map[Cache.File] = Cache.Nullability;
279 }
280
281 // Pull this entry into the cache.
282 Cache.File = file;
283 Cache.Nullability = Map[file];
284 return Cache.Nullability;
285 }
286};
287
288/// Tracks expected type during expression parsing, for use in code completion.
289/// The type is tied to a particular token, all functions that update or consume
290/// the type take a start location of the token they are looking at as a
291/// parameter. This avoids updating the type on hot paths in the parser.
292class PreferredTypeBuilder {
293public:
294 PreferredTypeBuilder(ASTContext *Ctx, bool Enabled)
295 : Ctx(Ctx), Enabled(Enabled) {}
296
297 void enterCondition(Sema &S, SourceLocation Tok);
298 void enterReturn(Sema &S, SourceLocation Tok);
299 void enterVariableInit(SourceLocation Tok, Decl *D);
300 /// Handles e.g. BaseType{ .D = Tok...
301 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
302 const Designation &D);
303 /// Computing a type for the function argument may require running
304 /// overloading, so we postpone its computation until it is actually needed.
305 ///
306 /// Clients should be very careful when using this function, as it stores a
307 /// function_ref, clients should make sure all calls to get() with the same
308 /// location happen while function_ref is alive.
309 ///
310 /// The callback should also emit signature help as a side-effect, but only
311 /// if the completion point has been reached.
312 void enterFunctionArgument(SourceLocation Tok,
313 llvm::function_ref<QualType()> ComputeType);
314
315 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
316 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
317 SourceLocation OpLoc);
318 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
319 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
320 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
321 /// Handles all type casts, including C-style cast, C++ casts, etc.
322 void enterTypeCast(SourceLocation Tok, QualType CastType);
323
324 /// Get the expected type associated with this location, if any.
325 ///
326 /// If the location is a function argument, determining the expected type
327 /// involves considering all function overloads and the arguments so far.
328 /// In this case, signature help for these function overloads will be reported
329 /// as a side-effect (only if the completion point has been reached).
330 QualType get(SourceLocation Tok) const {
331 if (!Enabled || Tok != ExpectedLoc)
332 return QualType();
333 if (!Type.isNull())
334 return Type;
335 if (ComputeType)
336 return ComputeType();
337 return QualType();
338 }
339
340private:
341 ASTContext *Ctx;
342 bool Enabled;
343 /// Start position of a token for which we store expected type.
344 SourceLocation ExpectedLoc;
345 /// Expected type for a token starting at ExpectedLoc.
346 QualType Type;
347 /// A function to compute expected type at ExpectedLoc. It is only considered
348 /// if Type is null.
349 llvm::function_ref<QualType()> ComputeType;
350};
351
352struct SkipBodyInfo {
353 SkipBodyInfo() = default;
354 bool ShouldSkip = false;
355 bool CheckSameAsPrevious = false;
356 NamedDecl *Previous = nullptr;
357 NamedDecl *New = nullptr;
358};
359
360/// Describes the result of template argument deduction.
361///
362/// The TemplateDeductionResult enumeration describes the result of
363/// template argument deduction, as returned from
364/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
365/// structure provides additional information about the results of
366/// template argument deduction, e.g., the deduced template argument
367/// list (if successful) or the specific template parameters or
368/// deduced arguments that were involved in the failure.
369enum class TemplateDeductionResult {
370 /// Template argument deduction was successful.
371 Success = 0,
372 /// The declaration was invalid; do nothing.
373 Invalid,
374 /// Template argument deduction exceeded the maximum template
375 /// instantiation depth (which has already been diagnosed).
376 InstantiationDepth,
377 /// Template argument deduction did not deduce a value
378 /// for every template parameter.
379 Incomplete,
380 /// Template argument deduction did not deduce a value for every
381 /// expansion of an expanded template parameter pack.
382 IncompletePack,
383 /// Template argument deduction produced inconsistent
384 /// deduced values for the given template parameter.
385 Inconsistent,
386 /// Template argument deduction failed due to inconsistent
387 /// cv-qualifiers on a template parameter type that would
388 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
389 /// but were given a non-const "X".
390 Underqualified,
391 /// Substitution of the deduced template argument values
392 /// resulted in an error.
393 SubstitutionFailure,
394 /// After substituting deduced template arguments, a dependent
395 /// parameter type did not match the corresponding argument.
396 DeducedMismatch,
397 /// After substituting deduced template arguments, an element of
398 /// a dependent parameter type did not match the corresponding element
399 /// of the corresponding argument (when deducing from an initializer list).
400 DeducedMismatchNested,
401 /// A non-depnedent component of the parameter did not match the
402 /// corresponding component of the argument.
403 NonDeducedMismatch,
404 /// When performing template argument deduction for a function
405 /// template, there were too many call arguments.
406 TooManyArguments,
407 /// When performing template argument deduction for a function
408 /// template, there were too few call arguments.
409 TooFewArguments,
410 /// The explicitly-specified template arguments were not valid
411 /// template arguments for the given template.
412 InvalidExplicitArguments,
413 /// Checking non-dependent argument conversions failed.
414 NonDependentConversionFailure,
415 /// The deduced arguments did not satisfy the constraints associated
416 /// with the template.
417 ConstraintsNotSatisfied,
418 /// Deduction failed; that's all we know.
419 MiscellaneousDeductionFailure,
420 /// CUDA Target attributes do not match.
421 CUDATargetMismatch,
422 /// Some error which was already diagnosed.
423 AlreadyDiagnosed
424};
425
426/// Kinds of C++ special members.
427enum class CXXSpecialMemberKind {
428 DefaultConstructor,
429 CopyConstructor,
430 MoveConstructor,
431 CopyAssignment,
432 MoveAssignment,
433 Destructor,
434 Invalid
435};
436
437/// The kind of conversion being performed.
438enum class CheckedConversionKind {
439 /// An implicit conversion.
440 Implicit,
441 /// A C-style cast.
442 CStyleCast,
443 /// A functional-style cast.
444 FunctionalCast,
445 /// A cast other than a C-style cast.
446 OtherCast,
447 /// A conversion for an operand of a builtin overloaded operator.
448 ForBuiltinOverloadedOp
449};
450
451enum class TagUseKind {
452 Reference, // Reference to a tag: 'struct foo *X;'
453 Declaration, // Fwd decl of a tag: 'struct foo;'
454 Definition, // Definition of a tag: 'struct foo { int X; } Y;'
455 Friend // Friend declaration: 'friend struct foo;'
456};
457
458/// Used with attributes/effects with a boolean condition, e.g. `nonblocking`.
459enum class FunctionEffectMode : uint8_t {
460 None, // effect is not present.
461 False, // effect(false).
462 True, // effect(true).
463 Dependent // effect(expr) where expr is dependent.
464};
465
466/// pragma clang section kind
467enum class PragmaClangSectionKind {
468 Invalid = 0,
469 BSS = 1,
470 Data = 2,
471 Rodata = 3,
472 Text = 4,
473 Relro = 5
474};
475
476enum class PragmaClangSectionAction { Set = 0, Clear = 1 };
477
478enum class PragmaOptionsAlignKind {
479 Native, // #pragma options align=native
480 Natural, // #pragma options align=natural
481 Packed, // #pragma options align=packed
482 Power, // #pragma options align=power
483 Mac68k, // #pragma options align=mac68k
484 Reset // #pragma options align=reset
485};
486
487enum class TUFragmentKind {
488 /// The global module fragment, between 'module;' and a module-declaration.
489 Global,
490 /// A normal translation unit fragment. For a non-module unit, this is the
491 /// entire translation unit. Otherwise, it runs from the module-declaration
492 /// to the private-module-fragment (if any) or the end of the TU (if not).
493 Normal,
494 /// The private module fragment, between 'module :private;' and the end of
495 /// the translation unit.
496 Private
497};
498
499enum class FormatStringType {
500 Scanf,
501 Printf,
502 NSString,
503 Strftime,
504 Strfmon,
505 Kprintf,
506 FreeBSDKPrintf,
507 OSTrace,
508 OSLog,
509 Unknown
510};
511
512// Used for emitting the right warning by DefaultVariadicArgumentPromotion
513enum class VariadicCallType {
514 Function,
515 Block,
516 Method,
517 Constructor,
518 DoesNotApply
519};
520
521enum class BuiltinCountedByRefKind {
522 Assignment,
523 Initializer,
524 FunctionArg,
525 ReturnArg,
526 ArraySubscript,
527 BinaryExpr,
528};
529
530// Contexts where using non-trivial C union types can be disallowed. This is
531// passed to err_non_trivial_c_union_in_invalid_context.
532enum class NonTrivialCUnionContext {
533 // Function parameter.
534 FunctionParam,
535 // Function return.
536 FunctionReturn,
537 // Default-initialized object.
538 DefaultInitializedObject,
539 // Variable with automatic storage duration.
540 AutoVar,
541 // Initializer expression that might copy from another object.
542 CopyInit,
543 // Assignment.
544 Assignment,
545 // Compound literal.
546 CompoundLiteral,
547 // Block capture.
548 BlockCapture,
549 // lvalue-to-rvalue conversion of volatile type.
550 LValueToRValueVolatile,
551};
552
553/// Describes the result of the name lookup and resolution performed
554/// by \c Sema::ClassifyName().
555enum class NameClassificationKind {
556 /// This name is not a type or template in this context, but might be
557 /// something else.
558 Unknown,
559 /// Classification failed; an error has been produced.
560 Error,
561 /// The name has been typo-corrected to a keyword.
562 Keyword,
563 /// The name was classified as a type.
564 Type,
565 /// The name was classified as a specific non-type, non-template
566 /// declaration. ActOnNameClassifiedAsNonType should be called to
567 /// convert the declaration to an expression.
568 NonType,
569 /// The name was classified as an ADL-only function name.
570 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
571 /// result to an expression.
572 UndeclaredNonType,
573 /// The name denotes a member of a dependent type that could not be
574 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
575 /// convert the result to an expression.
576 DependentNonType,
577 /// The name was classified as an overload set, and an expression
578 /// representing that overload set has been formed.
579 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
580 /// expression referencing the overload set.
581 OverloadSet,
582 /// The name was classified as a template whose specializations are types.
583 TypeTemplate,
584 /// The name was classified as a variable template name.
585 VarTemplate,
586 /// The name was classified as a function template name.
587 FunctionTemplate,
588 /// The name was classified as an ADL-only function template name.
589 UndeclaredTemplate,
590 /// The name was classified as a concept name.
591 Concept,
592};
593
594enum class PointerAuthDiscArgKind {
595 // Address discrimination argument of __ptrauth.
596 Addr,
597
598 // Extra discriminator argument of __ptrauth.
599 Extra,
600};
601
602/// Common ways to introduce type names without a tag for use in diagnostics.
603/// Keep in sync with err_tag_reference_non_tag.
604enum class NonTagKind {
605 NonStruct,
606 NonClass,
607 NonUnion,
608 NonEnum,
609 Typedef,
610 TypeAlias,
611 Template,
612 TypeAliasTemplate,
613 TemplateTemplateArgument,
614};
615
616enum class OffsetOfKind {
617 // Not parsing a type within __builtin_offsetof.
618 Outside,
619 // Parsing a type within __builtin_offsetof.
620 Builtin,
621 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
622 // To improve our diagnostic message.
623 Macro,
624};
625
626/// Describes the kind of merge to perform for availability
627/// attributes (including "deprecated", "unavailable", and "availability").
628enum class AvailabilityMergeKind {
629 /// Don't merge availability attributes at all.
630 None,
631 /// Merge availability attributes for a redeclaration, which requires
632 /// an exact match.
633 Redeclaration,
634 /// Merge availability attributes for an override, which requires
635 /// an exact match or a weakening of constraints.
636 Override,
637 /// Merge availability attributes for an implementation of
638 /// a protocol requirement.
639 ProtocolImplementation,
640 /// Merge availability attributes for an implementation of
641 /// an optional protocol requirement.
642 OptionalProtocolImplementation
643};
644
645enum class TrivialABIHandling {
646 /// The triviality of a method unaffected by "trivial_abi".
647 IgnoreTrivialABI,
648
649 /// The triviality of a method affected by "trivial_abi".
650 ConsiderTrivialABI
651};
652
653enum class TryCaptureKind { Implicit, ExplicitByVal, ExplicitByRef };
654
655enum class AllowFoldKind {
656 No,
657 Allow,
658};
659
660/// Context in which we're performing a usual arithmetic conversion.
661enum class ArithConvKind {
662 /// An arithmetic operation.
663 Arithmetic,
664 /// A bitwise operation.
665 BitwiseOp,
666 /// A comparison.
667 Comparison,
668 /// A conditional (?:) operator.
669 Conditional,
670 /// A compound assignment expression.
671 CompAssign,
672};
673
674// Used for determining in which context a type is allowed to be passed to a
675// vararg function.
676enum class VarArgKind {
677 Valid,
678 ValidInCXX11,
679 Undefined,
680 MSVCUndefined,
681 Invalid
682};
683
684/// AssignConvertType - All of the 'assignment' semantic checks return this
685/// enum to indicate whether the assignment was allowed. These checks are
686/// done for simple assignments, as well as initialization, return from
687/// function, argument passing, etc. The query is phrased in terms of a
688/// source and destination type.
689enum class AssignConvertType {
690 /// Compatible - the types are compatible according to the standard.
691 Compatible,
692
693 /// CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because
694 /// a void * can implicitly convert to another pointer type, which we
695 /// differentiate for better diagnostic behavior.
696 CompatibleVoidPtrToNonVoidPtr,
697
698 /// PointerToInt - The assignment converts a pointer to an int, which we
699 /// accept as an extension.
700 PointerToInt,
701
702 /// IntToPointer - The assignment converts an int to a pointer, which we
703 /// accept as an extension.
704 IntToPointer,
705
706 /// FunctionVoidPointer - The assignment is between a function pointer and
707 /// void*, which the standard doesn't allow, but we accept as an extension.
708 FunctionVoidPointer,
709
710 /// IncompatiblePointer - The assignment is between two pointers types that
711 /// are not compatible, but we accept them as an extension.
712 IncompatiblePointer,
713
714 /// IncompatibleFunctionPointer - The assignment is between two function
715 /// pointers types that are not compatible, but we accept them as an
716 /// extension.
717 IncompatibleFunctionPointer,
718
719 /// IncompatibleFunctionPointerStrict - The assignment is between two
720 /// function pointer types that are not identical, but are compatible,
721 /// unless compiled with -fsanitize=cfi, in which case the type mismatch
722 /// may trip an indirect call runtime check.
723 IncompatibleFunctionPointerStrict,
724
725 /// IncompatiblePointerSign - The assignment is between two pointers types
726 /// which point to integers which have a different sign, but are otherwise
727 /// identical. This is a subset of the above, but broken out because it's by
728 /// far the most common case of incompatible pointers.
729 IncompatiblePointerSign,
730
731 /// CompatiblePointerDiscardsQualifiers - The assignment discards
732 /// c/v/r qualifiers, which we accept as an extension.
733 CompatiblePointerDiscardsQualifiers,
734
735 /// IncompatiblePointerDiscardsQualifiers - The assignment
736 /// discards qualifiers that we don't permit to be discarded,
737 /// like address spaces.
738 IncompatiblePointerDiscardsQualifiers,
739
740 /// IncompatiblePointerDiscardsOverflowBehavior - The assignment
741 /// discards overflow behavior annotations between otherwise compatible
742 /// pointer types.
743 IncompatiblePointerDiscardsOverflowBehavior,
744
745 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
746 /// changes address spaces in nested pointer types which is not allowed.
747 /// For instance, converting __private int ** to __generic int ** is
748 /// illegal even though __private could be converted to __generic.
749 IncompatibleNestedPointerAddressSpaceMismatch,
750
751 /// IncompatibleNestedPointerQualifiers - The assignment is between two
752 /// nested pointer types, and the qualifiers other than the first two
753 /// levels differ e.g. char ** -> const char **, but we accept them as an
754 /// extension.
755 IncompatibleNestedPointerQualifiers,
756
757 /// IncompatibleVectors - The assignment is between two vector types that
758 /// have the same size, which we accept as an extension.
759 IncompatibleVectors,
760
761 /// IntToBlockPointer - The assignment converts an int to a block
762 /// pointer. We disallow this.
763 IntToBlockPointer,
764
765 /// IncompatibleBlockPointer - The assignment is between two block
766 /// pointers types that are not compatible.
767 IncompatibleBlockPointer,
768
769 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
770 /// id type and something else (that is incompatible with it). For example,
771 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
772 IncompatibleObjCQualifiedId,
773
774 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
775 /// object with __weak qualifier.
776 IncompatibleObjCWeakRef,
777
778 /// IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType
779 /// kinds, e.g., from __ob_trap to __ob_wrap or vice versa.
780 IncompatibleOBTKinds,
781
782 /// CompatibleOBTDiscards - Assignment discards overflow behavior
783 CompatibleOBTDiscards,
784
785 /// Incompatible - We reject this conversion outright, it is invalid to
786 /// represent it in the AST.
787 Incompatible
788};
789
790/// The scope in which to find allocation functions.
791enum class AllocationFunctionScope {
792 /// Only look for allocation functions in the global scope.
793 Global,
794 /// Only look for allocation functions in the scope of the
795 /// allocated class.
796 Class,
797 /// Look for allocation functions in both the global scope
798 /// and in the scope of the allocated class.
799 Both
800};
801
802/// Describes the result of an "if-exists" condition check.
803enum class IfExistsResult {
804 /// The symbol exists.
805 Exists,
806
807 /// The symbol does not exist.
808 DoesNotExist,
809
810 /// The name is a dependent name, so the results will differ
811 /// from one instantiation to the next.
812 Dependent,
813
814 /// An error occurred.
815 Error
816};
817
818enum class CorrectTypoKind {
819 NonError, // CorrectTypo used in a non error recovery situation.
820 ErrorRecovery // CorrectTypo used in normal error recovery.
821};
822
823enum class OverloadKind {
824 /// This is a legitimate overload: the existing declarations are
825 /// functions or function templates with different signatures.
826 Overload,
827
828 /// This is not an overload because the signature exactly matches
829 /// an existing declaration.
830 Match,
831
832 /// This is not an overload because the lookup results contain a
833 /// non-function.
834 NonFunction
835};
836
837/// Contexts in which a converted constant expression is required.
838enum class CCEKind {
839 CaseValue, ///< Expression in a case label.
840 Enumerator, ///< Enumerator value with fixed underlying type.
841 TemplateArg, ///< Value of a non-type template parameter.
842 TempArgStrict, ///< As above, but applies strict template checking
843 ///< rules.
844 ArrayBound, ///< Array bound in array declarator or new-expression.
845 ExplicitBool, ///< Condition in an explicit(bool) specifier.
846 Noexcept, ///< Condition in a noexcept(bool) specifier.
847 StaticAssertMessageSize, ///< Call to size() in a static assert
848 ///< message.
849 StaticAssertMessageData, ///< Call to data() in a static assert
850 ///< message.
851};
852
853/// Enums for the diagnostics of target, target_version and target_clones.
854namespace DiagAttrParams {
855enum DiagType { Unsupported, Duplicate, Unknown };
856enum Specifier { None, CPU, Tune };
857enum AttrName { Target, TargetClones, TargetVersion };
858} // end namespace DiagAttrParams
859
860void inferNoReturnAttr(Sema &S, Decl *D);
861
862#ifdef __GNUC__
863#pragma GCC diagnostic push
864#pragma GCC diagnostic ignored "-Wattributes"
865#endif
866/// Sema - This implements semantic analysis and AST building for C.
867/// \nosubgrouping
868class Sema final : public SemaBase {
869#ifdef __GNUC__
870#pragma GCC diagnostic pop
871#endif
872 // Table of Contents
873 // -----------------
874 // 1. Semantic Analysis (Sema.cpp)
875 // 2. API Notes (SemaAPINotes.cpp)
876 // 3. C++ Access Control (SemaAccess.cpp)
877 // 4. Attributes (SemaAttr.cpp)
878 // 5. Availability Attribute Handling (SemaAvailability.cpp)
879 // 6. Bounds Safety (SemaBoundsSafety.cpp)
880 // 7. Casts (SemaCast.cpp)
881 // 8. Extra Semantic Checking (SemaChecking.cpp)
882 // 9. C++ Coroutines (SemaCoroutine.cpp)
883 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
884 // 11. Declarations (SemaDecl.cpp)
885 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
886 // 13. C++ Declarations (SemaDeclCXX.cpp)
887 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
888 // 15. Expressions (SemaExpr.cpp)
889 // 16. C++ Expressions (SemaExprCXX.cpp)
890 // 17. Member Access Expressions (SemaExprMember.cpp)
891 // 18. Initializers (SemaInit.cpp)
892 // 19. C++ Lambda Expressions (SemaLambda.cpp)
893 // 20. Name Lookup (SemaLookup.cpp)
894 // 21. Modules (SemaModule.cpp)
895 // 22. C++ Overloading (SemaOverload.cpp)
896 // 23. Statements (SemaStmt.cpp)
897 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
898 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
899 // 26. C++ Templates (SemaTemplate.cpp)
900 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
901 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
902 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
903 // 30. C++ Template Declaration Instantiation
904 // (SemaTemplateInstantiateDecl.cpp)
905 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
906 // 32. Constraints and Concepts (SemaConcept.cpp)
907 // 33. Types (SemaType.cpp)
908 // 34. FixIt Helpers (SemaFixItUtils.cpp)
909 // 35. Function Effects (SemaFunctionEffects.cpp)
910
911 /// \name Semantic Analysis
912 /// Implementations are in Sema.cpp
913 ///@{
914
915public:
916 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
917 TranslationUnitKind TUKind = TU_Complete,
918 CodeCompleteConsumer *CompletionConsumer = nullptr);
919 ~Sema();
920
921 /// Perform initialization that occurs after the parser has been
922 /// initialized but before it parses anything.
923 void Initialize();
924
925 /// This virtual key function only exists to limit the emission of debug info
926 /// describing the Sema class. GCC and Clang only emit debug info for a class
927 /// with a vtable when the vtable is emitted. Sema is final and not
928 /// polymorphic, but the debug info size savings are so significant that it is
929 /// worth adding a vtable just to take advantage of this optimization.
930 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
931
932 const LangOptions &getLangOpts() const { return LangOpts; }
933 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
934 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
935
936 DiagnosticsEngine &getDiagnostics() const { return Diags; }
937 SourceManager &getSourceManager() const { return SourceMgr; }
938 Preprocessor &getPreprocessor() const { return PP; }
939 ASTContext &getASTContext() const { return Context; }
940 ASTConsumer &getASTConsumer() const { return Consumer; }
941 ASTMutationListener *getASTMutationListener() const;
942 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
943
944 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
945 StringRef Platform);
946 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
947
948 /// Registers an external source. If an external source already exists,
949 /// creates a multiplex external source and appends to it.
950 ///
951 ///\param[in] E - A non-null external sema source.
952 ///
953 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
954
955 /// Print out statistics about the semantic analysis.
956 void PrintStats() const;
957
958 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
959 /// guaranteed). Produces a warning if we're low on stack space and allocates
960 /// more in that case. Use this in code that may recurse deeply (for example,
961 /// in template instantiation) to avoid stack overflow.
962 void runWithSufficientStackSpace(SourceLocation Loc,
963 llvm::function_ref<void()> Fn);
964
965 /// Returns default addr space for method qualifiers.
966 LangAS getDefaultCXXMethodAddrSpace() const;
967
968 /// Load weak undeclared identifiers from the external source.
969 void LoadExternalWeakUndeclaredIdentifiers();
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 /// Obtain a sorted list of functions that are undefined but ODR-used.
977 void getUndefinedButUsed(
978 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
979
980 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
981 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
982 /// Retrieves list of suspicious delete-expressions that will be checked at
983 /// the end of translation unit.
984 const llvm::MapVector<FieldDecl *, DeleteLocs> &
985 getMismatchingDeleteExpressions() const;
986
987 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
988 /// This is closely coupled to the SemaDiagnosticBuilder class and
989 /// should not be used elsewhere.
990 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
991
992 void addImplicitTypedef(StringRef Name, QualType T);
993
994 /// Whether uncompilable error has occurred. This includes error happens
995 /// in deferred diagnostics.
996 bool hasUncompilableErrorOccurred() const;
997
998 /// Looks through the macro-expansion chain for the given
999 /// location, looking for a macro expansion with the given name.
1000 /// If one is found, returns true and sets the location to that
1001 /// expansion loc.
1002 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1003
1004 /// Calls \c Lexer::getLocForEndOfToken()
1005 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1006
1007 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1008 /// locations of both ends of the token can be resolved it return that
1009 /// range; Otherwise it returns an invalid SourceRange.
1010 SourceRange getRangeForNextToken(
1011 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1012 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1013
1014 /// Retrieve the module loader associated with the preprocessor.
1015 ModuleLoader &getModuleLoader() const;
1016
1017 /// Invent a new identifier for parameters of abbreviated templates.
1018 IdentifierInfo *
1019 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1020 unsigned Index);
1021
1022 void emitAndClearUnusedLocalTypedefWarnings();
1023
1024 // Emit all deferred diagnostics.
1025 void emitDeferredDiags();
1026
1027 /// This is called before the very first declaration in the translation unit
1028 /// is parsed. Note that the ASTContext may have already injected some
1029 /// declarations.
1030 void ActOnStartOfTranslationUnit();
1031 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1032 /// translation unit when EOF is reached and all but the top-level scope is
1033 /// popped.
1034 void ActOnEndOfTranslationUnit();
1035 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1036
1037 /// Determines the active Scope associated with the given declaration
1038 /// context.
1039 ///
1040 /// This routine maps a declaration context to the active Scope object that
1041 /// represents that declaration context in the parser. It is typically used
1042 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1043 /// declarations) that injects a name for name-lookup purposes and, therefore,
1044 /// must update the Scope.
1045 ///
1046 /// \returns The scope corresponding to the given declaraion context, or NULL
1047 /// if no such scope is open.
1048 Scope *getScopeForContext(DeclContext *Ctx);
1049
1050 void PushFunctionScope();
1051 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1052 sema::LambdaScopeInfo *PushLambdaScope();
1053
1054 /// This is used to inform Sema what the current TemplateParameterDepth
1055 /// is during Parsing. Currently it is used to pass on the depth
1056 /// when parsing generic lambda 'auto' parameters.
1057 void RecordParsingTemplateParameterDepth(unsigned Depth);
1058
1059 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1060 RecordDecl *RD, CapturedRegionKind K,
1061 unsigned OpenMPCaptureLevel = 0);
1062
1063 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1064 /// time after they've been popped.
1065 class PoppedFunctionScopeDeleter {
1066 Sema *Self;
1067
1068 public:
1069 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1070 void operator()(sema::FunctionScopeInfo *Scope) const;
1071 };
1072
1073 using PoppedFunctionScopePtr =
1074 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1075
1076 /// Pop a function (or block or lambda or captured region) scope from the
1077 /// stack.
1078 ///
1079 /// \param WP The warning policy to use for CFG-based warnings, or null if
1080 /// such warnings should not be produced.
1081 /// \param D The declaration corresponding to this function scope, if
1082 /// producing CFG-based warnings.
1083 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1084 PoppedFunctionScopePtr
1085 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1086 Decl *D = nullptr, QualType BlockType = QualType());
1087
1088 sema::FunctionScopeInfo *getEnclosingFunction() const;
1089
1090 void setFunctionHasBranchIntoScope();
1091 void setFunctionHasBranchProtectedScope();
1092 void setFunctionHasIndirectGoto();
1093 void setFunctionHasMustTail();
1094
1095 void PushCompoundScope(bool IsStmtExpr);
1096 void PopCompoundScope();
1097
1098 /// Determine whether any errors occurred within this function/method/
1099 /// block.
1100 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1101
1102 /// Retrieve the current block, if any.
1103 sema::BlockScopeInfo *getCurBlock();
1104
1105 /// Get the innermost lambda or block enclosing the current location, if any.
1106 /// This looks through intervening non-lambda, non-block scopes such as local
1107 /// functions.
1108 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1109
1110 /// Retrieve the current lambda scope info, if any.
1111 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1112 /// lambda scope info ignoring all inner capturing scopes that are not
1113 /// lambda scopes.
1114 sema::LambdaScopeInfo *
1115 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1116
1117 /// Retrieve the current generic lambda info, if any.
1118 sema::LambdaScopeInfo *getCurGenericLambda();
1119
1120 /// Retrieve the current captured region, if any.
1121 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1122
1123 void ActOnComment(SourceRange Comment);
1124
1125 /// Retrieve the parser's current scope.
1126 ///
1127 /// This routine must only be used when it is certain that semantic analysis
1128 /// and the parser are in precisely the same context, which is not the case
1129 /// when, e.g., we are performing any kind of template instantiation.
1130 /// Therefore, the only safe places to use this scope are in the parser
1131 /// itself and in routines directly invoked from the parser and *never* from
1132 /// template substitution or instantiation.
1133 Scope *getCurScope() const { return CurScope; }
1134
1135 IdentifierInfo *getSuperIdentifier() const;
1136
1137 DeclContext *getCurLexicalContext() const {
1138 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1139 }
1140
1141 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1142 const FunctionDecl *FD = nullptr);
1143 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1144 const PartialDiagnostic &PD,
1145 const FunctionDecl *FD = nullptr) {
1146 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1147 }
1148
1149 /// Check if the type is allowed to be used for the current target.
1150 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1151 ValueDecl *D = nullptr);
1152
1153 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1154 /// cast. If there is already an implicit cast, merge into the existing one.
1155 /// If isLvalue, the result of the cast is an lvalue.
1156 ExprResult ImpCastExprToType(
1157 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1158 const CXXCastPath *BasePath = nullptr,
1159 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1160
1161 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1162 /// to the conversion from scalar type ScalarTy to the Boolean type.
1163 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1164
1165 /// If \p AllowLambda is true, treat lambda as function.
1166 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1167
1168 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1169 /// current context is not inside a function. If \p AllowLambda is true,
1170 /// this can return the call operator of an enclosing lambda, otherwise
1171 /// lambdas are skipped when looking for an enclosing function.
1172 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1173
1174 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1175 /// the method decl for the method being parsed. If we're currently
1176 /// in a 'block', this returns the containing context.
1177 ObjCMethodDecl *getCurMethodDecl();
1178
1179 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1180 /// or C function we're in, otherwise return null. If we're currently
1181 /// in a 'block', this returns the containing context.
1182 NamedDecl *getCurFunctionOrMethodDecl() const;
1183
1184 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1185 /// _Nonnull one.
1186 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1187 SourceLocation Loc);
1188
1189 /// Warn when implicitly casting 0 to nullptr.
1190 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1191
1192 /// Warn when implicitly changing function effects.
1193 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1194 SourceLocation Loc);
1195
1196 /// makeUnavailableInSystemHeader - There is an error in the current
1197 /// context. If we're still in a system header, and we can plausibly
1198 /// make the relevant declaration unavailable instead of erroring, do
1199 /// so and return true.
1200 bool makeUnavailableInSystemHeader(SourceLocation loc,
1201 UnavailableAttr::ImplicitReason reason);
1202
1203 /// Retrieve a suitable printing policy for diagnostics.
1204 PrintingPolicy getPrintingPolicy() const {
1205 return getPrintingPolicy(Ctx: Context, PP);
1206 }
1207
1208 /// Retrieve a suitable printing policy for diagnostics.
1209 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1210 const Preprocessor &PP);
1211
1212 /// Scope actions.
1213 void ActOnTranslationUnitScope(Scope *S);
1214
1215 /// Determine whether \param D is function like (function or function
1216 /// template) for parsing.
1217 bool isDeclaratorFunctionLike(Declarator &D);
1218
1219 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1220 /// because that allows us not to duplicate the constants in clang code,
1221 /// which we must to since we can't directly use the llvm constants.
1222 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1223 ///
1224 /// This is the greatest alignment value supported by load, store, and alloca
1225 /// instructions, and global values.
1226 static const unsigned MaxAlignmentExponent = 32;
1227 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1228
1229 /// Flag indicating whether or not to collect detailed statistics.
1230 bool CollectStats;
1231
1232 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1233
1234 /// Stack containing information about each of the nested
1235 /// function, block, and method scopes that are currently active.
1236 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1237
1238 /// The index of the first FunctionScope that corresponds to the current
1239 /// context.
1240 unsigned FunctionScopesStart = 0;
1241
1242 /// Track the number of currently active capturing scopes.
1243 unsigned CapturingFunctionScopes = 0;
1244
1245 llvm::BumpPtrAllocator BumpAlloc;
1246
1247 /// The kind of translation unit we are processing.
1248 ///
1249 /// When we're processing a complete translation unit, Sema will perform
1250 /// end-of-translation-unit semantic tasks (such as creating
1251 /// initializers for tentative definitions in C) once parsing has
1252 /// completed. Modules and precompiled headers perform different kinds of
1253 /// checks.
1254 const TranslationUnitKind TUKind;
1255
1256 /// Translation Unit Scope - useful to Objective-C actions that need
1257 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1258 /// For example, user-defined classes, built-in "id" type, etc.
1259 Scope *TUScope;
1260
1261 void incrementMSManglingNumber() const {
1262 return CurScope->incrementMSManglingNumber();
1263 }
1264
1265 /// Try to recover by turning the given expression into a
1266 /// call. Returns true if recovery was attempted or an error was
1267 /// emitted; this may also leave the ExprResult invalid.
1268 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1269 bool ForceComplain = false,
1270 bool (*IsPlausibleResult)(QualType) = nullptr);
1271
1272 // Adds implicit lifetime bound attribute for implicit this to its
1273 // TypeSourceInfo.
1274 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1275
1276 /// Figure out if an expression could be turned into a call.
1277 ///
1278 /// Use this when trying to recover from an error where the programmer may
1279 /// have written just the name of a function instead of actually calling it.
1280 ///
1281 /// \param E - The expression to examine.
1282 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1283 /// with no arguments, this parameter is set to the type returned by such a
1284 /// call; otherwise, it is set to an empty QualType.
1285 /// \param OverloadSet - If the expression is an overloaded function
1286 /// name, this parameter is populated with the decls of the various
1287 /// overloads.
1288 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1289 UnresolvedSetImpl &NonTemplateOverloads);
1290
1291 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1292 typedef OpaquePtr<TemplateName> TemplateTy;
1293 typedef OpaquePtr<QualType> TypeTy;
1294
1295 OpenCLOptions OpenCLFeatures;
1296 FPOptions CurFPFeatures;
1297
1298 const LangOptions &LangOpts;
1299 Preprocessor &PP;
1300 ASTContext &Context;
1301 ASTConsumer &Consumer;
1302 DiagnosticsEngine &Diags;
1303 SourceManager &SourceMgr;
1304 api_notes::APINotesManager APINotes;
1305
1306 /// A RAII object to enter scope of a compound statement.
1307 class CompoundScopeRAII {
1308 public:
1309 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1310 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1311 }
1312
1313 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1314 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1315 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1316
1317 private:
1318 Sema &S;
1319 };
1320
1321 /// An RAII helper that pops function a function scope on exit.
1322 struct FunctionScopeRAII {
1323 Sema &S;
1324 bool Active;
1325 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1326 ~FunctionScopeRAII() {
1327 if (Active)
1328 S.PopFunctionScopeInfo();
1329 }
1330 void disable() { Active = false; }
1331 };
1332
1333 sema::FunctionScopeInfo *getCurFunction() const {
1334 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1335 }
1336
1337 /// Worker object for performing CFG-based warnings.
1338 sema::AnalysisBasedWarnings AnalysisWarnings;
1339 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1340
1341 /// Callback to the parser to parse templated functions when needed.
1342 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1343 LateTemplateParserCB *LateTemplateParser;
1344 void *OpaqueParser;
1345
1346 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1347 LateTemplateParser = LTP;
1348 OpaqueParser = P;
1349 }
1350
1351 /// Callback to the parser to parse a type expressed as a string.
1352 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1353 ParseTypeFromStringCallback;
1354
1355 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1356 /// This is used as part of a hack to omit that class from ADL results.
1357 DeclarationName VAListTagName;
1358
1359 /// Is the last error level diagnostic immediate. This is used to determined
1360 /// whether the next info diagnostic should be immediate.
1361 bool IsLastErrorImmediate = true;
1362
1363 /// Track if we're currently analyzing overflow behavior types in assignment
1364 /// context.
1365 bool InOverflowBehaviorAssignmentContext = false;
1366
1367 class DelayedDiagnostics;
1368
1369 class DelayedDiagnosticsState {
1370 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1371 friend class Sema::DelayedDiagnostics;
1372 };
1373 typedef DelayedDiagnosticsState ParsingDeclState;
1374 typedef DelayedDiagnosticsState ProcessingContextState;
1375
1376 /// A class which encapsulates the logic for delaying diagnostics
1377 /// during parsing and other processing.
1378 class DelayedDiagnostics {
1379 /// The current pool of diagnostics into which delayed
1380 /// diagnostics should go.
1381 sema::DelayedDiagnosticPool *CurPool = nullptr;
1382
1383 public:
1384 DelayedDiagnostics() = default;
1385
1386 /// Adds a delayed diagnostic.
1387 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1388
1389 /// Determines whether diagnostics should be delayed.
1390 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1391
1392 /// Returns the current delayed-diagnostics pool.
1393 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1394
1395 /// Enter a new scope. Access and deprecation diagnostics will be
1396 /// collected in this pool.
1397 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1398 DelayedDiagnosticsState state;
1399 state.SavedPool = CurPool;
1400 CurPool = &pool;
1401 return state;
1402 }
1403
1404 /// Leave a delayed-diagnostic state that was previously pushed.
1405 /// Do not emit any of the diagnostics. This is performed as part
1406 /// of the bookkeeping of popping a pool "properly".
1407 void popWithoutEmitting(DelayedDiagnosticsState state) {
1408 CurPool = state.SavedPool;
1409 }
1410
1411 /// Enter a new scope where access and deprecation diagnostics are
1412 /// not delayed.
1413 DelayedDiagnosticsState pushUndelayed() {
1414 DelayedDiagnosticsState state;
1415 state.SavedPool = CurPool;
1416 CurPool = nullptr;
1417 return state;
1418 }
1419
1420 /// Undo a previous pushUndelayed().
1421 void popUndelayed(DelayedDiagnosticsState state) {
1422 assert(CurPool == nullptr);
1423 CurPool = state.SavedPool;
1424 }
1425 } DelayedDiagnostics;
1426
1427 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1428 return DelayedDiagnostics.push(pool);
1429 }
1430
1431 /// Diagnostics that are emitted only if we discover that the given function
1432 /// must be codegen'ed. Because handling these correctly adds overhead to
1433 /// compilation, this is currently only used for offload languages like CUDA,
1434 /// OpenMP, and SYCL.
1435 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1436
1437 /// CurContext - This is the current declaration context of parsing.
1438 DeclContext *CurContext;
1439
1440 SemaAMDGPU &AMDGPU() {
1441 assert(AMDGPUPtr);
1442 return *AMDGPUPtr;
1443 }
1444
1445 SemaARM &ARM() {
1446 assert(ARMPtr);
1447 return *ARMPtr;
1448 }
1449
1450 SemaAVR &AVR() {
1451 assert(AVRPtr);
1452 return *AVRPtr;
1453 }
1454
1455 SemaBPF &BPF() {
1456 assert(BPFPtr);
1457 return *BPFPtr;
1458 }
1459
1460 SemaCodeCompletion &CodeCompletion() {
1461 assert(CodeCompletionPtr);
1462 return *CodeCompletionPtr;
1463 }
1464
1465 SemaCUDA &CUDA() {
1466 assert(CUDAPtr);
1467 return *CUDAPtr;
1468 }
1469
1470 SemaDirectX &DirectX() {
1471 assert(DirectXPtr);
1472 return *DirectXPtr;
1473 }
1474
1475 SemaHLSL &HLSL() {
1476 assert(HLSLPtr);
1477 return *HLSLPtr;
1478 }
1479
1480 SemaHexagon &Hexagon() {
1481 assert(HexagonPtr);
1482 return *HexagonPtr;
1483 }
1484
1485 SemaLoongArch &LoongArch() {
1486 assert(LoongArchPtr);
1487 return *LoongArchPtr;
1488 }
1489
1490 SemaM68k &M68k() {
1491 assert(M68kPtr);
1492 return *M68kPtr;
1493 }
1494
1495 SemaMIPS &MIPS() {
1496 assert(MIPSPtr);
1497 return *MIPSPtr;
1498 }
1499
1500 SemaMSP430 &MSP430() {
1501 assert(MSP430Ptr);
1502 return *MSP430Ptr;
1503 }
1504
1505 SemaNVPTX &NVPTX() {
1506 assert(NVPTXPtr);
1507 return *NVPTXPtr;
1508 }
1509
1510 SemaObjC &ObjC() {
1511 assert(ObjCPtr);
1512 return *ObjCPtr;
1513 }
1514
1515 SemaOpenACC &OpenACC() {
1516 assert(OpenACCPtr);
1517 return *OpenACCPtr;
1518 }
1519
1520 SemaOpenCL &OpenCL() {
1521 assert(OpenCLPtr);
1522 return *OpenCLPtr;
1523 }
1524
1525 SemaOpenMP &OpenMP() {
1526 assert(OpenMPPtr && "SemaOpenMP is dead");
1527 return *OpenMPPtr;
1528 }
1529
1530 SemaPPC &PPC() {
1531 assert(PPCPtr);
1532 return *PPCPtr;
1533 }
1534
1535 SemaPseudoObject &PseudoObject() {
1536 assert(PseudoObjectPtr);
1537 return *PseudoObjectPtr;
1538 }
1539
1540 SemaRISCV &RISCV() {
1541 assert(RISCVPtr);
1542 return *RISCVPtr;
1543 }
1544
1545 SemaSPIRV &SPIRV() {
1546 assert(SPIRVPtr);
1547 return *SPIRVPtr;
1548 }
1549
1550 SemaSYCL &SYCL() {
1551 assert(SYCLPtr);
1552 return *SYCLPtr;
1553 }
1554
1555 SemaSwift &Swift() {
1556 assert(SwiftPtr);
1557 return *SwiftPtr;
1558 }
1559
1560 SemaSystemZ &SystemZ() {
1561 assert(SystemZPtr);
1562 return *SystemZPtr;
1563 }
1564
1565 SemaWasm &Wasm() {
1566 assert(WasmPtr);
1567 return *WasmPtr;
1568 }
1569
1570 SemaX86 &X86() {
1571 assert(X86Ptr);
1572 return *X86Ptr;
1573 }
1574
1575 /// Source of additional semantic information.
1576 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1577
1578protected:
1579 friend class Parser;
1580 friend class InitializationSequence;
1581 friend class ASTReader;
1582 friend class ASTDeclReader;
1583 friend class ASTWriter;
1584
1585private:
1586 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1587 bool WarnedDarwinSDKInfoMissing = false;
1588
1589 StackExhaustionHandler StackHandler;
1590
1591 Sema(const Sema &) = delete;
1592 void operator=(const Sema &) = delete;
1593
1594 /// The handler for the FileChanged preprocessor events.
1595 ///
1596 /// Used for diagnostics that implement custom semantic analysis for #include
1597 /// directives, like -Wpragma-pack.
1598 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1599
1600 /// The parser's current scope.
1601 ///
1602 /// The parser maintains this state here.
1603 Scope *CurScope;
1604
1605 mutable IdentifierInfo *Ident_super;
1606
1607 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1608 std::unique_ptr<SemaARM> ARMPtr;
1609 std::unique_ptr<SemaAVR> AVRPtr;
1610 std::unique_ptr<SemaBPF> BPFPtr;
1611 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1612 std::unique_ptr<SemaCUDA> CUDAPtr;
1613 std::unique_ptr<SemaDirectX> DirectXPtr;
1614 std::unique_ptr<SemaHLSL> HLSLPtr;
1615 std::unique_ptr<SemaHexagon> HexagonPtr;
1616 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1617 std::unique_ptr<SemaM68k> M68kPtr;
1618 std::unique_ptr<SemaMIPS> MIPSPtr;
1619 std::unique_ptr<SemaMSP430> MSP430Ptr;
1620 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1621 std::unique_ptr<SemaObjC> ObjCPtr;
1622 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1623 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1624 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1625 std::unique_ptr<SemaPPC> PPCPtr;
1626 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1627 std::unique_ptr<SemaRISCV> RISCVPtr;
1628 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1629 std::unique_ptr<SemaSYCL> SYCLPtr;
1630 std::unique_ptr<SemaSwift> SwiftPtr;
1631 std::unique_ptr<SemaSystemZ> SystemZPtr;
1632 std::unique_ptr<SemaWasm> WasmPtr;
1633 std::unique_ptr<SemaX86> X86Ptr;
1634
1635 ///@}
1636
1637 //
1638 //
1639 // -------------------------------------------------------------------------
1640 //
1641 //
1642
1643 /// \name API Notes
1644 /// Implementations are in SemaAPINotes.cpp
1645 ///@{
1646
1647public:
1648 /// Map any API notes provided for this declaration to attributes on the
1649 /// declaration.
1650 ///
1651 /// Triggered by declaration-attribute processing.
1652 void ProcessAPINotes(Decl *D);
1653 /// Apply the 'Nullability:' annotation to the specified declaration
1654 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1655 /// Apply the 'Type:' annotation to the specified declaration
1656 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1657
1658 /// Whether APINotes should be gathered for all applicable Swift language
1659 /// versions, without being applied. Leaving clients of the current module
1660 /// to select and apply the correct version.
1661 bool captureSwiftVersionIndependentAPINotes() {
1662 return APINotes.captureVersionIndependentSwift();
1663 }
1664 ///@}
1665
1666 //
1667 //
1668 // -------------------------------------------------------------------------
1669 //
1670 //
1671
1672 /// \name C++ Access Control
1673 /// Implementations are in SemaAccess.cpp
1674 ///@{
1675
1676public:
1677 enum AccessResult {
1678 AR_accessible,
1679 AR_inaccessible,
1680 AR_dependent,
1681 AR_delayed
1682 };
1683
1684 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1685 /// Returns true on error (when the previous member decl access specifier
1686 /// is different from the new member decl access specifier).
1687 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1688 NamedDecl *PrevMemberDecl,
1689 AccessSpecifier LexicalAS);
1690
1691 /// Perform access-control checking on a previously-unresolved member
1692 /// access which has now been resolved to a member.
1693 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1694 DeclAccessPair FoundDecl);
1695 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1696 DeclAccessPair FoundDecl);
1697
1698 /// Checks access to an overloaded operator new or delete.
1699 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1700 SourceRange PlacementRange,
1701 CXXRecordDecl *NamingClass,
1702 DeclAccessPair FoundDecl,
1703 bool Diagnose = true);
1704
1705 /// Checks access to a constructor.
1706 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1707 DeclAccessPair FoundDecl,
1708 const InitializedEntity &Entity,
1709 bool IsCopyBindingRefToTemp = false);
1710
1711 /// Checks access to a constructor.
1712 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1713 DeclAccessPair FoundDecl,
1714 const InitializedEntity &Entity,
1715 const PartialDiagnostic &PDiag);
1716 AccessResult CheckDestructorAccess(SourceLocation Loc,
1717 CXXDestructorDecl *Dtor,
1718 const PartialDiagnostic &PDiag,
1719 QualType objectType = QualType());
1720
1721 /// Checks access to the target of a friend declaration.
1722 AccessResult CheckFriendAccess(NamedDecl *D);
1723
1724 /// Checks access to a member.
1725 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1726 CXXRecordDecl *NamingClass,
1727 DeclAccessPair Found);
1728
1729 /// Checks implicit access to a member in a structured binding.
1730 AccessResult
1731 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1732 CXXRecordDecl *DecomposedClass,
1733 DeclAccessPair Field);
1734 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1735 const SourceRange &,
1736 DeclAccessPair FoundDecl);
1737
1738 /// Checks access to an overloaded member operator, including
1739 /// conversion operators.
1740 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1741 Expr *ArgExpr,
1742 DeclAccessPair FoundDecl);
1743 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1744 ArrayRef<Expr *> ArgExprs,
1745 DeclAccessPair FoundDecl);
1746 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1747 DeclAccessPair FoundDecl);
1748
1749 /// Checks access for a hierarchy conversion.
1750 ///
1751 /// \param ForceCheck true if this check should be performed even if access
1752 /// control is disabled; some things rely on this for semantics
1753 /// \param ForceUnprivileged true if this check should proceed as if the
1754 /// context had no special privileges
1755 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1756 QualType Derived, const CXXBasePath &Path,
1757 unsigned DiagID, bool ForceCheck = false,
1758 bool ForceUnprivileged = false);
1759
1760 AccessResult CheckBaseClassAccess(
1761 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1762 const CXXBasePath &Path, unsigned DiagID,
1763 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1764 bool ForceCheck = false, bool ForceUnprivileged = false);
1765
1766 /// Checks access to all the declarations in the given result set.
1767 void CheckLookupAccess(const LookupResult &R);
1768
1769 /// Checks access to Target from the given class. The check will take access
1770 /// specifiers into account, but no member access expressions and such.
1771 ///
1772 /// \param Target the declaration to check if it can be accessed
1773 /// \param NamingClass the class in which the lookup was started.
1774 /// \param BaseType type of the left side of member access expression.
1775 /// \p BaseType and \p NamingClass are used for C++ access control.
1776 /// Depending on the lookup case, they should be set to the following:
1777 /// - lhs.target (member access without a qualifier):
1778 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1779 /// - lhs.X::target (member access with a qualifier):
1780 /// BaseType is the type of 'lhs', NamingClass is 'X'
1781 /// - X::target (qualified lookup without member access):
1782 /// BaseType is null, NamingClass is 'X'.
1783 /// - target (unqualified lookup).
1784 /// BaseType is null, NamingClass is the parent class of 'target'.
1785 /// \return true if the Target is accessible from the Class, false otherwise.
1786 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1787 QualType BaseType);
1788
1789 /// Is the given member accessible for the purposes of deciding whether to
1790 /// define a special member function as deleted?
1791 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1792 DeclAccessPair Found, QualType ObjectType,
1793 SourceLocation Loc,
1794 const PartialDiagnostic &Diag);
1795 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1796 DeclAccessPair Found,
1797 QualType ObjectType) {
1798 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1799 Loc: SourceLocation(), Diag: PDiag());
1800 }
1801
1802 void HandleDependentAccessCheck(
1803 const DependentDiagnostic &DD,
1804 const MultiLevelTemplateArgumentList &TemplateArgs);
1805 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1806
1807 ///@}
1808
1809 //
1810 //
1811 // -------------------------------------------------------------------------
1812 //
1813 //
1814
1815 /// \name Attributes
1816 /// Implementations are in SemaAttr.cpp
1817 ///@{
1818
1819public:
1820 /// Controls member pointer representation format under the MS ABI.
1821 LangOptions::PragmaMSPointersToMembersKind
1822 MSPointerToMemberRepresentationMethod;
1823
1824 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1825
1826 /// Source location for newly created implicit MSInheritanceAttrs
1827 SourceLocation ImplicitMSInheritanceAttrLoc;
1828
1829 struct PragmaClangSection {
1830 std::string SectionName;
1831 bool Valid = false;
1832 SourceLocation PragmaLocation;
1833 };
1834
1835 PragmaClangSection PragmaClangBSSSection;
1836 PragmaClangSection PragmaClangDataSection;
1837 PragmaClangSection PragmaClangRodataSection;
1838 PragmaClangSection PragmaClangRelroSection;
1839 PragmaClangSection PragmaClangTextSection;
1840
1841 enum PragmaMsStackAction {
1842 PSK_Reset = 0x0, // #pragma ()
1843 PSK_Set = 0x1, // #pragma (value)
1844 PSK_Push = 0x2, // #pragma (push[, id])
1845 PSK_Pop = 0x4, // #pragma (pop[, id])
1846 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1847 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1848 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1849 };
1850
1851 struct PragmaPackInfo {
1852 PragmaMsStackAction Action;
1853 StringRef SlotLabel;
1854 Token Alignment;
1855 };
1856
1857 // #pragma pack and align.
1858 class AlignPackInfo {
1859 public:
1860 // `Native` represents default align mode, which may vary based on the
1861 // platform.
1862 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1863
1864 // #pragma pack info constructor
1865 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1866 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1867 assert(Num == PackNumber && "The pack number has been truncated.");
1868 }
1869
1870 // #pragma align info constructor
1871 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1872 : PackAttr(false), AlignMode(M),
1873 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1874
1875 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1876
1877 AlignPackInfo() : AlignPackInfo(Native, false) {}
1878
1879 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1880 // integer encoding for it. This should only be passed to
1881 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1882 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1883 std::uint32_t Encoding{};
1884 if (Info.IsXLStack())
1885 Encoding |= IsXLMask;
1886
1887 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1888
1889 if (Info.IsPackAttr())
1890 Encoding |= PackAttrMask;
1891
1892 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1893
1894 return Encoding;
1895 }
1896
1897 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1898 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1899 AlignPackInfo::Mode M =
1900 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1901 int PackNumber = (Encoding & PackNumMask) >> 4;
1902
1903 if (Encoding & PackAttrMask)
1904 return AlignPackInfo(M, PackNumber, IsXL);
1905
1906 return AlignPackInfo(M, IsXL);
1907 }
1908
1909 bool IsPackAttr() const { return PackAttr; }
1910
1911 bool IsAlignAttr() const { return !PackAttr; }
1912
1913 Mode getAlignMode() const { return AlignMode; }
1914
1915 unsigned getPackNumber() const { return PackNumber; }
1916
1917 bool IsPackSet() const {
1918 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1919 // attriute on a decl.
1920 return PackNumber != UninitPackVal && PackNumber != 0;
1921 }
1922
1923 bool IsXLStack() const { return XLStack; }
1924
1925 bool operator==(const AlignPackInfo &Info) const {
1926 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1927 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1928 args: Info.XLStack);
1929 }
1930
1931 bool operator!=(const AlignPackInfo &Info) const {
1932 return !(*this == Info);
1933 }
1934
1935 private:
1936 /// \brief True if this is a pragma pack attribute,
1937 /// not a pragma align attribute.
1938 bool PackAttr;
1939
1940 /// \brief The alignment mode that is in effect.
1941 Mode AlignMode;
1942
1943 /// \brief The pack number of the stack.
1944 unsigned char PackNumber;
1945
1946 /// \brief True if it is a XL #pragma align/pack stack.
1947 bool XLStack;
1948
1949 /// \brief Uninitialized pack value.
1950 static constexpr unsigned char UninitPackVal = -1;
1951
1952 // Masks to encode and decode an AlignPackInfo.
1953 static constexpr uint32_t IsXLMask{0x0000'0001};
1954 static constexpr uint32_t AlignModeMask{0x0000'0006};
1955 static constexpr uint32_t PackAttrMask{0x00000'0008};
1956 static constexpr uint32_t PackNumMask{0x0000'01F0};
1957 };
1958
1959 template <typename ValueType> struct PragmaStack {
1960 struct Slot {
1961 llvm::StringRef StackSlotLabel;
1962 ValueType Value;
1963 SourceLocation PragmaLocation;
1964 SourceLocation PragmaPushLocation;
1965 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1966 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
1967 : StackSlotLabel(StackSlotLabel), Value(Value),
1968 PragmaLocation(PragmaLocation),
1969 PragmaPushLocation(PragmaPushLocation) {}
1970 };
1971
1972 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1973 llvm::StringRef StackSlotLabel, ValueType Value) {
1974 if (Action == PSK_Reset) {
1975 CurrentValue = DefaultValue;
1976 CurrentPragmaLocation = PragmaLocation;
1977 return;
1978 }
1979 if (Action & PSK_Push)
1980 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1981 PragmaLocation);
1982 else if (Action & PSK_Pop) {
1983 if (!StackSlotLabel.empty()) {
1984 // If we've got a label, try to find it and jump there.
1985 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1986 return x.StackSlotLabel == StackSlotLabel;
1987 });
1988 // If we found the label so pop from there.
1989 if (I != Stack.rend()) {
1990 CurrentValue = I->Value;
1991 CurrentPragmaLocation = I->PragmaLocation;
1992 Stack.erase(std::prev(I.base()), Stack.end());
1993 }
1994 } else if (!Stack.empty()) {
1995 // We do not have a label, just pop the last entry.
1996 CurrentValue = Stack.back().Value;
1997 CurrentPragmaLocation = Stack.back().PragmaLocation;
1998 Stack.pop_back();
1999 }
2000 }
2001 if (Action & PSK_Set) {
2002 CurrentValue = Value;
2003 CurrentPragmaLocation = PragmaLocation;
2004 }
2005 }
2006
2007 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2008 // method body to restore the stacks on exit, so it works like this:
2009 //
2010 // struct S {
2011 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2012 // void Method {}
2013 // #pragma <name>(pop, InternalPragmaSlot)
2014 // };
2015 //
2016 // It works even with #pragma vtordisp, although MSVC doesn't support
2017 // #pragma vtordisp(push [, id], n)
2018 // syntax.
2019 //
2020 // Push / pop a named sentinel slot.
2021 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2022 assert((Action == PSK_Push || Action == PSK_Pop) &&
2023 "Can only push / pop #pragma stack sentinels!");
2024 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2025 }
2026
2027 // Constructors.
2028 explicit PragmaStack(const ValueType &Default)
2029 : DefaultValue(Default), CurrentValue(Default) {}
2030
2031 bool hasValue() const { return CurrentValue != DefaultValue; }
2032
2033 SmallVector<Slot, 2> Stack;
2034 ValueType DefaultValue; // Value used for PSK_Reset action.
2035 ValueType CurrentValue;
2036 SourceLocation CurrentPragmaLocation;
2037 };
2038 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2039 // we shouldn't do so if they're in a module).
2040
2041 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2042 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2043 ///
2044 /// 0: Suppress all vtordisps
2045 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2046 /// structors
2047 /// 2: Always insert vtordisps to support RTTI on partially constructed
2048 /// objects
2049 PragmaStack<MSVtorDispMode> VtorDispStack;
2050 PragmaStack<AlignPackInfo> AlignPackStack;
2051 // The current #pragma align/pack values and locations at each #include.
2052 struct AlignPackIncludeState {
2053 AlignPackInfo CurrentValue;
2054 SourceLocation CurrentPragmaLocation;
2055 bool HasNonDefaultValue, ShouldWarnOnInclude;
2056 };
2057 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2058 // Segment #pragmas.
2059 PragmaStack<StringLiteral *> DataSegStack;
2060 PragmaStack<StringLiteral *> BSSSegStack;
2061 PragmaStack<StringLiteral *> ConstSegStack;
2062 PragmaStack<StringLiteral *> CodeSegStack;
2063
2064 // #pragma strict_gs_check.
2065 PragmaStack<bool> StrictGuardStackCheckStack;
2066
2067 // This stack tracks the current state of Sema.CurFPFeatures.
2068 PragmaStack<FPOptionsOverride> FpPragmaStack;
2069 FPOptionsOverride CurFPFeatureOverrides() {
2070 FPOptionsOverride result;
2071 if (!FpPragmaStack.hasValue()) {
2072 result = FPOptionsOverride();
2073 } else {
2074 result = FpPragmaStack.CurrentValue;
2075 }
2076 return result;
2077 }
2078
2079 enum PragmaSectionKind {
2080 PSK_DataSeg,
2081 PSK_BSSSeg,
2082 PSK_ConstSeg,
2083 PSK_CodeSeg,
2084 };
2085
2086 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2087 // Actions should be performed only if we enter / exit a C++ method body.
2088 class PragmaStackSentinelRAII {
2089 public:
2090 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2091 ~PragmaStackSentinelRAII();
2092 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2093 PragmaStackSentinelRAII &
2094 operator=(const PragmaStackSentinelRAII &) = delete;
2095
2096 private:
2097 Sema &S;
2098 StringRef SlotLabel;
2099 bool ShouldAct;
2100 };
2101
2102 /// Last section used with #pragma init_seg.
2103 StringLiteral *CurInitSeg;
2104 SourceLocation CurInitSegLoc;
2105
2106 /// Sections used with #pragma alloc_text.
2107 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2108
2109 /// VisContext - Manages the stack for \#pragma GCC visibility.
2110 void *VisContext; // Really a "PragmaVisStack*"
2111
2112 /// This an attribute introduced by \#pragma clang attribute.
2113 struct PragmaAttributeEntry {
2114 SourceLocation Loc;
2115 ParsedAttr *Attribute;
2116 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2117 bool IsUsed;
2118 };
2119
2120 /// A push'd group of PragmaAttributeEntries.
2121 struct PragmaAttributeGroup {
2122 /// The location of the push attribute.
2123 SourceLocation Loc;
2124 /// The namespace of this push group.
2125 const IdentifierInfo *Namespace;
2126 SmallVector<PragmaAttributeEntry, 2> Entries;
2127 };
2128
2129 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2130
2131 /// The declaration that is currently receiving an attribute from the
2132 /// #pragma attribute stack.
2133 const Decl *PragmaAttributeCurrentTargetDecl;
2134
2135 /// This represents the last location of a "#pragma clang optimize off"
2136 /// directive if such a directive has not been closed by an "on" yet. If
2137 /// optimizations are currently "on", this is set to an invalid location.
2138 SourceLocation OptimizeOffPragmaLocation;
2139
2140 /// Get the location for the currently active "\#pragma clang optimize
2141 /// off". If this location is invalid, then the state of the pragma is "on".
2142 SourceLocation getOptimizeOffPragmaLocation() const {
2143 return OptimizeOffPragmaLocation;
2144 }
2145
2146 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2147 /// whether the optimizations in the list passed to the pragma should be
2148 /// turned off or on. This boolean is true by default because command line
2149 /// options are honored when `#pragma optimize("", on)`.
2150 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2151 bool MSPragmaOptimizeIsOn = true;
2152
2153 /// Set of no-builtin functions listed by \#pragma function.
2154 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2155
2156 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2157 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2158 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2159
2160 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2161 void AddMsStructLayoutForRecord(RecordDecl *RD);
2162
2163 /// Add gsl::Pointer attribute to std::container::iterator
2164 /// \param ND The declaration that introduces the name
2165 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2166 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2167
2168 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2169 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2170
2171 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2172 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2173
2174 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2175 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2176
2177 /// Add [[gsl::Pointer]] attributes for std:: types.
2178 void inferGslPointerAttribute(TypedefNameDecl *TD);
2179
2180 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2181 StringRef ParamName);
2182 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2183 // can be the name of a function parameter, we need to parse the function
2184 // declaration and rest of the parameters before processesing 'X'. Therefore
2185 // do this lazily instead of processing while parsing the annotation itself.
2186 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2187
2188 /// Add _Nullable attributes for std:: types.
2189 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2190
2191 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2192 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2193 PragmaClangSectionAction Action,
2194 PragmaClangSectionKind SecKind,
2195 StringRef SecName);
2196
2197 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2198 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2199 SourceLocation PragmaLoc);
2200
2201 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2202 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2203 StringRef SlotLabel, Expr *Alignment);
2204
2205 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2206 /// (unless they are value dependent or type dependent). Returns false
2207 /// and emits a diagnostic if one or more of the arguments could not be
2208 /// folded into a constant.
2209 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2210 MutableArrayRef<Expr *> Args);
2211
2212 enum class PragmaAlignPackDiagnoseKind {
2213 NonDefaultStateAtInclude,
2214 ChangedStateAtExit
2215 };
2216
2217 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2218 SourceLocation IncludeLoc);
2219 void DiagnoseUnterminatedPragmaAlignPack();
2220
2221 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2222 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2223
2224 /// ActOnPragmaMSComment - Called on well formed
2225 /// \#pragma comment(kind, "arg").
2226 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2227 StringRef Arg);
2228
2229 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2230 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2231 StringRef Value);
2232
2233 /// Are precise floating point semantics currently enabled?
2234 bool isPreciseFPEnabled() {
2235 return !CurFPFeatures.getAllowFPReassociate() &&
2236 !CurFPFeatures.getNoSignedZero() &&
2237 !CurFPFeatures.getAllowReciprocal() &&
2238 !CurFPFeatures.getAllowApproxFunc();
2239 }
2240
2241 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2242 LangOptions::FPEvalMethodKind Value);
2243
2244 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2245 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2246 PragmaFloatControlKind Value);
2247
2248 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2249 /// pointers_to_members(representation method[, general purpose
2250 /// representation]).
2251 void ActOnPragmaMSPointersToMembers(
2252 LangOptions::PragmaMSPointersToMembersKind Kind,
2253 SourceLocation PragmaLoc);
2254
2255 /// Called on well formed \#pragma vtordisp().
2256 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2257 SourceLocation PragmaLoc, MSVtorDispMode Value);
2258
2259 bool UnifySection(StringRef SectionName, int SectionFlags,
2260 NamedDecl *TheDecl);
2261 bool UnifySection(StringRef SectionName, int SectionFlags,
2262 SourceLocation PragmaSectionLocation);
2263
2264 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2265 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2266 PragmaMsStackAction Action,
2267 llvm::StringRef StackSlotLabel,
2268 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2269
2270 /// Called on well formed \#pragma section().
2271 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2272 StringLiteral *SegmentName);
2273
2274 /// Called on well-formed \#pragma init_seg().
2275 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2276 StringLiteral *SegmentName);
2277
2278 /// Called on well-formed \#pragma alloc_text().
2279 void ActOnPragmaMSAllocText(
2280 SourceLocation PragmaLocation, StringRef Section,
2281 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2282 &Functions);
2283
2284 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2285 /// strict_gs_check.
2286 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2287 PragmaMsStackAction Action,
2288 bool Value);
2289
2290 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2291 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2292 SourceLocation PragmaLoc);
2293
2294 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2295 SourceLocation PragmaLoc,
2296 attr::ParsedSubjectMatchRuleSet Rules);
2297 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2298 const IdentifierInfo *Namespace);
2299
2300 /// Called on well-formed '\#pragma clang attribute pop'.
2301 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2302 const IdentifierInfo *Namespace);
2303
2304 /// Adds the attributes that have been specified using the
2305 /// '\#pragma clang attribute push' directives to the given declaration.
2306 void AddPragmaAttributes(Scope *S, Decl *D);
2307
2308 using InstantiationContextDiagFuncRef =
2309 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2310 auto getDefaultDiagFunc() {
2311 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2312 // This bypasses a lot of the filters in the diag engine, as it's
2313 // to be used to attach notes to diagnostics which have already
2314 // been filtered through.
2315 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2316 PD.Emit(DB: Builder);
2317 };
2318 }
2319
2320 void PrintPragmaAttributeInstantiationPoint(
2321 InstantiationContextDiagFuncRef DiagFunc);
2322 void PrintPragmaAttributeInstantiationPoint() {
2323 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2324 }
2325
2326 void DiagnoseUnterminatedPragmaAttribute();
2327
2328 /// Called on well formed \#pragma clang optimize.
2329 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2330
2331 /// #pragma optimize("[optimization-list]", on | off).
2332 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2333
2334 /// Call on well formed \#pragma function.
2335 void
2336 ActOnPragmaMSFunction(SourceLocation Loc,
2337 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2338
2339 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2340 SourceLocation NameLoc,
2341 Scope *curScope);
2342
2343 /// Information from a C++ #pragma export, for a symbol that we
2344 /// haven't seen the declaration for yet.
2345 struct PendingPragmaInfo {
2346 SourceLocation NameLoc;
2347 bool Used;
2348 };
2349
2350 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2351
2352 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2353 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2354 Scope *curScope);
2355
2356 /// Only called on function definitions; if there is a pragma in scope
2357 /// with the effect of a range-based optnone, consider marking the function
2358 /// with attribute optnone.
2359 void AddRangeBasedOptnone(FunctionDecl *FD);
2360
2361 /// Only called on function definitions; if there is a `#pragma alloc_text`
2362 /// that decides which code section the function should be in, add
2363 /// attribute section to the function.
2364 void AddSectionMSAllocText(FunctionDecl *FD);
2365
2366 /// Adds the 'optnone' attribute to the function declaration if there
2367 /// are no conflicts; Loc represents the location causing the 'optnone'
2368 /// attribute to be added (usually because of a pragma).
2369 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2370
2371 /// Only called on function definitions; if there is a MSVC #pragma optimize
2372 /// in scope, consider changing the function's attributes based on the
2373 /// optimization list passed to the pragma.
2374 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2375
2376 /// Only called on function definitions; if there is a pragma in scope
2377 /// with the effect of a range-based no_builtin, consider marking the function
2378 /// with attribute no_builtin.
2379 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2380
2381 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2382 /// add an appropriate visibility attribute.
2383 void AddPushedVisibilityAttribute(Decl *RD);
2384
2385 /// FreeVisContext - Deallocate and null out VisContext.
2386 void FreeVisContext();
2387
2388 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2389 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2390 SourceLocation PragmaLoc);
2391
2392 /// ActOnPragmaFPContract - Called on well formed
2393 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2394 /// \#pragma clang fp contract
2395 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2396
2397 /// Called on well formed
2398 /// \#pragma clang fp reassociate
2399 /// or
2400 /// \#pragma clang fp reciprocal
2401 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2402 bool IsEnabled);
2403
2404 /// ActOnPragmaFenvAccess - Called on well formed
2405 /// \#pragma STDC FENV_ACCESS
2406 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2407
2408 /// ActOnPragmaCXLimitedRange - Called on well formed
2409 /// \#pragma STDC CX_LIMITED_RANGE
2410 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2411 LangOptions::ComplexRangeKind Range);
2412
2413 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2414 void ActOnPragmaFPExceptions(SourceLocation Loc,
2415 LangOptions::FPExceptionModeKind);
2416
2417 /// Called to set constant rounding mode for floating point operations.
2418 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2419
2420 /// Called to set exception behavior for floating point operations.
2421 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2422
2423 /// PushNamespaceVisibilityAttr - Note that we've entered a
2424 /// namespace with a visibility attribute.
2425 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2426 SourceLocation Loc);
2427
2428 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2429 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2430 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2431
2432 /// Handles semantic checking for features that are common to all attributes,
2433 /// such as checking whether a parameter was properly specified, or the
2434 /// correct number of arguments were passed, etc. Returns true if the
2435 /// attribute has been diagnosed.
2436 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2437 bool SkipArgCountCheck = false);
2438 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2439 bool SkipArgCountCheck = false);
2440
2441 ///@}
2442
2443 //
2444 //
2445 // -------------------------------------------------------------------------
2446 //
2447 //
2448
2449 /// \name Availability Attribute Handling
2450 /// Implementations are in SemaAvailability.cpp
2451 ///@{
2452
2453public:
2454 /// Issue any -Wunguarded-availability warnings in \c FD
2455 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2456
2457 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2458
2459 /// Retrieve the current function, if any, that should be analyzed for
2460 /// potential availability violations.
2461 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2462
2463 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2464 const ObjCInterfaceDecl *UnknownObjCClass,
2465 bool ObjCPropertyAccess,
2466 bool AvoidPartialAvailabilityChecks,
2467 ObjCInterfaceDecl *ClassReceiver);
2468
2469 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2470
2471 std::pair<AvailabilityResult, const NamedDecl *>
2472 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2473 ObjCInterfaceDecl *ClassReceiver);
2474 ///@}
2475
2476 //
2477 //
2478 // -------------------------------------------------------------------------
2479 //
2480 //
2481
2482 /// \name Bounds Safety
2483 /// Implementations are in SemaBoundsSafety.cpp
2484 ///@{
2485public:
2486 /// Check if applying the specified attribute variant from the "counted by"
2487 /// family of attributes to FieldDecl \p FD is semantically valid. If
2488 /// semantically invalid diagnostics will be emitted explaining the problems.
2489 ///
2490 /// \param FD The FieldDecl to apply the attribute to
2491 /// \param E The count expression on the attribute
2492 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2493 /// attributes. If the false the attribute is from
2494 /// "counted_by" family of attributes.
2495 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2496 /// of attributes. If false the attribute does not have the
2497 /// suffix.
2498 ///
2499 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2500 /// \p CountInBytes and \p OrNull both being true indicates the
2501 /// `counted_by_or_null` attribute.
2502 ///
2503 /// \returns false iff semantically valid.
2504 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2505 bool OrNull);
2506
2507 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2508 /// `__counted_by_or_null` pointer type \param LHSTy.
2509 ///
2510 /// \param LHSTy The type being assigned to. Checks will only be performed if
2511 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2512 /// \param RHSExpr The expression being assigned from.
2513 /// \param Action The type assignment being performed
2514 /// \param Loc The SourceLocation to use for error diagnostics
2515 /// \param Assignee The ValueDecl being assigned. This is used to compute
2516 /// the name of the assignee. If the assignee isn't known this can
2517 /// be set to nullptr.
2518 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2519 /// Assignee to compute the name of the assignee use the fully
2520 /// qualified name, otherwise use the unqualified name.
2521 ///
2522 /// \returns True iff no diagnostic where emitted, false otherwise.
2523 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2524 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2525 SourceLocation Loc, const ValueDecl *Assignee,
2526 bool ShowFullyQualifiedAssigneeName);
2527
2528 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2529 /// pointer.
2530 ///
2531 /// \param Entity The entity being initialized
2532 /// \param Kind The kind of initialization being performed
2533 /// \param Action The type assignment being performed
2534 /// \param LHSTy The type being assigned to. Checks will only be performed if
2535 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2536 /// \param RHSExpr The expression being used for initialization.
2537 ///
2538 /// \returns True iff no diagnostic where emitted, false otherwise.
2539 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2540 const InitializationKind &Kind,
2541 AssignmentAction Action,
2542 QualType LHSType, Expr *RHSExpr);
2543
2544 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2545 /// or counted_by_or_null pointers in \param E.
2546 ///
2547 /// \param E the expression to check
2548 ///
2549 /// \returns True iff no diagnostic where emitted, false otherwise.
2550 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2551 ///@}
2552
2553 //
2554 //
2555 // -------------------------------------------------------------------------
2556 //
2557 //
2558
2559 /// \name Casts
2560 /// Implementations are in SemaCast.cpp
2561 ///@{
2562
2563public:
2564 static bool isCast(CheckedConversionKind CCK) {
2565 return CCK == CheckedConversionKind::CStyleCast ||
2566 CCK == CheckedConversionKind::FunctionalCast ||
2567 CCK == CheckedConversionKind::OtherCast;
2568 }
2569
2570 /// ActOnCXXNamedCast - Parse
2571 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2572 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2573 SourceLocation LAngleBracketLoc, Declarator &D,
2574 SourceLocation RAngleBracketLoc,
2575 SourceLocation LParenLoc, Expr *E,
2576 SourceLocation RParenLoc);
2577
2578 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2579 TypeSourceInfo *Ty, Expr *E,
2580 SourceRange AngleBrackets, SourceRange Parens);
2581
2582 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2583 ExprResult Operand,
2584 SourceLocation RParenLoc);
2585
2586 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2587 Expr *Operand, SourceLocation RParenLoc);
2588
2589 // Checks that reinterpret casts don't have undefined behavior.
2590 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2591 bool IsDereference, SourceRange Range);
2592
2593 // Checks that the vector type should be initialized from a scalar
2594 // by splatting the value rather than populating a single element.
2595 // This is the case for AltiVecVector types as well as with
2596 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2597 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2598
2599 // Checks if the -faltivec-src-compat=gcc option is specified.
2600 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2601 // treated the same way as they are when trying to initialize
2602 // these vectors on gcc (an error is emitted).
2603 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2604 QualType SrcTy);
2605
2606 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2607 SourceLocation RParenLoc, Expr *Op);
2608
2609 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2610 SourceLocation LParenLoc,
2611 Expr *CastExpr,
2612 SourceLocation RParenLoc);
2613
2614 ///@}
2615
2616 //
2617 //
2618 // -------------------------------------------------------------------------
2619 //
2620 //
2621
2622 /// \name Extra Semantic Checking
2623 /// Implementations are in SemaChecking.cpp
2624 ///@{
2625
2626public:
2627 /// Used to change context to isConstantEvaluated without pushing a heavy
2628 /// ExpressionEvaluationContextRecord object.
2629 bool isConstantEvaluatedOverride = false;
2630
2631 bool isConstantEvaluatedContext() const {
2632 return currentEvaluationContext().isConstantEvaluated() ||
2633 isConstantEvaluatedOverride;
2634 }
2635
2636 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2637 unsigned ByteNo) const;
2638
2639 enum FormatArgumentPassingKind {
2640 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2641 FAPK_Variadic, // values to format are passed as variadic arguments
2642 FAPK_VAList, // values to format are passed in a va_list
2643 FAPK_Elsewhere, // values to format are not passed to this function
2644 };
2645
2646 // Used to grab the relevant information from a FormatAttr and a
2647 // FunctionDeclaration.
2648 struct FormatStringInfo {
2649 unsigned FormatIdx;
2650 unsigned FirstDataArg;
2651 FormatArgumentPassingKind ArgPassingKind;
2652 };
2653
2654 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2655 /// populate the FormatStringInfo parameter with the attribute's correct
2656 /// format_idx and firstDataArg. Returns true when the format fits the
2657 /// function and the FormatStringInfo has been populated.
2658 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2659 unsigned FirstArg, FormatStringInfo *FSI);
2660 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2661 bool HasImplicitThisParam, bool IsVariadic,
2662 FormatStringInfo *FSI);
2663
2664 // Used by C++ template instantiation.
2665 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2666
2667 /// ConvertVectorExpr - Handle __builtin_convertvector
2668 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2669 SourceLocation BuiltinLoc,
2670 SourceLocation RParenLoc);
2671
2672 static StringRef GetFormatStringTypeName(FormatStringType FST);
2673 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2674 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2675 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2676
2677 bool FormatStringHasSArg(const StringLiteral *FExpr);
2678
2679 /// Check for comparisons of floating-point values using == and !=. Issue a
2680 /// warning if the comparison is not likely to do what the programmer
2681 /// intended.
2682 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2683 const Expr *RHS, BinaryOperatorKind Opcode);
2684
2685 /// Register a magic integral constant to be used as a type tag.
2686 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2687 uint64_t MagicValue, QualType Type,
2688 bool LayoutCompatible, bool MustBeNull);
2689
2690 struct TypeTagData {
2691 TypeTagData() {}
2692
2693 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2694 : Type(Type), LayoutCompatible(LayoutCompatible),
2695 MustBeNull(MustBeNull) {}
2696
2697 QualType Type;
2698
2699 /// If true, \c Type should be compared with other expression's types for
2700 /// layout-compatibility.
2701 LLVM_PREFERRED_TYPE(bool)
2702 unsigned LayoutCompatible : 1;
2703 LLVM_PREFERRED_TYPE(bool)
2704 unsigned MustBeNull : 1;
2705 };
2706
2707 /// A pair of ArgumentKind identifier and magic value. This uniquely
2708 /// identifies the magic value.
2709 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2710
2711 /// Diagnoses the current set of gathered accesses. This happens at the end of
2712 /// each expression evaluation context. Diagnostics are emitted only for
2713 /// accesses gathered in the current evaluation context.
2714 void DiagnoseMisalignedMembers();
2715
2716 /// This function checks if the expression is in the sef of potentially
2717 /// misaligned members and it is converted to some pointer type T with lower
2718 /// or equal alignment requirements. If so it removes it. This is used when
2719 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2720 /// void*).
2721 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2722
2723 /// Returns true if `From` is a function or pointer to a function with the
2724 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2725 /// function without this attribute.
2726 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2727
2728 /// This function calls Action when it determines that E designates a
2729 /// misaligned member due to the packed attribute. This is used to emit
2730 /// local diagnostics like in reference binding.
2731 void RefersToMemberWithReducedAlignment(
2732 Expr *E,
2733 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2734 Action);
2735
2736 enum class AtomicArgumentOrder { API, AST };
2737 ExprResult
2738 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2739 SourceLocation RParenLoc, MultiExprArg Args,
2740 AtomicExpr::AtomicOp Op,
2741 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2742
2743 /// Check to see if a given expression could have '.c_str()' called on it.
2744 bool hasCStrMethod(const Expr *E);
2745
2746 /// Diagnose pointers that are always non-null.
2747 /// \param E the expression containing the pointer
2748 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2749 /// compared to a null pointer
2750 /// \param IsEqual True when the comparison is equal to a null pointer
2751 /// \param Range Extra SourceRange to highlight in the diagnostic
2752 void DiagnoseAlwaysNonNullPointer(Expr *E,
2753 Expr::NullPointerConstantKind NullType,
2754 bool IsEqual, SourceRange Range);
2755
2756 /// CheckParmsForFunctionDef - Check that the parameters of the given
2757 /// function are appropriate for the definition of a function. This
2758 /// takes care of any checks that cannot be performed on the
2759 /// declaration itself, e.g., that the types of each of the function
2760 /// parameters are complete.
2761 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2762 bool CheckParameterNames);
2763
2764 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2765 /// pointer cast increases the alignment requirements.
2766 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2767
2768 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2769 /// to weak/__unsafe_unretained type.
2770 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2771
2772 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2773 /// to weak/__unsafe_unretained expression.
2774 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2775
2776 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2777 /// statement as a \p Body, and it is located on the same line.
2778 ///
2779 /// This helps prevent bugs due to typos, such as:
2780 /// if (condition);
2781 /// do_stuff();
2782 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2783 unsigned DiagID);
2784
2785 /// Warn if a for/while loop statement \p S, which is followed by
2786 /// \p PossibleBody, has a suspicious null statement as a body.
2787 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2788
2789 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2790 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2791 SourceLocation OpLoc);
2792
2793 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2794 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2795 const TypeSourceInfo *Derived);
2796
2797 /// CheckFunctionCall - Check a direct function call for various correctness
2798 /// and safety properties not strictly enforced by the C type system.
2799 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2800 const FunctionProtoType *Proto);
2801
2802 enum class EltwiseBuiltinArgTyRestriction {
2803 None,
2804 FloatTy,
2805 IntegerTy,
2806 SignedIntOrFloatTy,
2807 };
2808
2809 /// \param FPOnly restricts the arguments to floating-point types.
2810 std::optional<QualType>
2811 BuiltinVectorMath(CallExpr *TheCall,
2812 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2813 EltwiseBuiltinArgTyRestriction::None);
2814 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2815
2816 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2817 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2818
2819 /// Handles the checks for format strings, non-POD arguments to vararg
2820 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2821 /// attributes and AArch64 SME attributes.
2822 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2823 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2824 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2825 VariadicCallType CallType);
2826
2827 /// Verify that two format strings (as understood by attribute(format) and
2828 /// attribute(format_matches) are compatible. If they are incompatible,
2829 /// diagnostics are emitted with the assumption that \c
2830 /// AuthoritativeFormatString is correct and
2831 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2832 /// diagnostics will point to it and a note will refer to \c
2833 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2834 bool
2835 CheckFormatStringsCompatible(FormatStringType FST,
2836 const StringLiteral *AuthoritativeFormatString,
2837 const StringLiteral *TestedFormatString,
2838 const Expr *FunctionCallArg = nullptr);
2839
2840 /// Verify that one format string (as understood by attribute(format)) is
2841 /// self-consistent; for instance, that it doesn't have multiple positional
2842 /// arguments referring to the same argument in incompatible ways. Diagnose
2843 /// if it isn't.
2844 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2845
2846 /// \brief Enforce the bounds of a TCB
2847 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2848 /// directly calls other functions in the same TCB as marked by the
2849 /// enforce_tcb and enforce_tcb_leaf attributes.
2850 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2851 const NamedDecl *Callee);
2852
2853 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2854
2855 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2856 /// TheCall is a constant expression.
2857 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2858 llvm::APSInt &Result);
2859
2860 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2861 /// TheCall is a constant expression in the range [Low, High].
2862 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2863 int High, bool RangeIsError = true);
2864
2865 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2866 /// TheCall is a constant expression is a multiple of Num..
2867 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2868 unsigned Multiple);
2869
2870 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2871 /// constant expression representing a power of 2.
2872 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2873
2874 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2875 /// a constant expression representing an arbitrary byte value shifted left by
2876 /// a multiple of 8 bits.
2877 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2878 unsigned ArgBits);
2879
2880 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2881 /// TheCall is a constant expression representing either a shifted byte value,
2882 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2883 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2884 /// Arm MVE intrinsics.
2885 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2886 unsigned ArgBits);
2887
2888 /// Checks that a call expression's argument count is at least the desired
2889 /// number. This is useful when doing custom type-checking on a variadic
2890 /// function. Returns true on error.
2891 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2892
2893 /// Checks that a call expression's argument count is at most the desired
2894 /// number. This is useful when doing custom type-checking on a variadic
2895 /// function. Returns true on error.
2896 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2897
2898 /// Checks that a call expression's argument count is in the desired range.
2899 /// This is useful when doing custom type-checking on a variadic function.
2900 /// Returns true on error.
2901 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2902 unsigned MaxArgCount);
2903
2904 /// Checks that a call expression's argument count is the desired number.
2905 /// This is useful when doing custom type-checking. Returns true on error.
2906 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2907
2908 /// Returns true if the argument consists of one contiguous run of 1s with any
2909 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2910 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2911 /// since all 1s are not contiguous.
2912 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2913
2914 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2915 bool *ICContext = nullptr,
2916 bool IsListInit = false);
2917
2918 /// Check for overflow behavior type related implicit conversion diagnostics.
2919 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2920 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
2921 SourceLocation CC);
2922
2923 bool
2924 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2925 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2926 EltwiseBuiltinArgTyRestriction::FloatTy);
2927 bool PrepareBuiltinElementwiseMathOneArgCall(
2928 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2929 EltwiseBuiltinArgTyRestriction::None);
2930
2931private:
2932 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2933 const ArraySubscriptExpr *ASE = nullptr,
2934 bool AllowOnePastEnd = true, bool IndexNegated = false);
2935 void CheckArrayAccess(const Expr *E);
2936
2937 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2938 const FunctionProtoType *Proto);
2939
2940 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2941 /// such as function pointers returned from functions.
2942 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2943
2944 /// CheckConstructorCall - Check a constructor call for correctness and safety
2945 /// properties not enforced by the C type system.
2946 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2947 ArrayRef<const Expr *> Args,
2948 const FunctionProtoType *Proto, SourceLocation Loc);
2949
2950 /// Warn if a pointer or reference argument passed to a function points to an
2951 /// object that is less aligned than the parameter. This can happen when
2952 /// creating a typedef with a lower alignment than the original type and then
2953 /// calling functions defined in terms of the original type.
2954 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2955 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2956
2957 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2958
2959 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2960 CallExpr *TheCall);
2961
2962 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2963 CallExpr *TheCall);
2964
2965 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2966
2967 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2968 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2969 /// on failure; return false on success.
2970 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2971 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2972
2973 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2974 /// friends. This is declared to take (...), so we have to check everything.
2975 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2976
2977 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2978 /// __builtin_isnan and friends. This is declared to take (...), so we have
2979 /// to check everything.
2980 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2981 unsigned BuiltinID);
2982
2983 /// Perform semantic analysis for a call to __builtin_complex.
2984 bool BuiltinComplex(CallExpr *TheCall);
2985 bool BuiltinOSLogFormat(CallExpr *TheCall);
2986
2987 /// BuiltinPrefetch - Handle __builtin_prefetch.
2988 /// This is declared to take (const void*, ...) and can take two
2989 /// optional constant int args.
2990 bool BuiltinPrefetch(CallExpr *TheCall);
2991
2992 /// Handle __builtin_alloca_with_align. This is declared
2993 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
2994 /// than 8.
2995 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
2996
2997 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
2998 bool BuiltinArithmeticFence(CallExpr *TheCall);
2999
3000 /// BuiltinAssume - Handle __assume (MS Extension).
3001 /// __assume does not evaluate its arguments, and should warn if its argument
3002 /// has side effects.
3003 bool BuiltinAssume(CallExpr *TheCall);
3004
3005 /// Handle __builtin_assume_aligned. This is declared
3006 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3007 bool BuiltinAssumeAligned(CallExpr *TheCall);
3008
3009 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3010 /// This checks that the target supports __builtin_longjmp and
3011 /// that val is a constant 1.
3012 bool BuiltinLongjmp(CallExpr *TheCall);
3013
3014 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3015 /// This checks that the target supports __builtin_setjmp.
3016 bool BuiltinSetjmp(CallExpr *TheCall);
3017
3018 /// We have a call to a function like __sync_fetch_and_add, which is an
3019 /// overloaded function based on the pointer type of its first argument.
3020 /// The main BuildCallExpr routines have already promoted the types of
3021 /// arguments because all of these calls are prototyped as void(...).
3022 ///
3023 /// This function goes through and does final semantic checking for these
3024 /// builtins, as well as generating any warnings.
3025 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3026
3027 /// BuiltinNontemporalOverloaded - We have a call to
3028 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3029 /// overloaded function based on the pointer type of its last argument.
3030 ///
3031 /// This function goes through and does final semantic checking for these
3032 /// builtins.
3033 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3034 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3035 AtomicExpr::AtomicOp Op);
3036
3037 /// \param FPOnly restricts the arguments to floating-point types.
3038 bool BuiltinElementwiseMath(CallExpr *TheCall,
3039 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3040 EltwiseBuiltinArgTyRestriction::None);
3041 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3042
3043 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3044
3045 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3046 BuiltinCountedByRefKind K);
3047 bool BuiltinCountedByRef(CallExpr *TheCall);
3048
3049 // Matrix builtin handling.
3050 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3051 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3052 ExprResult CallResult);
3053 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3054 ExprResult CallResult);
3055
3056 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3057 /// functions) for correct use of format strings.
3058 /// Returns true if a format string has been fully checked.
3059 bool CheckFormatArguments(const FormatAttr *Format,
3060 ArrayRef<const Expr *> Args, bool IsCXXMember,
3061 VariadicCallType CallType, SourceLocation Loc,
3062 SourceRange Range,
3063 llvm::SmallBitVector &CheckedVarArgs);
3064 bool CheckFormatString(const FormatMatchesAttr *Format,
3065 ArrayRef<const Expr *> Args, bool IsCXXMember,
3066 VariadicCallType CallType, SourceLocation Loc,
3067 SourceRange Range,
3068 llvm::SmallBitVector &CheckedVarArgs);
3069 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3070 FormatArgumentPassingKind FAPK,
3071 StringLiteral *ReferenceFormatString,
3072 unsigned format_idx, unsigned firstDataArg,
3073 FormatStringType Type, VariadicCallType CallType,
3074 SourceLocation Loc, SourceRange range,
3075 llvm::SmallBitVector &CheckedVarArgs);
3076
3077 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3078
3079 /// Warn when using the wrong abs() function.
3080 void CheckAbsoluteValueFunction(const CallExpr *Call,
3081 const FunctionDecl *FDecl);
3082
3083 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3084
3085 /// Check for dangerous or invalid arguments to memset().
3086 ///
3087 /// This issues warnings on known problematic, dangerous or unspecified
3088 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3089 /// function calls.
3090 ///
3091 /// \param Call The call expression to diagnose.
3092 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3093 IdentifierInfo *FnName);
3094
3095 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3096 IdentifierInfo *FnName);
3097 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3098 // be the size of the source, instead of the destination.
3099 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3100
3101 // Warn on anti-patterns as the 'size' argument to strncat.
3102 // The correct size argument should look like following:
3103 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3104 void CheckStrncatArguments(const CallExpr *Call,
3105 const IdentifierInfo *FnName);
3106
3107 /// Alerts the user that they are attempting to free a non-malloc'd object.
3108 void CheckFreeArguments(const CallExpr *E);
3109
3110 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3111 SourceLocation ReturnLoc, bool isObjCMethod = false,
3112 const AttrVec *Attrs = nullptr,
3113 const FunctionDecl *FD = nullptr);
3114
3115 /// Diagnoses "dangerous" implicit conversions within the given
3116 /// expression (which is a full expression). Implements -Wconversion
3117 /// and -Wsign-compare.
3118 ///
3119 /// \param CC the "context" location of the implicit conversion, i.e.
3120 /// the most location of the syntactic entity requiring the implicit
3121 /// conversion
3122 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3123
3124 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3125 /// Input argument E is a logical expression.
3126 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3127
3128 /// Diagnose when expression is an integer constant expression and its
3129 /// evaluation results in integer overflow
3130 void CheckForIntOverflow(const Expr *E);
3131 void CheckUnsequencedOperations(const Expr *E);
3132
3133 /// Perform semantic checks on a completed expression. This will either
3134 /// be a full-expression or a default argument expression.
3135 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3136 bool IsConstexpr = false);
3137
3138 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3139 Expr *Init);
3140
3141 /// A map from magic value to type information.
3142 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3143 TypeTagForDatatypeMagicValues;
3144
3145 /// Peform checks on a call of a function with argument_with_type_tag
3146 /// or pointer_with_type_tag attributes.
3147 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3148 const ArrayRef<const Expr *> ExprArgs,
3149 SourceLocation CallSiteLoc);
3150
3151 /// Check if we are taking the address of a packed field
3152 /// as this may be a problem if the pointer value is dereferenced.
3153 void CheckAddressOfPackedMember(Expr *rhs);
3154
3155 /// Helper class that collects misaligned member designations and
3156 /// their location info for delayed diagnostics.
3157 struct MisalignedMember {
3158 Expr *E;
3159 RecordDecl *RD;
3160 ValueDecl *MD;
3161 CharUnits Alignment;
3162
3163 MisalignedMember() : E(), RD(), MD() {}
3164 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3165 CharUnits Alignment)
3166 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3167 explicit MisalignedMember(Expr *E)
3168 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3169
3170 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3171 };
3172
3173 /// Adds an expression to the set of gathered misaligned members.
3174 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3175 CharUnits Alignment);
3176 ///@}
3177
3178 //
3179 //
3180 // -------------------------------------------------------------------------
3181 //
3182 //
3183
3184 /// \name C++ Coroutines
3185 /// Implementations are in SemaCoroutine.cpp
3186 ///@{
3187
3188public:
3189 /// The C++ "std::coroutine_traits" template, which is defined in
3190 /// \<coroutine_traits>
3191 ClassTemplateDecl *StdCoroutineTraitsCache;
3192
3193 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3194 StringRef Keyword);
3195 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3196 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3197 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3198
3199 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3200 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3201 UnresolvedLookupExpr *Lookup);
3202 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3203 Expr *Awaiter, bool IsImplicit = false);
3204 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3205 UnresolvedLookupExpr *Lookup);
3206 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3207 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3208 bool IsImplicit = false);
3209 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3210 bool buildCoroutineParameterMoves(SourceLocation Loc);
3211 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3212 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3213
3214 // As a clang extension, enforces that a non-coroutine function must be marked
3215 // with [[clang::coro_wrapper]] if it returns a type marked with
3216 // [[clang::coro_return_type]].
3217 // Expects that FD is not a coroutine.
3218 void CheckCoroutineWrapper(FunctionDecl *FD);
3219 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3220 /// namespace. The namespace found is recorded in Namespace.
3221 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3222 SourceLocation FuncLoc);
3223 /// Check that the expression co_await promise.final_suspend() shall not be
3224 /// potentially-throwing.
3225 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3226
3227 ///@}
3228
3229 //
3230 //
3231 // -------------------------------------------------------------------------
3232 //
3233 //
3234
3235 /// \name C++ Scope Specifiers
3236 /// Implementations are in SemaCXXScopeSpec.cpp
3237 ///@{
3238
3239public:
3240 // Marks SS invalid if it represents an incomplete type.
3241 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3242 // Complete an enum decl, maybe without a scope spec.
3243 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3244 CXXScopeSpec *SS = nullptr);
3245
3246 /// Compute the DeclContext that is associated with the given type.
3247 ///
3248 /// \param T the type for which we are attempting to find a DeclContext.
3249 ///
3250 /// \returns the declaration context represented by the type T,
3251 /// or NULL if the declaration context cannot be computed (e.g., because it is
3252 /// dependent and not the current instantiation).
3253 DeclContext *computeDeclContext(QualType T);
3254
3255 /// Compute the DeclContext that is associated with the given
3256 /// scope specifier.
3257 ///
3258 /// \param SS the C++ scope specifier as it appears in the source
3259 ///
3260 /// \param EnteringContext when true, we will be entering the context of
3261 /// this scope specifier, so we can retrieve the declaration context of a
3262 /// class template or class template partial specialization even if it is
3263 /// not the current instantiation.
3264 ///
3265 /// \returns the declaration context represented by the scope specifier @p SS,
3266 /// or NULL if the declaration context cannot be computed (e.g., because it is
3267 /// dependent and not the current instantiation).
3268 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3269 bool EnteringContext = false);
3270 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3271
3272 /// If the given nested name specifier refers to the current
3273 /// instantiation, return the declaration that corresponds to that
3274 /// current instantiation (C++0x [temp.dep.type]p1).
3275 ///
3276 /// \param NNS a dependent nested name specifier.
3277 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3278
3279 /// The parser has parsed a global nested-name-specifier '::'.
3280 ///
3281 /// \param CCLoc The location of the '::'.
3282 ///
3283 /// \param SS The nested-name-specifier, which will be updated in-place
3284 /// to reflect the parsed nested-name-specifier.
3285 ///
3286 /// \returns true if an error occurred, false otherwise.
3287 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3288
3289 /// The parser has parsed a '__super' nested-name-specifier.
3290 ///
3291 /// \param SuperLoc The location of the '__super' keyword.
3292 ///
3293 /// \param ColonColonLoc The location of the '::'.
3294 ///
3295 /// \param SS The nested-name-specifier, which will be updated in-place
3296 /// to reflect the parsed nested-name-specifier.
3297 ///
3298 /// \returns true if an error occurred, false otherwise.
3299 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3300 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3301
3302 /// Determines whether the given declaration is an valid acceptable
3303 /// result for name lookup of a nested-name-specifier.
3304 /// \param SD Declaration checked for nested-name-specifier.
3305 /// \param IsExtension If not null and the declaration is accepted as an
3306 /// extension, the pointed variable is assigned true.
3307 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3308 bool *CanCorrect = nullptr);
3309
3310 /// If the given nested-name-specifier begins with a bare identifier
3311 /// (e.g., Base::), perform name lookup for that identifier as a
3312 /// nested-name-specifier within the given scope, and return the result of
3313 /// that name lookup.
3314 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3315
3316 /// Keeps information about an identifier in a nested-name-spec.
3317 ///
3318 struct NestedNameSpecInfo {
3319 /// The type of the object, if we're parsing nested-name-specifier in
3320 /// a member access expression.
3321 ParsedType ObjectType;
3322
3323 /// The identifier preceding the '::'.
3324 IdentifierInfo *Identifier;
3325
3326 /// The location of the identifier.
3327 SourceLocation IdentifierLoc;
3328
3329 /// The location of the '::'.
3330 SourceLocation CCLoc;
3331
3332 /// Creates info object for the most typical case.
3333 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3334 SourceLocation ColonColonLoc,
3335 ParsedType ObjectType = ParsedType())
3336 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3337 CCLoc(ColonColonLoc) {}
3338
3339 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3340 SourceLocation ColonColonLoc, QualType ObjectType)
3341 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3342 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3343 };
3344
3345 /// Build a new nested-name-specifier for "identifier::", as described
3346 /// by ActOnCXXNestedNameSpecifier.
3347 ///
3348 /// \param S Scope in which the nested-name-specifier occurs.
3349 /// \param IdInfo Parser information about an identifier in the
3350 /// nested-name-spec.
3351 /// \param EnteringContext If true, enter the context specified by the
3352 /// nested-name-specifier.
3353 /// \param SS Optional nested name specifier preceding the identifier.
3354 /// \param ScopeLookupResult Provides the result of name lookup within the
3355 /// scope of the nested-name-specifier that was computed at template
3356 /// definition time.
3357 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3358 /// error recovery and what kind of recovery is performed.
3359 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3360 /// are allowed. The bool value pointed by this parameter is set to
3361 /// 'true' if the identifier is treated as if it was followed by ':',
3362 /// not '::'.
3363 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3364 ///
3365 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3366 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3367 /// the result of name lookup within the scope of the nested-name-specifier
3368 /// that was computed at template definition time.
3369 ///
3370 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3371 /// recovery. This means that it should not emit diagnostics, it should
3372 /// just return true on failure. It also means it should only return a valid
3373 /// scope if it *knows* that the result is correct. It should not return in a
3374 /// dependent context, for example. Nor will it extend \p SS with the scope
3375 /// specifier.
3376 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3377 bool EnteringContext, CXXScopeSpec &SS,
3378 NamedDecl *ScopeLookupResult,
3379 bool ErrorRecoveryLookup,
3380 bool *IsCorrectedToColon = nullptr,
3381 bool OnlyNamespace = false);
3382
3383 /// The parser has parsed a nested-name-specifier 'identifier::'.
3384 ///
3385 /// \param S The scope in which this nested-name-specifier occurs.
3386 ///
3387 /// \param IdInfo Parser information about an identifier in the
3388 /// nested-name-spec.
3389 ///
3390 /// \param EnteringContext Whether we're entering the context nominated by
3391 /// this nested-name-specifier.
3392 ///
3393 /// \param SS The nested-name-specifier, which is both an input
3394 /// parameter (the nested-name-specifier before this type) and an
3395 /// output parameter (containing the full nested-name-specifier,
3396 /// including this new type).
3397 ///
3398 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3399 /// are allowed. The bool value pointed by this parameter is set to 'true'
3400 /// if the identifier is treated as if it was followed by ':', not '::'.
3401 ///
3402 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3403 ///
3404 /// \returns true if an error occurred, false otherwise.
3405 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3406 bool EnteringContext, CXXScopeSpec &SS,
3407 bool *IsCorrectedToColon = nullptr,
3408 bool OnlyNamespace = false);
3409
3410 /// The parser has parsed a nested-name-specifier
3411 /// 'template[opt] template-name < template-args >::'.
3412 ///
3413 /// \param S The scope in which this nested-name-specifier occurs.
3414 ///
3415 /// \param SS The nested-name-specifier, which is both an input
3416 /// parameter (the nested-name-specifier before this type) and an
3417 /// output parameter (containing the full nested-name-specifier,
3418 /// including this new type).
3419 ///
3420 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3421 /// \param TemplateName the template name.
3422 /// \param TemplateNameLoc The location of the template name.
3423 /// \param LAngleLoc The location of the opening angle bracket ('<').
3424 /// \param TemplateArgs The template arguments.
3425 /// \param RAngleLoc The location of the closing angle bracket ('>').
3426 /// \param CCLoc The location of the '::'.
3427 ///
3428 /// \param EnteringContext Whether we're entering the context of the
3429 /// nested-name-specifier.
3430 ///
3431 ///
3432 /// \returns true if an error occurred, false otherwise.
3433 bool ActOnCXXNestedNameSpecifier(
3434 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3435 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3436 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3437 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3438
3439 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3440 SourceLocation ColonColonLoc);
3441
3442 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3443 const DeclSpec &DS,
3444 SourceLocation ColonColonLoc,
3445 QualType Type);
3446
3447 /// IsInvalidUnlessNestedName - This method is used for error recovery
3448 /// purposes to determine whether the specified identifier is only valid as
3449 /// a nested name specifier, for example a namespace name. It is
3450 /// conservatively correct to always return false from this method.
3451 ///
3452 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3453 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3454 NestedNameSpecInfo &IdInfo,
3455 bool EnteringContext);
3456
3457 /// Given a C++ nested-name-specifier, produce an annotation value
3458 /// that the parser can use later to reconstruct the given
3459 /// nested-name-specifier.
3460 ///
3461 /// \param SS A nested-name-specifier.
3462 ///
3463 /// \returns A pointer containing all of the information in the
3464 /// nested-name-specifier \p SS.
3465 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3466
3467 /// Given an annotation pointer for a nested-name-specifier, restore
3468 /// the nested-name-specifier structure.
3469 ///
3470 /// \param Annotation The annotation pointer, produced by
3471 /// \c SaveNestedNameSpecifierAnnotation().
3472 ///
3473 /// \param AnnotationRange The source range corresponding to the annotation.
3474 ///
3475 /// \param SS The nested-name-specifier that will be updated with the contents
3476 /// of the annotation pointer.
3477 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3478 SourceRange AnnotationRange,
3479 CXXScopeSpec &SS);
3480
3481 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3482
3483 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3484 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3485 /// After this method is called, according to [C++ 3.4.3p3], names should be
3486 /// looked up in the declarator-id's scope, until the declarator is parsed and
3487 /// ActOnCXXExitDeclaratorScope is called.
3488 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3489 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3490
3491 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3492 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3493 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3494 /// Used to indicate that names should revert to being looked up in the
3495 /// defining scope.
3496 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3497
3498 ///@}
3499
3500 //
3501 //
3502 // -------------------------------------------------------------------------
3503 //
3504 //
3505
3506 /// \name Declarations
3507 /// Implementations are in SemaDecl.cpp
3508 ///@{
3509
3510public:
3511 IdentifierResolver IdResolver;
3512
3513 /// The index of the first InventedParameterInfo that refers to the current
3514 /// context.
3515 unsigned InventedParameterInfosStart = 0;
3516
3517 /// A RAII object to temporarily push a declaration context.
3518 class ContextRAII {
3519 private:
3520 Sema &S;
3521 DeclContext *SavedContext;
3522 ProcessingContextState SavedContextState;
3523 QualType SavedCXXThisTypeOverride;
3524 unsigned SavedFunctionScopesStart;
3525 unsigned SavedInventedParameterInfosStart;
3526
3527 public:
3528 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3529 : S(S), SavedContext(S.CurContext),
3530 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3531 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3532 SavedFunctionScopesStart(S.FunctionScopesStart),
3533 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3534 assert(ContextToPush && "pushing null context");
3535 S.CurContext = ContextToPush;
3536 if (NewThisContext)
3537 S.CXXThisTypeOverride = QualType();
3538 // Any saved FunctionScopes do not refer to this context.
3539 S.FunctionScopesStart = S.FunctionScopes.size();
3540 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3541 }
3542
3543 void pop() {
3544 if (!SavedContext)
3545 return;
3546 S.CurContext = SavedContext;
3547 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3548 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3549 S.FunctionScopesStart = SavedFunctionScopesStart;
3550 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3551 SavedContext = nullptr;
3552 }
3553
3554 ~ContextRAII() { pop(); }
3555 ContextRAII(const ContextRAII &) = delete;
3556 ContextRAII &operator=(const ContextRAII &) = delete;
3557 };
3558
3559 void DiagnoseInvalidJumps(Stmt *Body);
3560
3561 /// The function definitions which were renamed as part of typo-correction
3562 /// to match their respective declarations. We want to keep track of them
3563 /// to ensure that we don't emit a "redefinition" error if we encounter a
3564 /// correctly named definition after the renamed definition.
3565 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3566
3567 /// A cache of the flags available in enumerations with the flag_bits
3568 /// attribute.
3569 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3570
3571 /// A cache of enumerator values for enums checked by -Wassign-enum.
3572 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3573 AssignEnumCache;
3574
3575 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3576 /// declared. Rare. May alias another identifier, declared or undeclared.
3577 ///
3578 /// For aliases, the target identifier is used as a key for eventual
3579 /// processing when the target is declared. For the single-identifier form,
3580 /// the sole identifier is used as the key. Each entry is a `SetVector`
3581 /// (ordered by parse order) of aliases (identified by the alias name) in case
3582 /// of multiple aliases to the same undeclared identifier.
3583 llvm::MapVector<
3584 IdentifierInfo *,
3585 llvm::SetVector<
3586 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3587 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3588 WeakUndeclaredIdentifiers;
3589
3590 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3591 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3592 /// to define functions that occur in multiple standards to call the version
3593 /// in the currently selected standard.
3594 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers;
3595
3596 /// Set containing all typedefs that are likely unused.
3597 llvm::SmallSetVector<const TypedefNameDecl *, 4>
3598 UnusedLocalTypedefNameCandidates;
3599
3600 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
3601 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3602 UnusedFileScopedDeclsType;
3603
3604 /// The set of file scoped decls seen so far that have not been used
3605 /// and must warn if not used. Only contains the first declaration.
3606 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3607
3608 typedef LazyVector<VarDecl *, ExternalSemaSource,
3609 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
3610 TentativeDefinitionsType;
3611
3612 /// All the tentative definitions encountered in the TU.
3613 TentativeDefinitionsType TentativeDefinitions;
3614
3615 /// All the external declarations encoutered and used in the TU.
3616 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3617
3618 /// Generally null except when we temporarily switch decl contexts,
3619 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3620 DeclContext *OriginalLexicalContext;
3621
3622 /// Is the module scope we are in a C++ Header Unit?
3623 bool currentModuleIsHeaderUnit() const {
3624 return ModuleScopes.empty() ? false
3625 : ModuleScopes.back().Module->isHeaderUnit();
3626 }
3627
3628 /// Get the module owning an entity.
3629 Module *getOwningModule(const Decl *Entity) {
3630 return Entity->getOwningModule();
3631 }
3632
3633 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3634
3635 enum class DiagCtorKind { None, Implicit, Typename };
3636 /// Returns the TypeDeclType for the given type declaration,
3637 /// as ASTContext::getTypeDeclType would, but
3638 /// performs the required semantic checks for name lookup of said entity.
3639 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3640 SourceLocation NameLoc);
3641
3642 /// If the identifier refers to a type name within this scope,
3643 /// return the declaration of that type.
3644 ///
3645 /// This routine performs ordinary name lookup of the identifier II
3646 /// within the given scope, with optional C++ scope specifier SS, to
3647 /// determine whether the name refers to a type. If so, returns an
3648 /// opaque pointer (actually a QualType) corresponding to that
3649 /// type. Otherwise, returns NULL.
3650 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3651 Scope *S, CXXScopeSpec *SS = nullptr,
3652 bool isClassName = false, bool HasTrailingDot = false,
3653 ParsedType ObjectType = nullptr,
3654 bool IsCtorOrDtorName = false,
3655 bool WantNontrivialTypeSourceInfo = false,
3656 bool IsClassTemplateDeductionContext = true,
3657 ImplicitTypenameContext AllowImplicitTypename =
3658 ImplicitTypenameContext::No,
3659 IdentifierInfo **CorrectedII = nullptr);
3660
3661 /// isTagName() - This method is called *for error recovery purposes only*
3662 /// to determine if the specified name is a valid tag name ("struct foo"). If
3663 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3664 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3665 /// diagnose cases in C where the user forgot to specify the tag.
3666 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3667
3668 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3669 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3670 /// then downgrade the missing typename error to a warning.
3671 /// This is needed for MSVC compatibility; Example:
3672 /// @code
3673 /// template<class T> class A {
3674 /// public:
3675 /// typedef int TYPE;
3676 /// };
3677 /// template<class T> class B : public A<T> {
3678 /// public:
3679 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3680 /// };
3681 /// @endcode
3682 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3683 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3684 Scope *S, CXXScopeSpec *SS,
3685 ParsedType &SuggestedType,
3686 bool IsTemplateName = false);
3687
3688 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3689 /// type name has failed in a dependent context. In these situations, we
3690 /// automatically form a DependentTypeName that will retry lookup in a related
3691 /// scope during instantiation.
3692 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3693 SourceLocation NameLoc,
3694 bool IsTemplateTypeArg);
3695
3696 class NameClassification {
3697 NameClassificationKind Kind;
3698 union {
3699 ExprResult Expr;
3700 NamedDecl *NonTypeDecl;
3701 TemplateName Template;
3702 ParsedType Type;
3703 };
3704
3705 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3706
3707 public:
3708 NameClassification(ParsedType Type)
3709 : Kind(NameClassificationKind::Type), Type(Type) {}
3710
3711 NameClassification(const IdentifierInfo *Keyword)
3712 : Kind(NameClassificationKind::Keyword) {}
3713
3714 static NameClassification Error() {
3715 return NameClassification(NameClassificationKind::Error);
3716 }
3717
3718 static NameClassification Unknown() {
3719 return NameClassification(NameClassificationKind::Unknown);
3720 }
3721
3722 static NameClassification OverloadSet(ExprResult E) {
3723 NameClassification Result(NameClassificationKind::OverloadSet);
3724 Result.Expr = E;
3725 return Result;
3726 }
3727
3728 static NameClassification NonType(NamedDecl *D) {
3729 NameClassification Result(NameClassificationKind::NonType);
3730 Result.NonTypeDecl = D;
3731 return Result;
3732 }
3733
3734 static NameClassification UndeclaredNonType() {
3735 return NameClassification(NameClassificationKind::UndeclaredNonType);
3736 }
3737
3738 static NameClassification DependentNonType() {
3739 return NameClassification(NameClassificationKind::DependentNonType);
3740 }
3741
3742 static NameClassification TypeTemplate(TemplateName Name) {
3743 NameClassification Result(NameClassificationKind::TypeTemplate);
3744 Result.Template = Name;
3745 return Result;
3746 }
3747
3748 static NameClassification VarTemplate(TemplateName Name) {
3749 NameClassification Result(NameClassificationKind::VarTemplate);
3750 Result.Template = Name;
3751 return Result;
3752 }
3753
3754 static NameClassification FunctionTemplate(TemplateName Name) {
3755 NameClassification Result(NameClassificationKind::FunctionTemplate);
3756 Result.Template = Name;
3757 return Result;
3758 }
3759
3760 static NameClassification Concept(TemplateName Name) {
3761 NameClassification Result(NameClassificationKind::Concept);
3762 Result.Template = Name;
3763 return Result;
3764 }
3765
3766 static NameClassification UndeclaredTemplate(TemplateName Name) {
3767 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3768 Result.Template = Name;
3769 return Result;
3770 }
3771
3772 NameClassificationKind getKind() const { return Kind; }
3773
3774 ExprResult getExpression() const {
3775 assert(Kind == NameClassificationKind::OverloadSet);
3776 return Expr;
3777 }
3778
3779 ParsedType getType() const {
3780 assert(Kind == NameClassificationKind::Type);
3781 return Type;
3782 }
3783
3784 NamedDecl *getNonTypeDecl() const {
3785 assert(Kind == NameClassificationKind::NonType);
3786 return NonTypeDecl;
3787 }
3788
3789 TemplateName getTemplateName() const {
3790 assert(Kind == NameClassificationKind::TypeTemplate ||
3791 Kind == NameClassificationKind::FunctionTemplate ||
3792 Kind == NameClassificationKind::VarTemplate ||
3793 Kind == NameClassificationKind::Concept ||
3794 Kind == NameClassificationKind::UndeclaredTemplate);
3795 return Template;
3796 }
3797
3798 TemplateNameKind getTemplateNameKind() const {
3799 switch (Kind) {
3800 case NameClassificationKind::TypeTemplate:
3801 return TNK_Type_template;
3802 case NameClassificationKind::FunctionTemplate:
3803 return TNK_Function_template;
3804 case NameClassificationKind::VarTemplate:
3805 return TNK_Var_template;
3806 case NameClassificationKind::Concept:
3807 return TNK_Concept_template;
3808 case NameClassificationKind::UndeclaredTemplate:
3809 return TNK_Undeclared_template;
3810 default:
3811 llvm_unreachable("unsupported name classification.");
3812 }
3813 }
3814 };
3815
3816 /// Perform name lookup on the given name, classifying it based on
3817 /// the results of name lookup and the following token.
3818 ///
3819 /// This routine is used by the parser to resolve identifiers and help direct
3820 /// parsing. When the identifier cannot be found, this routine will attempt
3821 /// to correct the typo and classify based on the resulting name.
3822 ///
3823 /// \param S The scope in which we're performing name lookup.
3824 ///
3825 /// \param SS The nested-name-specifier that precedes the name.
3826 ///
3827 /// \param Name The identifier. If typo correction finds an alternative name,
3828 /// this pointer parameter will be updated accordingly.
3829 ///
3830 /// \param NameLoc The location of the identifier.
3831 ///
3832 /// \param NextToken The token following the identifier. Used to help
3833 /// disambiguate the name.
3834 ///
3835 /// \param CCC The correction callback, if typo correction is desired.
3836 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3837 IdentifierInfo *&Name, SourceLocation NameLoc,
3838 const Token &NextToken,
3839 CorrectionCandidateCallback *CCC = nullptr);
3840
3841 /// Act on the result of classifying a name as an undeclared (ADL-only)
3842 /// non-type declaration.
3843 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3844 SourceLocation NameLoc);
3845 /// Act on the result of classifying a name as an undeclared member of a
3846 /// dependent base class.
3847 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3848 IdentifierInfo *Name,
3849 SourceLocation NameLoc,
3850 bool IsAddressOfOperand);
3851 /// Act on the result of classifying a name as a specific non-type
3852 /// declaration.
3853 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3854 NamedDecl *Found,
3855 SourceLocation NameLoc,
3856 const Token &NextToken);
3857 /// Act on the result of classifying a name as an overload set.
3858 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3859
3860 /// Describes the detailed kind of a template name. Used in diagnostics.
3861 enum class TemplateNameKindForDiagnostics {
3862 ClassTemplate,
3863 FunctionTemplate,
3864 VarTemplate,
3865 AliasTemplate,
3866 TemplateTemplateParam,
3867 Concept,
3868 DependentTemplate
3869 };
3870 TemplateNameKindForDiagnostics
3871 getTemplateNameKindForDiagnostics(TemplateName Name);
3872
3873 /// Determine whether it's plausible that E was intended to be a
3874 /// template-name.
3875 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3876 if (!getLangOpts().CPlusPlus || E.isInvalid())
3877 return false;
3878 Dependent = false;
3879 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3880 return !DRE->hasExplicitTemplateArgs();
3881 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3882 return !ME->hasExplicitTemplateArgs();
3883 Dependent = true;
3884 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
3885 return !DSDRE->hasExplicitTemplateArgs();
3886 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
3887 return !DSME->hasExplicitTemplateArgs();
3888 // Any additional cases recognized here should also be handled by
3889 // diagnoseExprIntendedAsTemplateName.
3890 return false;
3891 }
3892
3893 void warnOnReservedIdentifier(const NamedDecl *D);
3894 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3895
3896 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3897
3898 Decl *ActOnDeclarator(Scope *S, Declarator &D);
3899
3900 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3901 MultiTemplateParamsArg TemplateParameterLists);
3902
3903 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3904 /// true if we were successful.
3905 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3906 SourceLocation Loc,
3907 unsigned FailedFoldDiagID);
3908
3909 /// Register the given locally-scoped extern "C" declaration so
3910 /// that it can be found later for redeclarations. We include any extern "C"
3911 /// declaration that is not visible in the translation unit here, not just
3912 /// function-scope declarations.
3913 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3914
3915 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3916 /// If T is the name of a class, then each of the following shall have a
3917 /// name different from T:
3918 /// - every static data member of class T;
3919 /// - every member function of class T
3920 /// - every member of class T that is itself a type;
3921 /// \returns true if the declaration name violates these rules.
3922 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3923
3924 /// Diagnose a declaration whose declarator-id has the given
3925 /// nested-name-specifier.
3926 ///
3927 /// \param SS The nested-name-specifier of the declarator-id.
3928 ///
3929 /// \param DC The declaration context to which the nested-name-specifier
3930 /// resolves.
3931 ///
3932 /// \param Name The name of the entity being declared.
3933 ///
3934 /// \param Loc The location of the name of the entity being declared.
3935 ///
3936 /// \param IsMemberSpecialization Whether we are declaring a member
3937 /// specialization.
3938 ///
3939 /// \param TemplateId The template-id, if any.
3940 ///
3941 /// \returns true if we cannot safely recover from this error, false
3942 /// otherwise.
3943 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3944 DeclarationName Name, SourceLocation Loc,
3945 TemplateIdAnnotation *TemplateId,
3946 bool IsMemberSpecialization);
3947
3948 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
3949
3950 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3951
3952 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
3953 unsigned &IntVal);
3954
3955 /// Diagnose function specifiers on a declaration of an identifier that
3956 /// does not identify a function.
3957 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3958
3959 /// Return the declaration shadowed by the given typedef \p D, or null
3960 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3961 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
3962 const LookupResult &R);
3963
3964 /// Return the declaration shadowed by the given variable \p D, or null
3965 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3966 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
3967
3968 /// Return the declaration shadowed by the given variable \p D, or null
3969 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3970 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
3971 const LookupResult &R);
3972 /// Diagnose variable or built-in function shadowing. Implements
3973 /// -Wshadow.
3974 ///
3975 /// This method is called whenever a VarDecl is added to a "useful"
3976 /// scope.
3977 ///
3978 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3979 /// \param R the lookup of the name
3980 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3981 const LookupResult &R);
3982
3983 /// Check -Wshadow without the advantage of a previous lookup.
3984 void CheckShadow(Scope *S, VarDecl *D);
3985
3986 /// Warn if 'E', which is an expression that is about to be modified, refers
3987 /// to a shadowing declaration.
3988 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
3989
3990 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
3991 /// when these variables are captured by the lambda.
3992 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
3993
3994 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
3995 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3996 TypedefNameDecl *NewTD);
3997 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
3998 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3999 TypeSourceInfo *TInfo,
4000 LookupResult &Previous);
4001
4002 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4003 /// declares a typedef-name, either using the 'typedef' type specifier or via
4004 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4005 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4006 LookupResult &Previous, bool &Redeclaration);
4007 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4008 TypeSourceInfo *TInfo,
4009 LookupResult &Previous,
4010 MultiTemplateParamsArg TemplateParamLists,
4011 bool &AddToScope,
4012 ArrayRef<BindingDecl *> Bindings = {});
4013
4014private:
4015 // Perform a check on an AsmLabel to verify its consistency and emit
4016 // diagnostics in case of an error.
4017 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4018 TypeSourceInfo *TInfo, VarDecl *);
4019
4020public:
4021 /// Perform semantic checking on a newly-created variable
4022 /// declaration.
4023 ///
4024 /// This routine performs all of the type-checking required for a
4025 /// variable declaration once it has been built. It is used both to
4026 /// check variables after they have been parsed and their declarators
4027 /// have been translated into a declaration, and to check variables
4028 /// that have been instantiated from a template.
4029 ///
4030 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4031 ///
4032 /// Returns true if the variable declaration is a redeclaration.
4033 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4034 void CheckVariableDeclarationType(VarDecl *NewVD);
4035 void CheckCompleteVariableDeclaration(VarDecl *VD);
4036
4037 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4038 TypeSourceInfo *TInfo,
4039 LookupResult &Previous,
4040 MultiTemplateParamsArg TemplateParamLists,
4041 bool &AddToScope);
4042
4043 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4044 /// and if so, check that it's a valid override and remember it.
4045 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4046
4047 /// Perform semantic checking of a new function declaration.
4048 ///
4049 /// Performs semantic analysis of the new function declaration
4050 /// NewFD. This routine performs all semantic checking that does not
4051 /// require the actual declarator involved in the declaration, and is
4052 /// used both for the declaration of functions as they are parsed
4053 /// (called via ActOnDeclarator) and for the declaration of functions
4054 /// that have been instantiated via C++ template instantiation (called
4055 /// via InstantiateDecl).
4056 ///
4057 /// \param IsMemberSpecialization whether this new function declaration is
4058 /// a member specialization (that replaces any definition provided by the
4059 /// previous declaration).
4060 ///
4061 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4062 ///
4063 /// \returns true if the function declaration is a redeclaration.
4064 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4065 LookupResult &Previous,
4066 bool IsMemberSpecialization, bool DeclIsDefn);
4067
4068 /// Checks if the new declaration declared in dependent context must be
4069 /// put in the same redeclaration chain as the specified declaration.
4070 ///
4071 /// \param D Declaration that is checked.
4072 /// \param PrevDecl Previous declaration found with proper lookup method for
4073 /// the same declaration name.
4074 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4075 /// belongs to.
4076 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4077
4078 /// Determines if we can perform a correct type check for \p D as a
4079 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4080 /// best-effort check.
4081 ///
4082 /// \param NewD The new declaration.
4083 /// \param OldD The old declaration.
4084 /// \param NewT The portion of the type of the new declaration to check.
4085 /// \param OldT The portion of the type of the old declaration to check.
4086 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4087 QualType NewT, QualType OldT);
4088 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4089 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4090
4091 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4092 /// containing class. Otherwise it will return implicit SectionAttr if the
4093 /// function is a definition and there is an active value on CodeSegStack
4094 /// (from the current #pragma code-seg value).
4095 ///
4096 /// \param FD Function being declared.
4097 /// \param IsDefinition Whether it is a definition or just a declaration.
4098 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4099 /// nullptr if no attribute should be added.
4100 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4101 bool IsDefinition);
4102
4103 /// Common checks for a parameter-declaration that should apply to both
4104 /// function parameters and non-type template parameters.
4105 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4106
4107 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4108 /// to introduce parameters into function prototype scope.
4109 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4110 SourceLocation ExplicitThisLoc = {});
4111
4112 /// Synthesizes a variable for a parameter arising from a
4113 /// typedef.
4114 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4115 QualType T);
4116 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4117 SourceLocation NameLoc,
4118 const IdentifierInfo *Name, QualType T,
4119 TypeSourceInfo *TSInfo, StorageClass SC);
4120
4121 /// Emit diagnostics if the initializer or any of its explicit or
4122 /// implicitly-generated subexpressions require copying or
4123 /// default-initializing a type that is or contains a C union type that is
4124 /// non-trivial to copy or default-initialize.
4125 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4126
4127 // These flags are passed to checkNonTrivialCUnion.
4128 enum NonTrivialCUnionKind {
4129 NTCUK_Init = 0x1,
4130 NTCUK_Destruct = 0x2,
4131 NTCUK_Copy = 0x4,
4132 };
4133
4134 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4135 /// a non-trivial C union is used in an invalid context.
4136 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4137 NonTrivialCUnionContext UseContext,
4138 unsigned NonTrivialKind);
4139
4140 /// Certain globally-unique variables might be accidentally duplicated if
4141 /// built into multiple shared libraries with hidden visibility. This can
4142 /// cause problems if the variable is mutable, its initialization is
4143 /// effectful, or its address is taken.
4144 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4145 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4146
4147 /// AddInitializerToDecl - Adds the initializer Init to the
4148 /// declaration dcl. If DirectInit is true, this is C++ direct
4149 /// initialization rather than copy initialization.
4150 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4151 void ActOnUninitializedDecl(Decl *dcl);
4152
4153 /// ActOnInitializerError - Given that there was an error parsing an
4154 /// initializer for the given declaration, try to at least re-establish
4155 /// invariants such as whether a variable's type is either dependent or
4156 /// complete.
4157 void ActOnInitializerError(Decl *Dcl);
4158
4159 void ActOnCXXForRangeDecl(Decl *D);
4160 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4161 IdentifierInfo *Ident,
4162 ParsedAttributes &Attrs);
4163
4164 /// Check if VD needs to be dllexport/dllimport due to being in a
4165 /// dllexport/import function.
4166 void CheckStaticLocalForDllExport(VarDecl *VD);
4167 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4168
4169 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4170 /// any semantic actions necessary after any initializer has been attached.
4171 void FinalizeDeclaration(Decl *D);
4172 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4173 ArrayRef<Decl *> Group);
4174
4175 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4176 /// group, performing any necessary semantic checking.
4177 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4178
4179 /// Should be called on all declarations that might have attached
4180 /// documentation comments.
4181 void ActOnDocumentableDecl(Decl *D);
4182 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4183
4184 enum class FnBodyKind {
4185 /// C++26 [dcl.fct.def.general]p1
4186 /// function-body:
4187 /// ctor-initializer[opt] compound-statement
4188 /// function-try-block
4189 Other,
4190 /// = default ;
4191 Default,
4192 /// deleted-function-body
4193 ///
4194 /// deleted-function-body:
4195 /// = delete ;
4196 /// = delete ( unevaluated-string ) ;
4197 Delete
4198 };
4199
4200 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4201 SourceLocation LocAfterDecls);
4202 void CheckForFunctionRedefinition(
4203 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4204 SkipBodyInfo *SkipBody = nullptr);
4205 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4206 MultiTemplateParamsArg TemplateParamLists,
4207 SkipBodyInfo *SkipBody = nullptr,
4208 FnBodyKind BodyKind = FnBodyKind::Other);
4209 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4210 SkipBodyInfo *SkipBody = nullptr,
4211 FnBodyKind BodyKind = FnBodyKind::Other);
4212 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4213
4214 /// Determine whether we can delay parsing the body of a function or
4215 /// function template until it is used, assuming we don't care about emitting
4216 /// code for that function.
4217 ///
4218 /// This will be \c false if we may need the body of the function in the
4219 /// middle of parsing an expression (where it's impractical to switch to
4220 /// parsing a different function), for instance, if it's constexpr in C++11
4221 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4222 bool canDelayFunctionBody(const Declarator &D);
4223
4224 /// Determine whether we can skip parsing the body of a function
4225 /// definition, assuming we don't care about analyzing its body or emitting
4226 /// code for that function.
4227 ///
4228 /// This will be \c false only if we may need the body of the function in
4229 /// order to parse the rest of the program (for instance, if it is
4230 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4231 bool canSkipFunctionBody(Decl *D);
4232
4233 /// Given the set of return statements within a function body,
4234 /// compute the variables that are subject to the named return value
4235 /// optimization.
4236 ///
4237 /// Each of the variables that is subject to the named return value
4238 /// optimization will be marked as NRVO variables in the AST, and any
4239 /// return statement that has a marked NRVO variable as its NRVO candidate can
4240 /// use the named return value optimization.
4241 ///
4242 /// This function applies a very simplistic algorithm for NRVO: if every
4243 /// return statement in the scope of a variable has the same NRVO candidate,
4244 /// that candidate is an NRVO variable.
4245 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4246
4247 /// Performs semantic analysis at the end of a function body.
4248 ///
4249 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4250 /// releasing the associated \p FunctionScopeInfo. This is useful when
4251 /// building e.g. LambdaExprs.
4252 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4253 bool IsInstantiation = false,
4254 bool RetainFunctionScopeInfo = false);
4255 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4256 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4257
4258 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4259 /// attribute for which parsing is delayed.
4260 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4261
4262 /// Diagnose any unused parameters in the given sequence of
4263 /// ParmVarDecl pointers.
4264 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4265
4266 /// Diagnose whether the size of parameters or return value of a
4267 /// function or obj-c method definition is pass-by-value and larger than a
4268 /// specified threshold.
4269 void
4270 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4271 QualType ReturnTy, NamedDecl *D);
4272
4273 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4274 SourceLocation RParenLoc);
4275
4276 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4277 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4278
4279 void ActOnPopScope(SourceLocation Loc, Scope *S);
4280
4281 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4282 /// no declarator (e.g. "struct foo;") is parsed.
4283 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4284 const ParsedAttributesView &DeclAttrs,
4285 RecordDecl *&AnonRecord);
4286
4287 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4288 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4289 /// parameters to cope with template friend declarations.
4290 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4291 const ParsedAttributesView &DeclAttrs,
4292 MultiTemplateParamsArg TemplateParams,
4293 bool IsExplicitInstantiation,
4294 RecordDecl *&AnonRecord,
4295 SourceLocation EllipsisLoc = {});
4296
4297 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4298 /// anonymous structure or union. Anonymous unions are a C++ feature
4299 /// (C++ [class.union]) and a C11 feature; anonymous structures
4300 /// are a C11 feature and GNU C++ extension.
4301 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4302 RecordDecl *Record,
4303 const PrintingPolicy &Policy);
4304
4305 /// Called once it is known whether
4306 /// a tag declaration is an anonymous union or struct.
4307 void ActOnDefinedDeclarationSpecifier(Decl *D);
4308
4309 /// Emit diagnostic warnings for placeholder members.
4310 /// We can only do that after the class is fully constructed,
4311 /// as anonymous union/structs can insert placeholders
4312 /// in their parent scope (which might be a Record).
4313 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4314
4315 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4316 /// Microsoft C anonymous structure.
4317 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4318 /// Example:
4319 ///
4320 /// struct A { int a; };
4321 /// struct B { struct A; int b; };
4322 ///
4323 /// void foo() {
4324 /// B var;
4325 /// var.a = 3;
4326 /// }
4327 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4328 RecordDecl *Record);
4329
4330 /// Given a non-tag type declaration, returns an enum useful for indicating
4331 /// what kind of non-tag type this is.
4332 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4333
4334 /// Determine whether a tag with a given kind is acceptable
4335 /// as a redeclaration of the given tag declaration.
4336 ///
4337 /// \returns true if the new tag kind is acceptable, false otherwise.
4338 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4339 bool isDefinition, SourceLocation NewTagLoc,
4340 const IdentifierInfo *Name);
4341
4342 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4343 /// former case, Name will be non-null. In the later case, Name will be null.
4344 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4345 /// a reference/declaration/definition of a tag.
4346 ///
4347 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4348 /// trailing-type-specifier) other than one in an alias-declaration.
4349 ///
4350 /// \param SkipBody If non-null, will be set to indicate if the caller should
4351 /// skip the definition of this tag and treat it as if it were a declaration.
4352 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4353 SourceLocation KWLoc, CXXScopeSpec &SS,
4354 IdentifierInfo *Name, SourceLocation NameLoc,
4355 const ParsedAttributesView &Attr, AccessSpecifier AS,
4356 SourceLocation ModulePrivateLoc,
4357 MultiTemplateParamsArg TemplateParameterLists,
4358 bool &OwnedDecl, bool &IsDependent,
4359 SourceLocation ScopedEnumKWLoc,
4360 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4361 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4362 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4363
4364 /// ActOnField - Each field of a C struct/union is passed into this in order
4365 /// to create a FieldDecl object for it.
4366 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4367 Declarator &D, Expr *BitfieldWidth);
4368
4369 /// HandleField - Analyze a field of a C struct or a C++ data member.
4370 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4371 Declarator &D, Expr *BitfieldWidth,
4372 InClassInitStyle InitStyle, AccessSpecifier AS);
4373
4374 /// Build a new FieldDecl and check its well-formedness.
4375 ///
4376 /// This routine builds a new FieldDecl given the fields name, type,
4377 /// record, etc. \p PrevDecl should refer to any previous declaration
4378 /// with the same name and in the same scope as the field to be
4379 /// created.
4380 ///
4381 /// \returns a new FieldDecl.
4382 ///
4383 /// \todo The Declarator argument is a hack. It will be removed once
4384 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4385 TypeSourceInfo *TInfo, RecordDecl *Record,
4386 SourceLocation Loc, bool Mutable,
4387 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4388 SourceLocation TSSL, AccessSpecifier AS,
4389 NamedDecl *PrevDecl, Declarator *D = nullptr);
4390
4391 bool CheckNontrivialField(FieldDecl *FD);
4392
4393 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4394 /// class and class extensions. For every class \@interface and class
4395 /// extension \@interface, if the last ivar is a bitfield of any type,
4396 /// then add an implicit `char :0` ivar to the end of that interface.
4397 void ActOnLastBitfield(SourceLocation DeclStart,
4398 SmallVectorImpl<Decl *> &AllIvarDecls);
4399
4400 // This is used for both record definitions and ObjC interface declarations.
4401 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4402 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4403 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4404
4405 /// ActOnTagStartDefinition - Invoked when we have entered the
4406 /// scope of a tag's definition (e.g., for an enumeration, class,
4407 /// struct, or union).
4408 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4409
4410 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4411 /// Differently from C++, actually parse the body and reject / error out
4412 /// in case of a structural mismatch.
4413 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4414
4415 typedef void *SkippedDefinitionContext;
4416
4417 /// Invoked when we enter a tag definition that we're skipping.
4418 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4419
4420 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4421 /// C++ record definition's base-specifiers clause and are starting its
4422 /// member declarations.
4423 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4424 SourceLocation FinalLoc,
4425 bool IsFinalSpelledSealed,
4426 bool IsAbstract,
4427 SourceLocation LBraceLoc);
4428
4429 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4430 /// the definition of a tag (enumeration, class, struct, or union).
4431 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4432 SourceRange BraceRange);
4433
4434 ASTContext::CXXRecordDeclRelocationInfo
4435 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4436
4437 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4438
4439 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4440 /// error parsing the definition of a tag.
4441 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4442
4443 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4444 EnumConstantDecl *LastEnumConst,
4445 SourceLocation IdLoc, IdentifierInfo *Id,
4446 Expr *val);
4447
4448 /// Check that this is a valid underlying type for an enum declaration.
4449 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4450
4451 /// Check whether this is a valid redeclaration of a previous enumeration.
4452 /// \return true if the redeclaration was invalid.
4453 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4454 QualType EnumUnderlyingTy, bool IsFixed,
4455 const EnumDecl *Prev);
4456
4457 /// Determine whether the body of an anonymous enumeration should be skipped.
4458 /// \param II The name of the first enumerator.
4459 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4460 SourceLocation IILoc);
4461
4462 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4463 SourceLocation IdLoc, IdentifierInfo *Id,
4464 const ParsedAttributesView &Attrs,
4465 SourceLocation EqualLoc, Expr *Val,
4466 SkipBodyInfo *SkipBody = nullptr);
4467 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4468 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4469 const ParsedAttributesView &Attr);
4470
4471 /// Set the current declaration context until it gets popped.
4472 void PushDeclContext(Scope *S, DeclContext *DC);
4473 void PopDeclContext();
4474
4475 /// EnterDeclaratorContext - Used when we must lookup names in the context
4476 /// of a declarator's nested name specifier.
4477 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4478 void ExitDeclaratorContext(Scope *S);
4479
4480 /// Enter a template parameter scope, after it's been associated with a
4481 /// particular DeclContext. Causes lookup within the scope to chain through
4482 /// enclosing contexts in the correct order.
4483 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4484
4485 /// Push the parameters of D, which must be a function, into scope.
4486 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4487 void ActOnExitFunctionContext();
4488
4489 /// Add this decl to the scope shadowed decl chains.
4490 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4491
4492 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4493 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4494 /// true if 'D' belongs to the given declaration context.
4495 ///
4496 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4497 /// enclosing namespace set of the context, rather than contained
4498 /// directly within it.
4499 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4500 bool AllowInlineNamespace = false) const;
4501
4502 /// Finds the scope corresponding to the given decl context, if it
4503 /// happens to be an enclosing scope. Otherwise return NULL.
4504 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4505
4506 /// Subroutines of ActOnDeclarator().
4507 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4508 TypeSourceInfo *TInfo);
4509 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4510
4511 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4512 void mergeDeclAttributes(
4513 NamedDecl *New, Decl *Old,
4514 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4515
4516 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4517 /// requires the type to be deduced.
4518 void CheckAttributesOnDeducedType(Decl *D);
4519
4520 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4521 /// same name and scope as a previous declaration 'Old'. Figure out
4522 /// how to resolve this situation, merging decls or emitting
4523 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4524 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4525 LookupResult &OldDecls);
4526
4527 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4528 /// definition visible.
4529 /// This method performs any necessary cleanup on the parser state to discard
4530 /// child nodes from newly parsed decl we are retiring.
4531 void CleanupMergedEnum(Scope *S, Decl *New);
4532
4533 /// MergeFunctionDecl - We just parsed a function 'New' from
4534 /// declarator D which has the same name and scope as a previous
4535 /// declaration 'Old'. Figure out how to resolve this situation,
4536 /// merging decls or emitting diagnostics as appropriate.
4537 ///
4538 /// In C++, New and Old must be declarations that are not
4539 /// overloaded. Use IsOverload to determine whether New and Old are
4540 /// overloaded, and to select the Old declaration that New should be
4541 /// merged with.
4542 ///
4543 /// Returns true if there was an error, false otherwise.
4544 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4545 bool MergeTypeWithOld, bool NewDeclIsDefn);
4546
4547 /// Completes the merge of two function declarations that are
4548 /// known to be compatible.
4549 ///
4550 /// This routine handles the merging of attributes and other
4551 /// properties of function declarations from the old declaration to
4552 /// the new declaration, once we know that New is in fact a
4553 /// redeclaration of Old.
4554 ///
4555 /// \returns false
4556 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4557 Scope *S, bool MergeTypeWithOld);
4558 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4559
4560 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4561 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4562 /// situation, merging decls or emitting diagnostics as appropriate.
4563 ///
4564 /// Tentative definition rules (C99 6.9.2p2) are checked by
4565 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4566 /// definitions here, since the initializer hasn't been attached.
4567 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4568
4569 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4570 /// scope as a previous declaration 'Old'. Figure out how to merge their
4571 /// types, emitting diagnostics as appropriate.
4572 ///
4573 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4574 /// back to here in AddInitializerToDecl. We can't check them before the
4575 /// initializer is attached.
4576 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4577
4578 /// We've just determined that \p Old and \p New both appear to be definitions
4579 /// of the same variable. Either diagnose or fix the problem.
4580 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4581 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4582
4583 /// Filters out lookup results that don't fall within the given scope
4584 /// as determined by isDeclInScope.
4585 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4586 bool ConsiderLinkage, bool AllowInlineNamespace);
4587
4588 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4589 /// have compatible owning modules.
4590 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4591
4592 /// [module.interface]p6:
4593 /// A redeclaration of an entity X is implicitly exported if X was introduced
4594 /// by an exported declaration; otherwise it shall not be exported.
4595 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4596
4597 /// A wrapper function for checking the semantic restrictions of
4598 /// a redeclaration within a module.
4599 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4600
4601 /// Check the redefinition in C++20 Modules.
4602 ///
4603 /// [basic.def.odr]p14:
4604 /// For any definable item D with definitions in multiple translation units,
4605 /// - if D is a non-inline non-templated function or variable, or
4606 /// - if the definitions in different translation units do not satisfy the
4607 /// following requirements,
4608 /// the program is ill-formed; a diagnostic is required only if the
4609 /// definable item is attached to a named module and a prior definition is
4610 /// reachable at the point where a later definition occurs.
4611 /// - Each such definition shall not be attached to a named module
4612 /// ([module.unit]).
4613 /// - Each such definition shall consist of the same sequence of tokens, ...
4614 /// ...
4615 ///
4616 /// Return true if the redefinition is not allowed. Return false otherwise.
4617 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4618
4619 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4620
4621 /// If it's a file scoped decl that must warn if not used, keep track
4622 /// of it.
4623 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4624
4625 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4626 DiagReceiverTy;
4627
4628 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4629 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4630 DiagReceiverTy DiagReceiver);
4631 void DiagnoseUnusedDecl(const NamedDecl *ND);
4632
4633 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4634 /// unless they are marked attr(unused).
4635 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4636
4637 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4638 /// variable.
4639 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4640
4641 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4642 /// from S, where a non-field would be declared. This routine copes
4643 /// with the difference between C and C++ scoping rules in structs and
4644 /// unions. For example, the following code is well-formed in C but
4645 /// ill-formed in C++:
4646 /// @code
4647 /// struct S6 {
4648 /// enum { BAR } e;
4649 /// };
4650 ///
4651 /// void test_S6() {
4652 /// struct S6 a;
4653 /// a.e = BAR;
4654 /// }
4655 /// @endcode
4656 /// For the declaration of BAR, this routine will return a different
4657 /// scope. The scope S will be the scope of the unnamed enumeration
4658 /// within S6. In C++, this routine will return the scope associated
4659 /// with S6, because the enumeration's scope is a transparent
4660 /// context but structures can contain non-field names. In C, this
4661 /// routine will return the translation unit scope, since the
4662 /// enumeration's scope is a transparent context and structures cannot
4663 /// contain non-field names.
4664 Scope *getNonFieldDeclScope(Scope *S);
4665
4666 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4667 SourceLocation Loc);
4668
4669 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4670 /// file scope. lazily create a decl for it. ForRedeclaration is true
4671 /// if we're creating this built-in in anticipation of redeclaring the
4672 /// built-in.
4673 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4674 bool ForRedeclaration, SourceLocation Loc);
4675
4676 /// Get the outermost AttributedType node that sets a calling convention.
4677 /// Valid types should not have multiple attributes with different CCs.
4678 const AttributedType *getCallingConvAttributedType(QualType T) const;
4679
4680 /// GetNameForDeclarator - Determine the full declaration name for the
4681 /// given Declarator.
4682 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4683
4684 /// Retrieves the declaration name from a parsed unqualified-id.
4685 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4686
4687 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4688 /// we are currently parsing the initializer.
4689 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4690
4691 /// Look for a locally scoped extern "C" declaration by the given name.
4692 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4693
4694 void deduceOpenCLAddressSpace(VarDecl *decl);
4695 void deduceHLSLAddressSpace(VarDecl *decl);
4696
4697 /// Adjust the \c DeclContext for a function or variable that might be a
4698 /// function-local external declaration.
4699 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4700
4701 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4702
4703 /// Checks if the variant/multiversion functions are compatible.
4704 bool areMultiversionVariantFunctionsCompatible(
4705 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4706 const PartialDiagnostic &NoProtoDiagID,
4707 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4708 const PartialDiagnosticAt &NoSupportDiagIDAt,
4709 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4710 bool ConstexprSupported, bool CLinkageMayDiffer);
4711
4712 /// type checking declaration initializers (C99 6.7.8)
4713 bool CheckForConstantInitializer(
4714 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4715
4716 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4717 QualType Type, TypeSourceInfo *TSI,
4718 SourceRange Range, bool DirectInit,
4719 Expr *Init);
4720
4721 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4722 Expr *Init);
4723
4724 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4725
4726 // Heuristically tells if the function is `get_return_object` member of a
4727 // coroutine promise_type by matching the function name.
4728 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4729 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4730
4731 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4732 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4733 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4734 Scope *S);
4735
4736 /// If this function is a C++ replaceable global allocation function
4737 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4738 /// adds any function attributes that we know a priori based on the standard.
4739 ///
4740 /// We need to check for duplicate attributes both here and where user-written
4741 /// attributes are applied to declarations.
4742 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4743 FunctionDecl *FD);
4744
4745 /// Adds any function attributes that we know a priori based on
4746 /// the declaration of this function.
4747 ///
4748 /// These attributes can apply both to implicitly-declared builtins
4749 /// (like __builtin___printf_chk) or to library-declared functions
4750 /// like NSLog or printf.
4751 ///
4752 /// We need to check for duplicate attributes both here and where user-written
4753 /// attributes are applied to declarations.
4754 void AddKnownFunctionAttributes(FunctionDecl *FD);
4755
4756 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4757 /// the correct width, and that the field type is valid.
4758 /// Returns false on success.
4759 ExprResult VerifyBitField(SourceLocation FieldLoc,
4760 const IdentifierInfo *FieldName, QualType FieldTy,
4761 bool IsMsStruct, Expr *BitWidth);
4762
4763 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4764 /// enum. If AllowMask is true, then we also allow the complement of a valid
4765 /// value, to be used as a mask.
4766 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4767 bool AllowMask) const;
4768
4769 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4770 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4771 SourceLocation WeakNameLoc);
4772
4773 /// ActOnPragmaRedefineExtname - Called on well formed
4774 /// \#pragma redefine_extname oldname newname.
4775 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4776 IdentifierInfo *AliasName,
4777 SourceLocation PragmaLoc,
4778 SourceLocation WeakNameLoc,
4779 SourceLocation AliasNameLoc);
4780
4781 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4782 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4783 SourceLocation PragmaLoc,
4784 SourceLocation WeakNameLoc,
4785 SourceLocation AliasNameLoc);
4786
4787 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4788 enum class FunctionEmissionStatus {
4789 Emitted,
4790 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4791 OMPDiscarded, // Discarded due to OpenMP hostness
4792 TemplateDiscarded, // Discarded due to uninstantiated templates
4793 Unknown,
4794 };
4795 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4796 bool Final = false);
4797
4798 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4799 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4800
4801 /// Function or variable declarations to be checked for whether the deferred
4802 /// diagnostics should be emitted.
4803 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4804
4805private:
4806 /// Map of current shadowing declarations to shadowed declarations. Warn if
4807 /// it looks like the user is trying to modify the shadowing declaration.
4808 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4809
4810 // We need this to handle
4811 //
4812 // typedef struct {
4813 // void *foo() { return 0; }
4814 // } A;
4815 //
4816 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4817 // for example. If 'A', foo will have external linkage. If we have '*A',
4818 // foo will have no linkage. Since we can't know until we get to the end
4819 // of the typedef, this function finds out if D might have non-external
4820 // linkage. Callers should verify at the end of the TU if it D has external
4821 // linkage or not.
4822 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4823
4824#include "clang/Sema/AttrIsTypeDependent.inc"
4825
4826 ///@}
4827
4828 //
4829 //
4830 // -------------------------------------------------------------------------
4831 //
4832 //
4833
4834 /// \name Declaration Attribute Handling
4835 /// Implementations are in SemaDeclAttr.cpp
4836 ///@{
4837
4838public:
4839 /// Describes the kind of priority given to an availability attribute.
4840 ///
4841 /// The sum of priorities deteremines the final priority of the attribute.
4842 /// The final priority determines how the attribute will be merged.
4843 /// An attribute with a lower priority will always remove higher priority
4844 /// attributes for the specified platform when it is being applied. An
4845 /// attribute with a higher priority will not be applied if the declaration
4846 /// already has an availability attribute with a lower priority for the
4847 /// specified platform. The final prirority values are not expected to match
4848 /// the values in this enumeration, but instead should be treated as a plain
4849 /// integer value. This enumeration just names the priority weights that are
4850 /// used to calculate that final vaue.
4851 enum AvailabilityPriority : int {
4852 /// The availability attribute was specified explicitly next to the
4853 /// declaration.
4854 AP_Explicit = 0,
4855
4856 /// The availability attribute was applied using '#pragma clang attribute'.
4857 AP_PragmaClangAttribute = 1,
4858
4859 /// The availability attribute for a specific platform was inferred from
4860 /// an availability attribute for another platform.
4861 AP_InferredFromOtherPlatform = 2
4862 };
4863
4864 /// Describes the reason a calling convention specification was ignored, used
4865 /// for diagnostics.
4866 enum class CallingConventionIgnoredReason {
4867 ForThisTarget = 0,
4868 VariadicFunction,
4869 ConstructorDestructor,
4870 BuiltinFunction
4871 };
4872
4873 /// A helper function to provide Attribute Location for the Attr types
4874 /// AND the ParsedAttr.
4875 template <typename AttrInfo>
4876 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4877 getAttrLoc(const AttrInfo &AL) {
4878 return AL.getLocation();
4879 }
4880 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4881
4882 /// If Expr is a valid integer constant, get the value of the integer
4883 /// expression and return success or failure. May output an error.
4884 ///
4885 /// Negative argument is implicitly converted to unsigned, unless
4886 /// \p StrictlyUnsigned is true.
4887 template <typename AttrInfo>
4888 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4889 unsigned Idx = UINT_MAX,
4890 bool StrictlyUnsigned = false) {
4891 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4892 if (Expr->isTypeDependent() ||
4893 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
4894 if (Idx != UINT_MAX)
4895 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4896 << &AI << Idx << AANT_ArgumentIntegerConstant
4897 << Expr->getSourceRange();
4898 else
4899 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4900 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4901 return false;
4902 }
4903
4904 if (!I->isIntN(N: 32)) {
4905 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
4906 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
4907 return false;
4908 }
4909
4910 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4911 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4912 << &AI << /*non-negative*/ 1;
4913 return false;
4914 }
4915
4916 Val = (uint32_t)I->getZExtValue();
4917 return true;
4918 }
4919
4920 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4921 /// \#pragma weak during processing of other Decls.
4922 /// I couldn't figure out a clean way to generate these in-line, so
4923 /// we store them here and handle separately -- which is a hack.
4924 /// It would be best to refactor this.
4925 SmallVector<Decl *, 2> WeakTopLevelDecl;
4926
4927 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4928 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
4929
4930 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
4931 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
4932 ExtVectorDeclsType;
4933
4934 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4935 /// us to associate a raw vector type with one of the ext_vector type names.
4936 /// This is only necessary for issuing pretty diagnostics.
4937 ExtVectorDeclsType ExtVectorDecls;
4938
4939 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4940 /// and return false, otherwise set \p Str to the value of the string literal
4941 /// and return true.
4942 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4943 const Expr *E, StringRef &Str,
4944 SourceLocation *ArgLocation = nullptr);
4945
4946 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4947 /// If not emit an error and return false. If the argument is an identifier it
4948 /// will emit an error with a fixit hint and treat it as if it was a string
4949 /// literal.
4950 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4951 StringRef &Str,
4952 SourceLocation *ArgLocation = nullptr);
4953
4954 /// Determine if type T is a valid subject for a nonnull and similar
4955 /// attributes. Dependent types are considered valid so they can be checked
4956 /// during instantiation time. By default, we look through references (the
4957 /// behavior used by nonnull), but if the second parameter is true, then we
4958 /// treat a reference type as valid.
4959 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4960
4961 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4962 /// declaration.
4963 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4964 Expr *OE);
4965
4966 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4967 /// declaration.
4968 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4969 Expr *ParamExpr);
4970
4971 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4972 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4973
4974 AvailabilityAttr *
4975 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
4976 const IdentifierInfo *Platform, bool Implicit,
4977 VersionTuple Introduced, VersionTuple Deprecated,
4978 VersionTuple Obsoleted, bool IsUnavailable,
4979 StringRef Message, bool IsStrict, StringRef Replacement,
4980 AvailabilityMergeKind AMK, int Priority,
4981 const IdentifierInfo *IIEnvironment);
4982
4983 TypeVisibilityAttr *
4984 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
4985 TypeVisibilityAttr::VisibilityType Vis);
4986 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
4987 VisibilityAttr::VisibilityType Vis);
4988 void mergeVisibilityType(Decl *D, SourceLocation Loc,
4989 VisibilityAttr::VisibilityType Type);
4990 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
4991 StringRef Name);
4992
4993 /// Used to implement to perform semantic checking on
4994 /// attribute((section("foo"))) specifiers.
4995 ///
4996 /// In this case, "foo" is passed in to be checked. If the section
4997 /// specifier is invalid, return an Error that indicates the problem.
4998 ///
4999 /// This is a simple quality of implementation feature to catch errors
5000 /// and give good diagnostics in cases when the assembler or code generator
5001 /// would otherwise reject the section specifier.
5002 llvm::Error isValidSectionSpecifier(StringRef Str);
5003 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5004 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5005 StringRef Name);
5006
5007 // Check for things we'd like to warn about. Multiversioning issues are
5008 // handled later in the process, once we know how many exist.
5009 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5010
5011 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5012 StringRef NewUserDiagnostic);
5013 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5014 const IdentifierInfo *Format, int FormatIdx,
5015 int FirstArg);
5016 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5017 const AttributeCommonInfo &CI,
5018 const IdentifierInfo *Format,
5019 int FormatIdx,
5020 StringLiteral *FormatStr);
5021 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5022 const AttributeCommonInfo &CI,
5023 const IdentifierInfo *ModularImplFn,
5024 StringRef ImplName,
5025 MutableArrayRef<StringRef> Aspects);
5026
5027 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5028 const AttributeCommonInfo &CI);
5029
5030 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5031 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5032 bool IsPackExpansion);
5033 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5034 bool IsPackExpansion);
5035
5036 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5037 /// declaration.
5038 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5039
5040 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5041 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5042 MutableArrayRef<Expr *> Args);
5043 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5044
5045 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5046 bool BestCase,
5047 MSInheritanceModel SemanticSpelling);
5048
5049 void CheckAlignasUnderalignment(Decl *D);
5050
5051 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5052 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5053 const IdentifierInfo *Name, bool InInstantiation = false);
5054 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5055 const AttributeCommonInfo &CI,
5056 const IdentifierInfo *Ident);
5057 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5058 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5059 const AttributeCommonInfo &CI);
5060 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5061 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5062 const InternalLinkageAttr &AL);
5063
5064 /// Check validaty of calling convention attribute \p attr. If \p FD
5065 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5066 /// target. Otherwise, it is specified by \p CFT.
5067 bool CheckCallingConvAttr(
5068 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5069 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5070
5071 /// Checks a regparm attribute, returning true if it is ill-formed and
5072 /// otherwise setting numParams to the appropriate value.
5073 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5074
5075 /// Create an CUDALaunchBoundsAttr attribute.
5076 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5077 Expr *MaxThreads,
5078 Expr *MinBlocks,
5079 Expr *MaxBlocks);
5080
5081 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5082 /// declaration.
5083 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5084 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5085
5086 /// Add a cluster_dims attribute to a particular declaration.
5087 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5088 Expr *X, Expr *Y, Expr *Z);
5089 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5090 Expr *Y, Expr *Z);
5091 /// Add a no_cluster attribute to a particular declaration.
5092 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5093
5094 enum class RetainOwnershipKind { NS, CF, OS };
5095
5096 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5097 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5098
5099 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5100
5101 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5102 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5103 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5104 const AttributeCommonInfo &CI,
5105 bool BestCase,
5106 MSInheritanceModel Model);
5107
5108 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5109 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5110 const EnforceTCBLeafAttr &AL);
5111
5112 /// Helper for delayed processing TransparentUnion or
5113 /// BPFPreserveAccessIndexAttr attribute.
5114 void ProcessDeclAttributeDelayed(Decl *D,
5115 const ParsedAttributesView &AttrList);
5116
5117 // Options for ProcessDeclAttributeList().
5118 struct ProcessDeclAttributeOptions {
5119 ProcessDeclAttributeOptions()
5120 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5121
5122 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5123 ProcessDeclAttributeOptions Result = *this;
5124 Result.IncludeCXX11Attributes = Val;
5125 return Result;
5126 }
5127
5128 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5129 ProcessDeclAttributeOptions Result = *this;
5130 Result.IgnoreTypeAttributes = Val;
5131 return Result;
5132 }
5133
5134 // Should C++11 attributes be processed?
5135 bool IncludeCXX11Attributes;
5136
5137 // Should any type attributes encountered be ignored?
5138 // If this option is false, a diagnostic will be emitted for any type
5139 // attributes of a kind that does not "slide" from the declaration to
5140 // the decl-specifier-seq.
5141 bool IgnoreTypeAttributes;
5142 };
5143
5144 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5145 /// attribute list to the specified decl, ignoring any type attributes.
5146 void ProcessDeclAttributeList(Scope *S, Decl *D,
5147 const ParsedAttributesView &AttrList,
5148 const ProcessDeclAttributeOptions &Options =
5149 ProcessDeclAttributeOptions());
5150
5151 /// Annotation attributes are the only attributes allowed after an access
5152 /// specifier.
5153 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5154 const ParsedAttributesView &AttrList);
5155
5156 /// checkUnusedDeclAttributes - Given a declarator which is not being
5157 /// used to build a declaration, complain about any decl attributes
5158 /// which might be lying around on it.
5159 void checkUnusedDeclAttributes(Declarator &D);
5160
5161 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5162
5163 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5164 /// \#pragma weak needs a non-definition decl and source may not have one.
5165 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5166 SourceLocation Loc);
5167
5168 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5169 /// applied to it, possibly with an alias.
5170 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5171
5172 void ProcessPragmaWeak(Scope *S, Decl *D);
5173 // Decl attributes - this routine is the top level dispatcher.
5174 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5175
5176 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5177
5178 /// Given a set of delayed diagnostics, re-emit them as if they had
5179 /// been delayed in the current context instead of in the given pool.
5180 /// Essentially, this just moves them to the current pool.
5181 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5182
5183 /// Check that the type is a plain record with one field being a pointer
5184 /// type and the other field being an integer. This matches the common
5185 /// implementation of std::span or sized_allocation_t in P0901R11.
5186 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5187
5188 /// Check if IdxExpr is a valid parameter index for a function or
5189 /// instance method D. May output an error.
5190 ///
5191 /// \returns true if IdxExpr is a valid index.
5192 template <typename AttrInfo>
5193 bool checkFunctionOrMethodParameterIndex(
5194 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5195 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5196 bool CanIndexVariadicArguments = false) {
5197 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5198
5199 // In C++ the implicit 'this' function parameter also counts.
5200 // Parameters are counted from one.
5201 bool HP = hasFunctionProto(D);
5202 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5203 bool IV = HP && isFunctionOrMethodVariadic(D);
5204 unsigned NumParams =
5205 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5206
5207 std::optional<llvm::APSInt> IdxInt;
5208 if (IdxExpr->isTypeDependent() ||
5209 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5210 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5211 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5212 << IdxExpr->getSourceRange();
5213 return false;
5214 }
5215
5216 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5217 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5218 if (IdxSource < 1 || IdxSource == Limit ||
5219 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5220 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5221 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5222 return false;
5223 }
5224 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5225 if (IdxSource == 1) {
5226 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5227 << &AI << IdxExpr->getSourceRange();
5228 return false;
5229 }
5230 }
5231
5232 Idx = ParamIdx(IdxSource, D);
5233 return true;
5234 }
5235
5236 ///@}
5237
5238 //
5239 //
5240 // -------------------------------------------------------------------------
5241 //
5242 //
5243
5244 /// \name C++ Declarations
5245 /// Implementations are in SemaDeclCXX.cpp
5246 ///@{
5247
5248public:
5249 void CheckDelegatingCtorCycles();
5250
5251 /// Called before parsing a function declarator belonging to a function
5252 /// declaration.
5253 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5254 unsigned TemplateParameterDepth);
5255
5256 /// Called after parsing a function declarator belonging to a function
5257 /// declaration.
5258 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5259
5260 // Act on C++ namespaces
5261 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5262 SourceLocation NamespaceLoc,
5263 SourceLocation IdentLoc, IdentifierInfo *Ident,
5264 SourceLocation LBrace,
5265 const ParsedAttributesView &AttrList,
5266 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5267
5268 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5269 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5270 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5271
5272 NamespaceDecl *getStdNamespace() const;
5273
5274 /// Retrieve the special "std" namespace, which may require us to
5275 /// implicitly define the namespace.
5276 NamespaceDecl *getOrCreateStdNamespace();
5277
5278 CXXRecordDecl *getStdBadAlloc() const;
5279 EnumDecl *getStdAlignValT() const;
5280
5281 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5282 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5283 QualType AllocType, SourceLocation);
5284
5285 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5286 const IdentifierInfo *MemberOrBase);
5287
5288 enum class ComparisonCategoryUsage {
5289 /// The '<=>' operator was used in an expression and a builtin operator
5290 /// was selected.
5291 OperatorInExpression,
5292 /// A defaulted 'operator<=>' needed the comparison category. This
5293 /// typically only applies to 'std::strong_ordering', due to the implicit
5294 /// fallback return value.
5295 DefaultedOperator,
5296 };
5297
5298 /// Lookup the specified comparison category types in the standard
5299 /// library, an check the VarDecls possibly returned by the operator<=>
5300 /// builtins for that type.
5301 ///
5302 /// \return The type of the comparison category type corresponding to the
5303 /// specified Kind, or a null type if an error occurs
5304 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5305 SourceLocation Loc,
5306 ComparisonCategoryUsage Usage);
5307
5308 /// Tests whether Ty is an instance of std::initializer_list and, if
5309 /// it is and Element is not NULL, assigns the element type to Element.
5310 bool isStdInitializerList(QualType Ty, QualType *Element);
5311
5312 /// Tests whether Ty is an instance of std::type_identity and, if
5313 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5314 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5315 /// incorrectly structured despite having the correct name, the faulty Decl
5316 /// will be assigned to MalformedDecl.
5317 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5318 const Decl **MalformedDecl = nullptr);
5319
5320 /// Looks for the std::initializer_list template and instantiates it
5321 /// with Element, or emits an error if it's not found.
5322 ///
5323 /// \returns The instantiated template, or null on error.
5324 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5325
5326 /// Looks for the std::type_identity template and instantiates it
5327 /// with Type, or returns a null type if type_identity has not been declared
5328 ///
5329 /// \returns The instantiated template, or null if std::type_identity is not
5330 /// declared
5331 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5332
5333 /// Determine whether Ctor is an initializer-list constructor, as
5334 /// defined in [dcl.init.list]p2.
5335 bool isInitListConstructor(const FunctionDecl *Ctor);
5336
5337 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5338 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5339 SourceLocation IdentLoc,
5340 IdentifierInfo *NamespcName,
5341 const ParsedAttributesView &AttrList);
5342
5343 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5344
5345 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5346 SourceLocation AliasLoc, IdentifierInfo *Alias,
5347 CXXScopeSpec &SS, SourceLocation IdentLoc,
5348 IdentifierInfo *Ident);
5349
5350 /// Remove decls we can't actually see from a lookup being used to declare
5351 /// shadow using decls.
5352 ///
5353 /// \param S - The scope of the potential shadow decl
5354 /// \param Previous - The lookup of a potential shadow decl's name.
5355 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5356
5357 /// Hides a using shadow declaration. This is required by the current
5358 /// using-decl implementation when a resolvable using declaration in a
5359 /// class is followed by a declaration which would hide or override
5360 /// one or more of the using decl's targets; for example:
5361 ///
5362 /// struct Base { void foo(int); };
5363 /// struct Derived : Base {
5364 /// using Base::foo;
5365 /// void foo(int);
5366 /// };
5367 ///
5368 /// The governing language is C++03 [namespace.udecl]p12:
5369 ///
5370 /// When a using-declaration brings names from a base class into a
5371 /// derived class scope, member functions in the derived class
5372 /// override and/or hide member functions with the same name and
5373 /// parameter types in a base class (rather than conflicting).
5374 ///
5375 /// There are two ways to implement this:
5376 /// (1) optimistically create shadow decls when they're not hidden
5377 /// by existing declarations, or
5378 /// (2) don't create any shadow decls (or at least don't make them
5379 /// visible) until we've fully parsed/instantiated the class.
5380 /// The problem with (1) is that we might have to retroactively remove
5381 /// a shadow decl, which requires several O(n) operations because the
5382 /// decl structures are (very reasonably) not designed for removal.
5383 /// (2) avoids this but is very fiddly and phase-dependent.
5384 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5385
5386 /// Determines whether to create a using shadow decl for a particular
5387 /// decl, given the set of decls existing prior to this using lookup.
5388 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5389 const LookupResult &PreviousDecls,
5390 UsingShadowDecl *&PrevShadow);
5391
5392 /// Builds a shadow declaration corresponding to a 'using' declaration.
5393 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5394 NamedDecl *Target,
5395 UsingShadowDecl *PrevDecl);
5396
5397 /// Checks that the given using declaration is not an invalid
5398 /// redeclaration. Note that this is checking only for the using decl
5399 /// itself, not for any ill-formedness among the UsingShadowDecls.
5400 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5401 bool HasTypenameKeyword,
5402 const CXXScopeSpec &SS,
5403 SourceLocation NameLoc,
5404 const LookupResult &Previous);
5405
5406 /// Checks that the given nested-name qualifier used in a using decl
5407 /// in the current context is appropriately related to the current
5408 /// scope. If an error is found, diagnoses it and returns true.
5409 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5410 /// the result of that lookup. UD is likewise nullptr, except when we have an
5411 /// already-populated UsingDecl whose shadow decls contain the same
5412 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5413 /// scope).
5414 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5415 const CXXScopeSpec &SS,
5416 const DeclarationNameInfo &NameInfo,
5417 SourceLocation NameLoc,
5418 const LookupResult *R = nullptr,
5419 const UsingDecl *UD = nullptr);
5420
5421 /// Builds a using declaration.
5422 ///
5423 /// \param IsInstantiation - Whether this call arises from an
5424 /// instantiation of an unresolved using declaration. We treat
5425 /// the lookup differently for these declarations.
5426 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5427 SourceLocation UsingLoc,
5428 bool HasTypenameKeyword,
5429 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5430 DeclarationNameInfo NameInfo,
5431 SourceLocation EllipsisLoc,
5432 const ParsedAttributesView &AttrList,
5433 bool IsInstantiation, bool IsUsingIfExists);
5434 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5435 SourceLocation UsingLoc,
5436 SourceLocation EnumLoc,
5437 SourceLocation NameLoc,
5438 TypeSourceInfo *EnumType, EnumDecl *ED);
5439 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5440 ArrayRef<NamedDecl *> Expansions);
5441
5442 /// Additional checks for a using declaration referring to a constructor name.
5443 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5444
5445 /// Given a derived-class using shadow declaration for a constructor and the
5446 /// correspnding base class constructor, find or create the implicit
5447 /// synthesized derived class constructor to use for this initialization.
5448 CXXConstructorDecl *
5449 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5450 ConstructorUsingShadowDecl *DerivedShadow);
5451
5452 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5453 SourceLocation UsingLoc,
5454 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5455 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5456 const ParsedAttributesView &AttrList);
5457 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5458 SourceLocation UsingLoc,
5459 SourceLocation EnumLoc, SourceRange TyLoc,
5460 const IdentifierInfo &II, ParsedType Ty,
5461 const CXXScopeSpec &SS);
5462 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5463 MultiTemplateParamsArg TemplateParams,
5464 SourceLocation UsingLoc, UnqualifiedId &Name,
5465 const ParsedAttributesView &AttrList,
5466 TypeResult Type, Decl *DeclFromDeclSpec);
5467
5468 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5469 /// including handling of its default argument expressions.
5470 ///
5471 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5472 ExprResult BuildCXXConstructExpr(
5473 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5474 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5475 bool HadMultipleCandidates, bool IsListInitialization,
5476 bool IsStdInitListInitialization, bool RequiresZeroInit,
5477 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5478
5479 /// Build a CXXConstructExpr whose constructor has already been resolved if
5480 /// it denotes an inherited constructor.
5481 ExprResult BuildCXXConstructExpr(
5482 SourceLocation ConstructLoc, QualType DeclInitType,
5483 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5484 bool HadMultipleCandidates, bool IsListInitialization,
5485 bool IsStdInitListInitialization, bool RequiresZeroInit,
5486 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5487
5488 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5489 // the constructor can be elidable?
5490 ExprResult BuildCXXConstructExpr(
5491 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5492 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5493 bool HadMultipleCandidates, bool IsListInitialization,
5494 bool IsStdInitListInitialization, bool RequiresZeroInit,
5495 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5496
5497 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5498 SourceLocation InitLoc);
5499
5500 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5501 /// constructed variable.
5502 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5503
5504 /// Helper class that collects exception specifications for
5505 /// implicitly-declared special member functions.
5506 class ImplicitExceptionSpecification {
5507 // Pointer to allow copying
5508 Sema *Self;
5509 // We order exception specifications thus:
5510 // noexcept is the most restrictive, but is only used in C++11.
5511 // throw() comes next.
5512 // Then a throw(collected exceptions)
5513 // Finally no specification, which is expressed as noexcept(false).
5514 // throw(...) is used instead if any called function uses it.
5515 ExceptionSpecificationType ComputedEST;
5516 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5517 SmallVector<QualType, 4> Exceptions;
5518
5519 void ClearExceptions() {
5520 ExceptionsSeen.clear();
5521 Exceptions.clear();
5522 }
5523
5524 public:
5525 explicit ImplicitExceptionSpecification(Sema &Self)
5526 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5527 if (!Self.getLangOpts().CPlusPlus11)
5528 ComputedEST = EST_DynamicNone;
5529 }
5530
5531 /// Get the computed exception specification type.
5532 ExceptionSpecificationType getExceptionSpecType() const {
5533 assert(!isComputedNoexcept(ComputedEST) &&
5534 "noexcept(expr) should not be a possible result");
5535 return ComputedEST;
5536 }
5537
5538 /// The number of exceptions in the exception specification.
5539 unsigned size() const { return Exceptions.size(); }
5540
5541 /// The set of exceptions in the exception specification.
5542 const QualType *data() const { return Exceptions.data(); }
5543
5544 /// Integrate another called method into the collected data.
5545 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5546
5547 /// Integrate an invoked expression into the collected data.
5548 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5549
5550 /// Integrate an invoked statement into the collected data.
5551 void CalledStmt(Stmt *S);
5552
5553 /// Overwrite an EPI's exception specification with this
5554 /// computed exception specification.
5555 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5556 FunctionProtoType::ExceptionSpecInfo ESI;
5557 ESI.Type = getExceptionSpecType();
5558 if (ESI.Type == EST_Dynamic) {
5559 ESI.Exceptions = Exceptions;
5560 } else if (ESI.Type == EST_None) {
5561 /// C++11 [except.spec]p14:
5562 /// The exception-specification is noexcept(false) if the set of
5563 /// potential exceptions of the special member function contains "any"
5564 ESI.Type = EST_NoexceptFalse;
5565 ESI.NoexceptExpr =
5566 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5567 }
5568 return ESI;
5569 }
5570 };
5571
5572 /// Evaluate the implicit exception specification for a defaulted
5573 /// special member function.
5574 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5575
5576 /// Check the given exception-specification and update the
5577 /// exception specification information with the results.
5578 void checkExceptionSpecification(bool IsTopLevel,
5579 ExceptionSpecificationType EST,
5580 ArrayRef<ParsedType> DynamicExceptions,
5581 ArrayRef<SourceRange> DynamicExceptionRanges,
5582 Expr *NoexceptExpr,
5583 SmallVectorImpl<QualType> &Exceptions,
5584 FunctionProtoType::ExceptionSpecInfo &ESI);
5585
5586 /// Add an exception-specification to the given member or friend function
5587 /// (or function template). The exception-specification was parsed
5588 /// after the function itself was declared.
5589 void actOnDelayedExceptionSpecification(
5590 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5591 ArrayRef<ParsedType> DynamicExceptions,
5592 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5593
5594 class InheritedConstructorInfo;
5595
5596 /// Determine if a special member function should have a deleted
5597 /// definition when it is defaulted.
5598 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5599 InheritedConstructorInfo *ICI = nullptr,
5600 bool Diagnose = false);
5601
5602 /// Produce notes explaining why a defaulted function was defined as deleted.
5603 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5604
5605 /// Declare the implicit default constructor for the given class.
5606 ///
5607 /// \param ClassDecl The class declaration into which the implicit
5608 /// default constructor will be added.
5609 ///
5610 /// \returns The implicitly-declared default constructor.
5611 CXXConstructorDecl *
5612 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5613
5614 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5615 /// defining this constructor as the default constructor.
5616 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5617 CXXConstructorDecl *Constructor);
5618
5619 /// Declare the implicit destructor for the given class.
5620 ///
5621 /// \param ClassDecl The class declaration into which the implicit
5622 /// destructor will be added.
5623 ///
5624 /// \returns The implicitly-declared destructor.
5625 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5626
5627 /// DefineImplicitDestructor - Checks for feasibility of
5628 /// defining this destructor as the default destructor.
5629 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5630 CXXDestructorDecl *Destructor);
5631
5632 /// Build an exception spec for destructors that don't have one.
5633 ///
5634 /// C++11 says that user-defined destructors with no exception spec get one
5635 /// that looks as if the destructor was implicitly declared.
5636 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5637
5638 /// Define the specified inheriting constructor.
5639 void DefineInheritingConstructor(SourceLocation UseLoc,
5640 CXXConstructorDecl *Constructor);
5641
5642 /// Declare the implicit copy constructor for the given class.
5643 ///
5644 /// \param ClassDecl The class declaration into which the implicit
5645 /// copy constructor will be added.
5646 ///
5647 /// \returns The implicitly-declared copy constructor.
5648 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5649
5650 /// DefineImplicitCopyConstructor - Checks for feasibility of
5651 /// defining this constructor as the copy constructor.
5652 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5653 CXXConstructorDecl *Constructor);
5654
5655 /// Declare the implicit move constructor for the given class.
5656 ///
5657 /// \param ClassDecl The Class declaration into which the implicit
5658 /// move constructor will be added.
5659 ///
5660 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5661 /// declared.
5662 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5663
5664 /// DefineImplicitMoveConstructor - Checks for feasibility of
5665 /// defining this constructor as the move constructor.
5666 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5667 CXXConstructorDecl *Constructor);
5668
5669 /// Declare the implicit copy assignment operator for the given class.
5670 ///
5671 /// \param ClassDecl The class declaration into which the implicit
5672 /// copy assignment operator will be added.
5673 ///
5674 /// \returns The implicitly-declared copy assignment operator.
5675 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5676
5677 /// Defines an implicitly-declared copy assignment operator.
5678 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5679 CXXMethodDecl *MethodDecl);
5680
5681 /// Declare the implicit move assignment operator for the given class.
5682 ///
5683 /// \param ClassDecl The Class declaration into which the implicit
5684 /// move assignment operator will be added.
5685 ///
5686 /// \returns The implicitly-declared move assignment operator, or NULL if it
5687 /// wasn't declared.
5688 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5689
5690 /// Defines an implicitly-declared move assignment operator.
5691 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5692 CXXMethodDecl *MethodDecl);
5693
5694 /// Check a completed declaration of an implicit special member.
5695 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5696
5697 /// Determine whether the given function is an implicitly-deleted
5698 /// special member function.
5699 bool isImplicitlyDeleted(FunctionDecl *FD);
5700
5701 /// Check whether 'this' shows up in the type of a static member
5702 /// function after the (naturally empty) cv-qualifier-seq would be.
5703 ///
5704 /// \returns true if an error occurred.
5705 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5706
5707 /// Whether this' shows up in the exception specification of a static
5708 /// member function.
5709 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5710
5711 /// Check whether 'this' shows up in the attributes of the given
5712 /// static member function.
5713 ///
5714 /// \returns true if an error occurred.
5715 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5716
5717 bool CheckImmediateEscalatingFunctionDefinition(
5718 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5719
5720 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5721
5722 /// Given a constructor and the set of arguments provided for the
5723 /// constructor, convert the arguments and add any required default arguments
5724 /// to form a proper call to this constructor.
5725 ///
5726 /// \returns true if an error occurred, false otherwise.
5727 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5728 QualType DeclInitType, MultiExprArg ArgsPtr,
5729 SourceLocation Loc,
5730 SmallVectorImpl<Expr *> &ConvertedArgs,
5731 bool AllowExplicit = false,
5732 bool IsListInitialization = false);
5733
5734 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5735 /// initializer for the declaration 'Dcl'.
5736 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5737 /// static data member of class X, names should be looked up in the scope of
5738 /// class X.
5739 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5740
5741 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5742 /// initializer for the declaration 'Dcl'.
5743 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5744
5745 /// Define the "body" of the conversion from a lambda object to a
5746 /// function pointer.
5747 ///
5748 /// This routine doesn't actually define a sensible body; rather, it fills
5749 /// in the initialization expression needed to copy the lambda object into
5750 /// the block, and IR generation actually generates the real body of the
5751 /// block pointer conversion.
5752 void
5753 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5754 CXXConversionDecl *Conv);
5755
5756 /// Define the "body" of the conversion from a lambda object to a
5757 /// block pointer.
5758 ///
5759 /// This routine doesn't actually define a sensible body; rather, it fills
5760 /// in the initialization expression needed to copy the lambda object into
5761 /// the block, and IR generation actually generates the real body of the
5762 /// block pointer conversion.
5763 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5764 CXXConversionDecl *Conv);
5765
5766 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5767 /// linkage specification, including the language and (if present)
5768 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5769 /// language string literal. LBraceLoc, if valid, provides the location of
5770 /// the '{' brace. Otherwise, this linkage specification does not
5771 /// have any braces.
5772 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5773 Expr *LangStr, SourceLocation LBraceLoc);
5774
5775 /// ActOnFinishLinkageSpecification - Complete the definition of
5776 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5777 /// valid, it's the position of the closing '}' brace in a linkage
5778 /// specification that uses braces.
5779 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5780 SourceLocation RBraceLoc);
5781
5782 //===--------------------------------------------------------------------===//
5783 // C++ Classes
5784 //
5785
5786 /// Get the class that is directly named by the current context. This is the
5787 /// class for which an unqualified-id in this scope could name a constructor
5788 /// or destructor.
5789 ///
5790 /// If the scope specifier denotes a class, this will be that class.
5791 /// If the scope specifier is empty, this will be the class whose
5792 /// member-specification we are currently within. Otherwise, there
5793 /// is no such class.
5794 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5795
5796 /// isCurrentClassName - Determine whether the identifier II is the
5797 /// name of the class type currently being defined. In the case of
5798 /// nested classes, this will only return true if II is the name of
5799 /// the innermost class.
5800 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5801 const CXXScopeSpec *SS = nullptr);
5802
5803 /// Determine whether the identifier II is a typo for the name of
5804 /// the class type currently being defined. If so, update it to the identifier
5805 /// that should have been used.
5806 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5807
5808 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5809 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5810 SourceLocation ColonLoc,
5811 const ParsedAttributesView &Attrs);
5812
5813 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5814 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5815 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5816 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5817 /// present (but parsing it has been deferred).
5818 NamedDecl *
5819 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5820 MultiTemplateParamsArg TemplateParameterLists,
5821 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5822 InClassInitStyle InitStyle);
5823
5824 /// Enter a new C++ default initializer scope. After calling this, the
5825 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5826 /// parsing or instantiating the initializer failed.
5827 void ActOnStartCXXInClassMemberInitializer();
5828
5829 /// This is invoked after parsing an in-class initializer for a
5830 /// non-static C++ class member, and after instantiating an in-class
5831 /// initializer in a class template. Such actions are deferred until the class
5832 /// is complete.
5833 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5834 SourceLocation EqualLoc,
5835 ExprResult Init);
5836
5837 /// Handle a C++ member initializer using parentheses syntax.
5838 MemInitResult
5839 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5840 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5841 const DeclSpec &DS, SourceLocation IdLoc,
5842 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5843 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5844
5845 /// Handle a C++ member initializer using braced-init-list syntax.
5846 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5847 CXXScopeSpec &SS,
5848 IdentifierInfo *MemberOrBase,
5849 ParsedType TemplateTypeTy,
5850 const DeclSpec &DS, SourceLocation IdLoc,
5851 Expr *InitList, SourceLocation EllipsisLoc);
5852
5853 /// Handle a C++ member initializer.
5854 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5855 CXXScopeSpec &SS,
5856 IdentifierInfo *MemberOrBase,
5857 ParsedType TemplateTypeTy,
5858 const DeclSpec &DS, SourceLocation IdLoc,
5859 Expr *Init, SourceLocation EllipsisLoc);
5860
5861 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5862 SourceLocation IdLoc);
5863
5864 MemInitResult BuildBaseInitializer(QualType BaseType,
5865 TypeSourceInfo *BaseTInfo, Expr *Init,
5866 CXXRecordDecl *ClassDecl,
5867 SourceLocation EllipsisLoc);
5868
5869 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5870 CXXRecordDecl *ClassDecl);
5871
5872 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5873 CXXCtorInitializer *Initializer);
5874
5875 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5876 ArrayRef<CXXCtorInitializer *> Initializers = {});
5877
5878 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5879 /// mark all the non-trivial destructors of its members and bases as
5880 /// referenced.
5881 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5882 CXXRecordDecl *Record);
5883
5884 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5885 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5886 /// class. In the Microsoft C++ ABI, this is done any time a class's
5887 /// destructor is referenced.
5888 void MarkVirtualBaseDestructorsReferenced(
5889 SourceLocation Location, CXXRecordDecl *ClassDecl,
5890 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5891 nullptr);
5892
5893 /// Do semantic checks to allow the complete destructor variant to be emitted
5894 /// when the destructor is defined in another translation unit. In the Itanium
5895 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5896 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5897 /// of the checks performed when emitting a regular destructor.
5898 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5899 CXXDestructorDecl *Dtor);
5900
5901 /// The list of classes whose vtables have been used within
5902 /// this translation unit, and the source locations at which the
5903 /// first use occurred.
5904 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5905
5906 /// The list of vtables that are required but have not yet been
5907 /// materialized.
5908 SmallVector<VTableUse, 16> VTableUses;
5909
5910 /// The set of classes whose vtables have been used within
5911 /// this translation unit, and a bit that will be true if the vtable is
5912 /// required to be emitted (otherwise, it should be emitted only if needed
5913 /// by code generation).
5914 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5915
5916 /// Load any externally-stored vtable uses.
5917 void LoadExternalVTableUses();
5918
5919 /// Note that the vtable for the given class was used at the
5920 /// given location.
5921 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5922 bool DefinitionRequired = false);
5923
5924 /// Mark the exception specifications of all virtual member functions
5925 /// in the given class as needed.
5926 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5927 const CXXRecordDecl *RD);
5928
5929 /// MarkVirtualMembersReferenced - Will mark all members of the given
5930 /// CXXRecordDecl referenced.
5931 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
5932 bool ConstexprOnly = false);
5933
5934 /// Define all of the vtables that have been used in this
5935 /// translation unit and reference any virtual members used by those
5936 /// vtables.
5937 ///
5938 /// \returns true if any work was done, false otherwise.
5939 bool DefineUsedVTables();
5940
5941 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5942 /// special functions, such as the default constructor, copy
5943 /// constructor, or destructor, to the given C++ class (C++
5944 /// [special]p1). This routine can only be executed just before the
5945 /// definition of the class is complete.
5946 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5947
5948 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5949 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5950 ArrayRef<CXXCtorInitializer *> MemInits,
5951 bool AnyErrors);
5952
5953 /// Check class-level dllimport/dllexport attribute. The caller must
5954 /// ensure that referenceDLLExportedClassMethods is called some point later
5955 /// when all outer classes of Class are complete.
5956 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5957 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
5958
5959 void referenceDLLExportedClassMethods();
5960
5961 /// Perform propagation of DLL attributes from a derived class to a
5962 /// templated base class for MS compatibility.
5963 void propagateDLLAttrToBaseClassTemplate(
5964 CXXRecordDecl *Class, Attr *ClassAttr,
5965 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5966 SourceLocation BaseLoc);
5967
5968 /// Perform semantic checks on a class definition that has been
5969 /// completing, introducing implicitly-declared members, checking for
5970 /// abstract types, etc.
5971 ///
5972 /// \param S The scope in which the class was parsed. Null if we didn't just
5973 /// parse a class definition.
5974 /// \param Record The completed class.
5975 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
5976
5977 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
5978 /// conditions that are needed for the attribute to have an effect.
5979 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
5980
5981 /// Check that VTable Pointer authentication is only being set on the first
5982 /// first instantiation of the vtable
5983 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
5984
5985 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
5986 Decl *TagDecl, SourceLocation LBrac,
5987 SourceLocation RBrac,
5988 const ParsedAttributesView &AttrList);
5989
5990 /// Perform any semantic analysis which needs to be delayed until all
5991 /// pending class member declarations have been parsed.
5992 void ActOnFinishCXXMemberDecls();
5993 void ActOnFinishCXXNonNestedClass();
5994
5995 /// This is used to implement the constant expression evaluation part of the
5996 /// attribute enable_if extension. There is nothing in standard C++ which
5997 /// would require reentering parameters.
5998 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5999 unsigned ActOnReenterTemplateScope(Decl *Template,
6000 llvm::function_ref<Scope *()> EnterScope);
6001 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6002
6003 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6004 /// parsing a top-level (non-nested) C++ class, and we are now
6005 /// parsing those parts of the given Method declaration that could
6006 /// not be parsed earlier (C++ [class.mem]p2), such as default
6007 /// arguments. This action should enter the scope of the given
6008 /// Method declaration as if we had just parsed the qualified method
6009 /// name. However, it should not bring the parameters into scope;
6010 /// that will be performed by ActOnDelayedCXXMethodParameter.
6011 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6012 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6013 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6014
6015 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6016 /// processing the delayed method declaration for Method. The method
6017 /// declaration is now considered finished. There may be a separate
6018 /// ActOnStartOfFunctionDef action later (not necessarily
6019 /// immediately!) for this method, if it was also defined inside the
6020 /// class body.
6021 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6022 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6023
6024 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6025
6026 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6027 StringEvaluationContext EvalContext,
6028 bool ErrorOnInvalidMessage);
6029 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6030 StringEvaluationContext EvalContext,
6031 bool ErrorOnInvalidMessage);
6032
6033 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6034 Expr *AssertExpr, Expr *AssertMessageExpr,
6035 SourceLocation RParenLoc);
6036 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6037 Expr *AssertExpr, Expr *AssertMessageExpr,
6038 SourceLocation RParenLoc, bool Failed);
6039
6040 /// Try to print more useful information about a failed static_assert
6041 /// with expression \E
6042 void DiagnoseStaticAssertDetails(const Expr *E);
6043
6044 /// If E represents a built-in type trait, or a known standard type trait,
6045 /// try to print more information about why the type type-trait failed.
6046 /// This assumes we already evaluated the expression to a false boolean value.
6047 void DiagnoseTypeTraitDetails(const Expr *E);
6048
6049 /// Handle a friend type declaration. This works in tandem with
6050 /// ActOnTag.
6051 ///
6052 /// Notes on friend class templates:
6053 ///
6054 /// We generally treat friend class declarations as if they were
6055 /// declaring a class. So, for example, the elaborated type specifier
6056 /// in a friend declaration is required to obey the restrictions of a
6057 /// class-head (i.e. no typedefs in the scope chain), template
6058 /// parameters are required to match up with simple template-ids, &c.
6059 /// However, unlike when declaring a template specialization, it's
6060 /// okay to refer to a template specialization without an empty
6061 /// template parameter declaration, e.g.
6062 /// friend class A<T>::B<unsigned>;
6063 /// We permit this as a special case; if there are any template
6064 /// parameters present at all, require proper matching, i.e.
6065 /// template <> template \<class T> friend class A<int>::B;
6066 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6067 MultiTemplateParamsArg TemplateParams,
6068 SourceLocation EllipsisLoc);
6069 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6070 MultiTemplateParamsArg TemplateParams);
6071
6072 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6073 /// the well-formedness of the constructor declarator @p D with type @p
6074 /// R. If there are any errors in the declarator, this routine will
6075 /// emit diagnostics and set the invalid bit to true. In any case, the type
6076 /// will be updated to reflect a well-formed type for the constructor and
6077 /// returned.
6078 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6079 StorageClass &SC);
6080
6081 /// CheckConstructor - Checks a fully-formed constructor for
6082 /// well-formedness, issuing any diagnostics required. Returns true if
6083 /// the constructor declarator is invalid.
6084 void CheckConstructor(CXXConstructorDecl *Constructor);
6085
6086 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6087 /// the well-formednes of the destructor declarator @p D with type @p
6088 /// R. If there are any errors in the declarator, this routine will
6089 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6090 /// will be updated to reflect a well-formed type for the destructor and
6091 /// returned.
6092 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6093 StorageClass &SC);
6094
6095 /// CheckDestructor - Checks a fully-formed destructor definition for
6096 /// well-formedness, issuing any diagnostics required. Returns true
6097 /// on error.
6098 bool CheckDestructor(CXXDestructorDecl *Destructor);
6099
6100 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6101 /// well-formednes of the conversion function declarator @p D with
6102 /// type @p R. If there are any errors in the declarator, this routine
6103 /// will emit diagnostics and return true. Otherwise, it will return
6104 /// false. Either way, the type @p R will be updated to reflect a
6105 /// well-formed type for the conversion operator.
6106 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6107
6108 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6109 /// the declaration of the given C++ conversion function. This routine
6110 /// is responsible for recording the conversion function in the C++
6111 /// class, if possible.
6112 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6113
6114 /// Check the validity of a declarator that we parsed for a deduction-guide.
6115 /// These aren't actually declarators in the grammar, so we need to check that
6116 /// the user didn't specify any pieces that are not part of the
6117 /// deduction-guide grammar. Return true on invalid deduction-guide.
6118 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6119 StorageClass &SC);
6120
6121 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6122
6123 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6124 CXXSpecialMemberKind CSM,
6125 SourceLocation DefaultLoc);
6126 void CheckDelayedMemberExceptionSpecs();
6127
6128 /// Kinds of defaulted comparison operator functions.
6129 enum class DefaultedComparisonKind : unsigned char {
6130 /// This is not a defaultable comparison operator.
6131 None,
6132 /// This is an operator== that should be implemented as a series of
6133 /// subobject comparisons.
6134 Equal,
6135 /// This is an operator<=> that should be implemented as a series of
6136 /// subobject comparisons.
6137 ThreeWay,
6138 /// This is an operator!= that should be implemented as a rewrite in terms
6139 /// of a == comparison.
6140 NotEqual,
6141 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6142 /// terms of a <=> comparison.
6143 Relational,
6144 };
6145
6146 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6147 DefaultedComparisonKind DCK);
6148 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6149 FunctionDecl *Spaceship);
6150 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6151 DefaultedComparisonKind DCK);
6152
6153 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6154 QualType R, bool IsLambda,
6155 DeclContext *DC = nullptr);
6156 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6157 DeclarationName Name, QualType R);
6158 void CheckExplicitObjectLambda(Declarator &D);
6159
6160 //===--------------------------------------------------------------------===//
6161 // C++ Derived Classes
6162 //
6163
6164 /// Check the validity of a C++ base class specifier.
6165 ///
6166 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6167 /// and returns NULL otherwise.
6168 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6169 SourceRange SpecifierRange, bool Virtual,
6170 AccessSpecifier Access,
6171 TypeSourceInfo *TInfo,
6172 SourceLocation EllipsisLoc);
6173
6174 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6175 /// one entry in the base class list of a class specifier, for
6176 /// example:
6177 /// class foo : public bar, virtual private baz {
6178 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6179 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6180 const ParsedAttributesView &Attrs, bool Virtual,
6181 AccessSpecifier Access, ParsedType basetype,
6182 SourceLocation BaseLoc,
6183 SourceLocation EllipsisLoc);
6184
6185 /// Performs the actual work of attaching the given base class
6186 /// specifiers to a C++ class.
6187 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6188 MutableArrayRef<CXXBaseSpecifier *> Bases);
6189
6190 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6191 /// class, after checking whether there are any duplicate base
6192 /// classes.
6193 void ActOnBaseSpecifiers(Decl *ClassDecl,
6194 MutableArrayRef<CXXBaseSpecifier *> Bases);
6195
6196 /// Determine whether the type \p Derived is a C++ class that is
6197 /// derived from the type \p Base.
6198 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6199 CXXRecordDecl *Base, CXXBasePaths &Paths);
6200 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6201 CXXRecordDecl *Base);
6202 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6203 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6204 CXXBasePaths &Paths);
6205
6206 // FIXME: I don't like this name.
6207 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6208
6209 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6210 SourceLocation Loc, SourceRange Range,
6211 CXXCastPath *BasePath = nullptr,
6212 bool IgnoreAccess = false);
6213
6214 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6215 /// conversion (where Derived and Base are class types) is
6216 /// well-formed, meaning that the conversion is unambiguous (and
6217 /// that all of the base classes are accessible). Returns true
6218 /// and emits a diagnostic if the code is ill-formed, returns false
6219 /// otherwise. Loc is the location where this routine should point to
6220 /// if there is an error, and Range is the source range to highlight
6221 /// if there is an error.
6222 ///
6223 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6224 /// diagnostic for the respective type of error will be suppressed, but the
6225 /// check for ill-formed code will still be performed.
6226 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6227 unsigned InaccessibleBaseID,
6228 unsigned AmbiguousBaseConvID,
6229 SourceLocation Loc, SourceRange Range,
6230 DeclarationName Name, CXXCastPath *BasePath,
6231 bool IgnoreAccess = false);
6232
6233 /// Builds a string representing ambiguous paths from a
6234 /// specific derived class to different subobjects of the same base
6235 /// class.
6236 ///
6237 /// This function builds a string that can be used in error messages
6238 /// to show the different paths that one can take through the
6239 /// inheritance hierarchy to go from the derived class to different
6240 /// subobjects of a base class. The result looks something like this:
6241 /// @code
6242 /// struct D -> struct B -> struct A
6243 /// struct D -> struct C -> struct A
6244 /// @endcode
6245 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6246
6247 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6248 const CXXMethodDecl *Old);
6249
6250 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6251 /// covariant, according to C++ [class.virtual]p5.
6252 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6253 const CXXMethodDecl *Old);
6254
6255 // Check that the overriding method has no explicit object parameter.
6256 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6257 const CXXMethodDecl *Old);
6258
6259 /// Mark the given method pure.
6260 ///
6261 /// \param Method the method to be marked pure.
6262 ///
6263 /// \param InitRange the source range that covers the "0" initializer.
6264 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6265
6266 /// CheckOverrideControl - Check C++11 override control semantics.
6267 void CheckOverrideControl(NamedDecl *D);
6268
6269 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6270 /// not used in the declaration of an overriding method.
6271 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6272
6273 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6274 /// function overrides a virtual member function marked 'final', according to
6275 /// C++11 [class.virtual]p4.
6276 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6277 const CXXMethodDecl *Old);
6278
6279 enum AbstractDiagSelID {
6280 AbstractNone = -1,
6281 AbstractReturnType,
6282 AbstractParamType,
6283 AbstractVariableType,
6284 AbstractFieldType,
6285 AbstractIvarType,
6286 AbstractSynthesizedIvarType,
6287 AbstractArrayType
6288 };
6289
6290 struct TypeDiagnoser;
6291
6292 bool isAbstractType(SourceLocation Loc, QualType T);
6293 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6294 TypeDiagnoser &Diagnoser);
6295 template <typename... Ts>
6296 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6297 const Ts &...Args) {
6298 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6299 return RequireNonAbstractType(Loc, T, Diagnoser);
6300 }
6301
6302 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6303
6304 //===--------------------------------------------------------------------===//
6305 // C++ Overloaded Operators [C++ 13.5]
6306 //
6307
6308 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6309 /// of this overloaded operator is well-formed. If so, returns false;
6310 /// otherwise, emits appropriate diagnostics and returns true.
6311 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6312
6313 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6314 /// of this literal operator function is well-formed. If so, returns
6315 /// false; otherwise, emits appropriate diagnostics and returns true.
6316 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6317
6318 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6319 /// found in an explicit(bool) specifier.
6320 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6321
6322 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6323 /// Returns true if the explicit specifier is now resolved.
6324 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6325
6326 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6327 /// C++ if/switch/while/for statement.
6328 /// e.g: "if (int x = f()) {...}"
6329 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6330
6331 // Emitting members of dllexported classes is delayed until the class
6332 // (including field initializers) is fully parsed.
6333 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6334 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6335
6336 /// Merge the exception specifications of two variable declarations.
6337 ///
6338 /// This is called when there's a redeclaration of a VarDecl. The function
6339 /// checks if the redeclaration might have an exception specification and
6340 /// validates compatibility and merges the specs if necessary.
6341 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6342
6343 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6344 /// function, once we already know that they have the same
6345 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6346 /// error, false otherwise.
6347 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6348
6349 /// Helpers for dealing with blocks and functions.
6350 void CheckCXXDefaultArguments(FunctionDecl *FD);
6351
6352 /// CheckExtraCXXDefaultArguments - Check for any extra default
6353 /// arguments in the declarator, which is not a function declaration
6354 /// or definition and therefore is not permitted to have default
6355 /// arguments. This routine should be invoked for every declarator
6356 /// that is not a function declaration or definition.
6357 void CheckExtraCXXDefaultArguments(Declarator &D);
6358
6359 CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD) {
6360 return getDefaultedFunctionKind(FD: MD).asSpecialMember();
6361 }
6362
6363 /// Perform semantic analysis for the variable declaration that
6364 /// occurs within a C++ catch clause, returning the newly-created
6365 /// variable.
6366 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6367 SourceLocation StartLoc,
6368 SourceLocation IdLoc,
6369 const IdentifierInfo *Id);
6370
6371 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6372 /// handler.
6373 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6374
6375 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6376
6377 /// Handle a friend tag declaration where the scope specifier was
6378 /// templated.
6379 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6380 unsigned TagSpec, SourceLocation TagLoc,
6381 CXXScopeSpec &SS, IdentifierInfo *Name,
6382 SourceLocation NameLoc,
6383 SourceLocation EllipsisLoc,
6384 const ParsedAttributesView &Attr,
6385 MultiTemplateParamsArg TempParamLists);
6386
6387 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6388 SourceLocation DeclStart, Declarator &D,
6389 Expr *BitfieldWidth,
6390 InClassInitStyle InitStyle,
6391 AccessSpecifier AS,
6392 const ParsedAttr &MSPropertyAttr);
6393
6394 /// Diagnose why the specified class does not have a trivial special member of
6395 /// the given kind.
6396 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6397 CXXSpecialMemberKind CSM);
6398
6399 /// Determine whether a defaulted or deleted special member function is
6400 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6401 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6402 bool SpecialMemberIsTrivial(
6403 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6404 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6405 bool Diagnose = false);
6406
6407 /// For a defaulted function, the kind of defaulted function that it is.
6408 class DefaultedFunctionKind {
6409 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6410 unsigned SpecialMember : 8;
6411 unsigned Comparison : 8;
6412
6413 public:
6414 DefaultedFunctionKind()
6415 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6416 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6417 DefaultedFunctionKind(CXXSpecialMemberKind CSM)
6418 : SpecialMember(llvm::to_underlying(E: CSM)),
6419 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6420 DefaultedFunctionKind(DefaultedComparisonKind Comp)
6421 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6422 Comparison(llvm::to_underlying(E: Comp)) {}
6423
6424 bool isSpecialMember() const {
6425 return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6426 CXXSpecialMemberKind::Invalid;
6427 }
6428 bool isComparison() const {
6429 return static_cast<DefaultedComparisonKind>(Comparison) !=
6430 DefaultedComparisonKind::None;
6431 }
6432
6433 explicit operator bool() const {
6434 return isSpecialMember() || isComparison();
6435 }
6436
6437 CXXSpecialMemberKind asSpecialMember() const {
6438 return static_cast<CXXSpecialMemberKind>(SpecialMember);
6439 }
6440 DefaultedComparisonKind asComparison() const {
6441 return static_cast<DefaultedComparisonKind>(Comparison);
6442 }
6443
6444 /// Get the index of this function kind for use in diagnostics.
6445 unsigned getDiagnosticIndex() const {
6446 static_assert(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid) >
6447 llvm::to_underlying(E: CXXSpecialMemberKind::Destructor),
6448 "invalid should have highest index");
6449 static_assert((unsigned)DefaultedComparisonKind::None == 0,
6450 "none should be equal to zero");
6451 return SpecialMember + Comparison;
6452 }
6453 };
6454
6455 /// Determine the kind of defaulting that would be done for a given function.
6456 ///
6457 /// If the function is both a default constructor and a copy / move
6458 /// constructor (due to having a default argument for the first parameter),
6459 /// this picks CXXSpecialMemberKind::DefaultConstructor.
6460 ///
6461 /// FIXME: Check that case is properly handled by all callers.
6462 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6463
6464 /// Handle a C++11 empty-declaration and attribute-declaration.
6465 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6466 SourceLocation SemiLoc);
6467
6468 enum class CheckConstexprKind {
6469 /// Diagnose issues that are non-constant or that are extensions.
6470 Diagnose,
6471 /// Identify whether this function satisfies the formal rules for constexpr
6472 /// functions in the current lanugage mode (with no extensions).
6473 CheckValid
6474 };
6475
6476 // Check whether a function declaration satisfies the requirements of a
6477 // constexpr function definition or a constexpr constructor definition. If so,
6478 // return true. If not, produce appropriate diagnostics (unless asked not to
6479 // by Kind) and return false.
6480 //
6481 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6482 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6483 CheckConstexprKind Kind);
6484
6485 /// Diagnose methods which overload virtual methods in a base class
6486 /// without overriding any.
6487 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6488
6489 /// Check if a method overloads virtual methods in a base class without
6490 /// overriding any.
6491 void
6492 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6493 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6494 void
6495 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6496 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6497
6498 /// ActOnParamDefaultArgument - Check whether the default argument
6499 /// provided for a function parameter is well-formed. If so, attach it
6500 /// to the parameter declaration.
6501 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6502 Expr *defarg);
6503
6504 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6505 /// argument for a function parameter, but we can't parse it yet
6506 /// because we're inside a class definition. Note that this default
6507 /// argument will be parsed later.
6508 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6509 SourceLocation ArgLoc);
6510
6511 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6512 /// the default argument for the parameter param failed.
6513 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6514 Expr *DefaultArg);
6515 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6516 SourceLocation EqualLoc);
6517 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6518 SourceLocation EqualLoc);
6519
6520 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6521 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6522 StringLiteral *Message = nullptr);
6523 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6524
6525 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6526 StringLiteral *DeletedMessage = nullptr);
6527 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6528 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6529 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6530
6531 NamedDecl *
6532 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6533 MultiTemplateParamsArg TemplateParamLists);
6534 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6535 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6536 RecordDecl *ClassDecl,
6537 const IdentifierInfo *Name);
6538
6539 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6540 SourceLocation Loc);
6541 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6542
6543 /// Stack containing information needed when in C++2a an 'auto' is encountered
6544 /// in a function declaration parameter type specifier in order to invent a
6545 /// corresponding template parameter in the enclosing abbreviated function
6546 /// template. This information is also present in LambdaScopeInfo, stored in
6547 /// the FunctionScopes stack.
6548 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6549
6550 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6551 std::unique_ptr<CXXFieldCollector> FieldCollector;
6552
6553 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6554 /// Set containing all declared private fields that are not used.
6555 NamedDeclSetType UnusedPrivateFields;
6556
6557 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6558
6559 /// PureVirtualClassDiagSet - a set of class declarations which we have
6560 /// emitted a list of pure virtual functions. Used to prevent emitting the
6561 /// same list more than once.
6562 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6563
6564 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
6565 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6566 DelegatingCtorDeclsType;
6567
6568 /// All the delegating constructors seen so far in the file, used for
6569 /// cycle detection at the end of the TU.
6570 DelegatingCtorDeclsType DelegatingCtorDecls;
6571
6572 /// The C++ "std" namespace, where the standard library resides.
6573 LazyDeclPtr StdNamespace;
6574
6575 /// The C++ "std::initializer_list" template, which is defined in
6576 /// \<initializer_list>.
6577 ClassTemplateDecl *StdInitializerList;
6578
6579 /// The C++ "std::type_identity" template, which is defined in
6580 /// \<type_traits>.
6581 ClassTemplateDecl *StdTypeIdentity;
6582
6583 // Contains the locations of the beginning of unparsed default
6584 // argument locations.
6585 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6586
6587 /// UndefinedInternals - all the used, undefined objects which require a
6588 /// definition in this translation unit.
6589 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6590
6591 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6592 SpecialMemberDecl;
6593
6594 /// The C++ special members which we are currently in the process of
6595 /// declaring. If this process recursively triggers the declaration of the
6596 /// same special member, we should act as if it is not yet declared.
6597 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6598
6599 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6600
6601 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6602
6603 typedef ProcessingContextState ParsingClassState;
6604 ParsingClassState PushParsingClass() {
6605 ParsingClassDepth++;
6606 return DelayedDiagnostics.pushUndelayed();
6607 }
6608 void PopParsingClass(ParsingClassState state) {
6609 ParsingClassDepth--;
6610 DelayedDiagnostics.popUndelayed(state);
6611 }
6612
6613 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6614 CXXScopeSpec &SS,
6615 ParsedType TemplateTypeTy,
6616 IdentifierInfo *MemberOrBase);
6617
6618private:
6619 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6620 QualType ResultTy,
6621 ArrayRef<QualType> Args);
6622 // Helper for ActOnFields to check for all function pointer members.
6623 bool EntirelyFunctionPointers(const RecordDecl *Record);
6624
6625 // A cache representing if we've fully checked the various comparison category
6626 // types stored in ASTContext. The bit-index corresponds to the integer value
6627 // of a ComparisonCategoryType enumerator.
6628 llvm::SmallBitVector FullyCheckedComparisonCategories;
6629
6630 /// Check if there is a field shadowing.
6631 void CheckShadowInheritedFields(const SourceLocation &Loc,
6632 DeclarationName FieldName,
6633 const CXXRecordDecl *RD,
6634 bool DeclIsField = true);
6635
6636 ///@}
6637
6638 //
6639 //
6640 // -------------------------------------------------------------------------
6641 //
6642 //
6643
6644 /// \name C++ Exception Specifications
6645 /// Implementations are in SemaExceptionSpec.cpp
6646 ///@{
6647
6648public:
6649 /// All the overriding functions seen during a class definition
6650 /// that had their exception spec checks delayed, plus the overridden
6651 /// function.
6652 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6653 DelayedOverridingExceptionSpecChecks;
6654
6655 /// All the function redeclarations seen during a class definition that had
6656 /// their exception spec checks delayed, plus the prior declaration they
6657 /// should be checked against. Except during error recovery, the new decl
6658 /// should always be a friend declaration, as that's the only valid way to
6659 /// redeclare a special member before its class is complete.
6660 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6661 DelayedEquivalentExceptionSpecChecks;
6662
6663 /// Determine if we're in a case where we need to (incorrectly) eagerly
6664 /// parse an exception specification to work around a libstdc++ bug.
6665 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6666
6667 /// Check the given noexcept-specifier, convert its expression, and compute
6668 /// the appropriate ExceptionSpecificationType.
6669 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6670 ExceptionSpecificationType &EST);
6671
6672 CanThrowResult canThrow(const Stmt *E);
6673 /// Determine whether the callee of a particular function call can throw.
6674 /// E, D and Loc are all optional.
6675 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6676 SourceLocation Loc = SourceLocation());
6677 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6678 const FunctionProtoType *FPT);
6679 void UpdateExceptionSpec(FunctionDecl *FD,
6680 const FunctionProtoType::ExceptionSpecInfo &ESI);
6681
6682 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6683 /// exception specification. Incomplete types, or pointers to incomplete types
6684 /// other than void are not allowed.
6685 ///
6686 /// \param[in,out] T The exception type. This will be decayed to a pointer
6687 /// type
6688 /// when the input is an array or a function type.
6689 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6690
6691 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6692 /// pointer to member to a function with an exception specification. This
6693 /// means that it is invalid to add another level of indirection.
6694 bool CheckDistantExceptionSpec(QualType T);
6695 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6696
6697 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6698 /// exception specifications. Exception specifications are equivalent if
6699 /// they allow exactly the same set of exception types. It does not matter how
6700 /// that is achieved. See C++ [except.spec]p2.
6701 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6702 SourceLocation OldLoc,
6703 const FunctionProtoType *New,
6704 SourceLocation NewLoc);
6705 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6706 const PartialDiagnostic &NoteID,
6707 const FunctionProtoType *Old,
6708 SourceLocation OldLoc,
6709 const FunctionProtoType *New,
6710 SourceLocation NewLoc);
6711 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6712
6713 /// CheckExceptionSpecSubset - Check whether the second function type's
6714 /// exception specification is a subset (or equivalent) of the first function
6715 /// type. This is used by override and pointer assignment checks.
6716 bool CheckExceptionSpecSubset(
6717 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6718 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6719 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6720 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6721 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6722
6723 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6724 /// two functions have equivalent exception specs. This is part of the
6725 /// assignment and override compatibility check. We do not check the
6726 /// parameters of parameter function pointers recursively, as no sane
6727 /// programmer would even be able to write such a function type.
6728 bool CheckParamExceptionSpec(
6729 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6730 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6731 SourceLocation TargetLoc, const FunctionProtoType *Source,
6732 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6733
6734 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6735
6736 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6737 /// spec is a subset of base spec.
6738 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6739 const CXXMethodDecl *Old);
6740
6741 ///@}
6742
6743 //
6744 //
6745 // -------------------------------------------------------------------------
6746 //
6747 //
6748
6749 /// \name Expressions
6750 /// Implementations are in SemaExpr.cpp
6751 ///@{
6752
6753public:
6754 /// Describes how the expressions currently being parsed are
6755 /// evaluated at run-time, if at all.
6756 enum class ExpressionEvaluationContext {
6757 /// The current expression and its subexpressions occur within an
6758 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6759 /// \c sizeof, where the type of the expression may be significant but
6760 /// no code will be generated to evaluate the value of the expression at
6761 /// run time.
6762 Unevaluated,
6763
6764 /// The current expression occurs within a braced-init-list within
6765 /// an unevaluated operand. This is mostly like a regular unevaluated
6766 /// context, except that we still instantiate constexpr functions that are
6767 /// referenced here so that we can perform narrowing checks correctly.
6768 UnevaluatedList,
6769
6770 /// The current expression occurs within a discarded statement.
6771 /// This behaves largely similarly to an unevaluated operand in preventing
6772 /// definitions from being required, but not in other ways.
6773 DiscardedStatement,
6774
6775 /// The current expression occurs within an unevaluated
6776 /// operand that unconditionally permits abstract references to
6777 /// fields, such as a SIZE operator in MS-style inline assembly.
6778 UnevaluatedAbstract,
6779
6780 /// The current context is "potentially evaluated" in C++11 terms,
6781 /// but the expression is evaluated at compile-time (like the values of
6782 /// cases in a switch statement).
6783 ConstantEvaluated,
6784
6785 /// In addition of being constant evaluated, the current expression
6786 /// occurs in an immediate function context - either a consteval function
6787 /// or a consteval if statement.
6788 ImmediateFunctionContext,
6789
6790 /// The current expression is potentially evaluated at run time,
6791 /// which means that code may be generated to evaluate the value of the
6792 /// expression at run time.
6793 PotentiallyEvaluated,
6794
6795 /// The current expression is potentially evaluated, but any
6796 /// declarations referenced inside that expression are only used if
6797 /// in fact the current expression is used.
6798 ///
6799 /// This value is used when parsing default function arguments, for which
6800 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6801 /// through varargs) but do not want to mark declarations as "referenced"
6802 /// until the default argument is used.
6803 PotentiallyEvaluatedIfUsed
6804 };
6805
6806 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6807 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6808 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6809 /// have been applied to all subexpressions of the enclosing full expression.
6810 /// This is cleared at the end of each full expression.
6811 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6812 MaybeODRUseExprSet MaybeODRUseExprs;
6813
6814 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6815
6816 /// Data structure used to record current or nested
6817 /// expression evaluation contexts.
6818 struct ExpressionEvaluationContextRecord {
6819 /// The expression evaluation context.
6820 ExpressionEvaluationContext Context;
6821
6822 /// Whether the enclosing context needed a cleanup.
6823 CleanupInfo ParentCleanup;
6824
6825 /// The number of active cleanup objects when we entered
6826 /// this expression evaluation context.
6827 unsigned NumCleanupObjects;
6828
6829 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6830
6831 /// The lambdas that are present within this context, if it
6832 /// is indeed an unevaluated context.
6833 SmallVector<LambdaExpr *, 2> Lambdas;
6834
6835 /// The declaration that provides context for lambda expressions
6836 /// and block literals if the normal declaration context does not
6837 /// suffice, e.g., in a default function argument.
6838 Decl *ManglingContextDecl;
6839
6840 /// Declaration for initializer if one is currently being
6841 /// parsed. Used when an expression has a possibly unreachable
6842 /// diagnostic to reference the declaration as a whole.
6843 VarDecl *DeclForInitializer = nullptr;
6844
6845 /// If we are processing a decltype type, a set of call expressions
6846 /// for which we have deferred checking the completeness of the return type.
6847 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6848
6849 /// If we are processing a decltype type, a set of temporary binding
6850 /// expressions for which we have deferred checking the destructor.
6851 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6852
6853 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6854
6855 /// Expressions appearing as the LHS of a volatile assignment in this
6856 /// context. We produce a warning for these when popping the context if
6857 /// they are not discarded-value expressions nor unevaluated operands.
6858 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6859
6860 /// Set of candidates for starting an immediate invocation.
6861 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6862 ImmediateInvocationCandidates;
6863
6864 /// Set of DeclRefExprs referencing a consteval function when used in a
6865 /// context not already known to be immediately invoked.
6866 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6867
6868 /// P2718R0 - Lifetime extension in range-based for loops.
6869 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6870 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6871 /// InLifetimeExtendingContext is true.
6872 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6873
6874 /// Small set of gathered accesses to potentially misaligned members
6875 /// due to the packed attribute.
6876 SmallVector<MisalignedMember, 4> MisalignedMembers;
6877
6878 /// \brief Describes whether we are in an expression constext which we have
6879 /// to handle differently.
6880 enum ExpressionKind {
6881 EK_Decltype,
6882 EK_TemplateArgument,
6883 EK_AttrArgument,
6884 EK_VariableInit,
6885 EK_Other
6886 } ExprContext;
6887
6888 // A context can be nested in both a discarded statement context and
6889 // an immediate function context, so they need to be tracked independently.
6890 bool InDiscardedStatement;
6891 bool InImmediateFunctionContext;
6892 bool InImmediateEscalatingFunctionContext;
6893
6894 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6895
6896 // We are in a constant context, but we also allow
6897 // non constant expressions, for example for array bounds (which may be
6898 // VLAs).
6899 bool InConditionallyConstantEvaluateContext = false;
6900
6901 /// Whether we are currently in a context in which all temporaries must be
6902 /// lifetime-extended, even if they're not bound to a reference (for
6903 /// example, in a for-range initializer).
6904 bool InLifetimeExtendingContext = false;
6905
6906 /// Whether evaluating an expression for a switch case label.
6907 bool IsCaseExpr = false;
6908
6909 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6910 bool RebuildDefaultArgOrDefaultInit = false;
6911
6912 // When evaluating immediate functions in the initializer of a default
6913 // argument or default member initializer, this is the declaration whose
6914 // default initializer is being evaluated and the location of the call
6915 // or constructor definition.
6916 struct InitializationContext {
6917 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6918 DeclContext *Context)
6919 : Loc(Loc), Decl(Decl), Context(Context) {
6920 assert(Decl && Context && "invalid initialization context");
6921 }
6922
6923 SourceLocation Loc;
6924 ValueDecl *Decl = nullptr;
6925 DeclContext *Context = nullptr;
6926 };
6927 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6928
6929 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6930 unsigned NumCleanupObjects,
6931 CleanupInfo ParentCleanup,
6932 Decl *ManglingContextDecl,
6933 ExpressionKind ExprContext)
6934 : Context(Context), ParentCleanup(ParentCleanup),
6935 NumCleanupObjects(NumCleanupObjects),
6936 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6937 InDiscardedStatement(false), InImmediateFunctionContext(false),
6938 InImmediateEscalatingFunctionContext(false) {}
6939
6940 bool isUnevaluated() const {
6941 return Context == ExpressionEvaluationContext::Unevaluated ||
6942 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6943 Context == ExpressionEvaluationContext::UnevaluatedList;
6944 }
6945
6946 bool isPotentiallyEvaluated() const {
6947 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6948 Context ==
6949 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6950 Context == ExpressionEvaluationContext::ConstantEvaluated;
6951 }
6952
6953 bool isConstantEvaluated() const {
6954 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6955 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6956 }
6957
6958 bool isImmediateFunctionContext() const {
6959 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
6960 (Context == ExpressionEvaluationContext::DiscardedStatement &&
6961 InImmediateFunctionContext) ||
6962 // C++23 [expr.const]p14:
6963 // An expression or conversion is in an immediate function
6964 // context if it is potentially evaluated and either:
6965 // * its innermost enclosing non-block scope is a function
6966 // parameter scope of an immediate function, or
6967 // * its enclosing statement is enclosed by the compound-
6968 // statement of a consteval if statement.
6969 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
6970 InImmediateFunctionContext);
6971 }
6972
6973 bool isDiscardedStatementContext() const {
6974 return Context == ExpressionEvaluationContext::DiscardedStatement ||
6975 ((Context ==
6976 ExpressionEvaluationContext::ImmediateFunctionContext ||
6977 isPotentiallyEvaluated()) &&
6978 InDiscardedStatement);
6979 }
6980 };
6981
6982 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
6983 assert(!ExprEvalContexts.empty() &&
6984 "Must be in an expression evaluation context");
6985 return ExprEvalContexts.back();
6986 }
6987
6988 ExpressionEvaluationContextRecord &currentEvaluationContext() {
6989 assert(!ExprEvalContexts.empty() &&
6990 "Must be in an expression evaluation context");
6991 return ExprEvalContexts.back();
6992 }
6993
6994 ExpressionEvaluationContextRecord &parentEvaluationContext() {
6995 assert(ExprEvalContexts.size() >= 2 &&
6996 "Must be in an expression evaluation context");
6997 return ExprEvalContexts[ExprEvalContexts.size() - 2];
6998 }
6999
7000 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
7001 return const_cast<Sema *>(this)->parentEvaluationContext();
7002 }
7003
7004 bool isAttrContext() const {
7005 return ExprEvalContexts.back().ExprContext ==
7006 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
7007 }
7008
7009 /// Increment when we find a reference; decrement when we find an ignored
7010 /// assignment. Ultimately the value is 0 if every reference is an ignored
7011 /// assignment.
7012 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7013
7014 /// Used to control the generation of ExprWithCleanups.
7015 CleanupInfo Cleanup;
7016
7017 /// ExprCleanupObjects - This is the stack of objects requiring
7018 /// cleanup that are created by the current full expression.
7019 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7020
7021 /// Determine whether the use of this declaration is valid, without
7022 /// emitting diagnostics.
7023 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7024 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7025 // has been used to find this declaration, which means we don't have to bother
7026 // checking the trailing requires clause.
7027 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7028 return DiagnoseUseOfDecl(
7029 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7030 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7031 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7032 }
7033
7034 /// Determine whether the use of this declaration is valid, and
7035 /// emit any corresponding diagnostics.
7036 ///
7037 /// This routine diagnoses various problems with referencing
7038 /// declarations that can occur when using a declaration. For example,
7039 /// it might warn if a deprecated or unavailable declaration is being
7040 /// used, or produce an error (and return true) if a C++0x deleted
7041 /// function is being used.
7042 ///
7043 /// \returns true if there was an error (this declaration cannot be
7044 /// referenced), false otherwise.
7045 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7046 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7047 bool ObjCPropertyAccess = false,
7048 bool AvoidPartialAvailabilityChecks = false,
7049 ObjCInterfaceDecl *ClassReceiver = nullptr,
7050 bool SkipTrailingRequiresClause = false);
7051
7052 /// Emit a note explaining that this function is deleted.
7053 void NoteDeletedFunction(FunctionDecl *FD);
7054
7055 /// DiagnoseSentinelCalls - This routine checks whether a call or
7056 /// message-send is to a declaration with the sentinel attribute, and
7057 /// if so, it checks that the requirements of the sentinel are
7058 /// satisfied.
7059 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7060 ArrayRef<Expr *> Args);
7061
7062 void PushExpressionEvaluationContext(
7063 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7064 ExpressionEvaluationContextRecord::ExpressionKind Type =
7065 ExpressionEvaluationContextRecord::EK_Other);
7066
7067 void PushExpressionEvaluationContextForFunction(
7068 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7069
7070 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7071 void PushExpressionEvaluationContext(
7072 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7073 ExpressionEvaluationContextRecord::ExpressionKind Type =
7074 ExpressionEvaluationContextRecord::EK_Other);
7075 void PopExpressionEvaluationContext();
7076
7077 void DiscardCleanupsInEvaluationContext();
7078
7079 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7080 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7081 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7082
7083 /// Check whether E, which is either a discarded-value expression or an
7084 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7085 /// lvalue, and if so, remove it from the list of volatile-qualified
7086 /// assignments that we are going to warn are deprecated.
7087 void CheckUnusedVolatileAssignment(Expr *E);
7088
7089 ExprResult ActOnConstantExpression(ExprResult Res);
7090
7091 // Functions for marking a declaration referenced. These functions also
7092 // contain the relevant logic for marking if a reference to a function or
7093 // variable is an odr-use (in the C++11 sense). There are separate variants
7094 // for expressions referring to a decl; these exist because odr-use marking
7095 // needs to be delayed for some constant variables when we build one of the
7096 // named expressions.
7097 //
7098 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7099 // should usually be true. This only needs to be set to false if the lack of
7100 // odr-use cannot be determined from the current context (for instance,
7101 // because the name denotes a virtual function and was written without an
7102 // explicit nested-name-specifier).
7103 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7104
7105 /// Mark a function referenced, and check whether it is odr-used
7106 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7107 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7108 bool MightBeOdrUse = true);
7109
7110 /// Mark a variable referenced, and check whether it is odr-used
7111 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7112 /// used directly for normal expressions referring to VarDecl.
7113 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7114
7115 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7116 ///
7117 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7118 /// be handled with care if the DeclRefExpr is not newly-created.
7119 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7120
7121 /// Perform reference-marking and odr-use handling for a MemberExpr.
7122 void MarkMemberReferenced(MemberExpr *E);
7123
7124 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7125 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7126 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7127 unsigned CapturingScopeIndex);
7128
7129 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7130 void CleanupVarDeclMarking();
7131
7132 /// Try to capture the given variable.
7133 ///
7134 /// \param Var The variable to capture.
7135 ///
7136 /// \param Loc The location at which the capture occurs.
7137 ///
7138 /// \param Kind The kind of capture, which may be implicit (for either a
7139 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7140 ///
7141 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7142 /// an explicit lambda capture.
7143 ///
7144 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7145 /// captures or diagnose errors. If false, this routine merely check whether
7146 /// the capture can occur without performing the capture itself or complaining
7147 /// if the variable cannot be captured.
7148 ///
7149 /// \param CaptureType Will be set to the type of the field used to capture
7150 /// this variable in the innermost block or lambda. Only valid when the
7151 /// variable can be captured.
7152 ///
7153 /// \param DeclRefType Will be set to the type of a reference to the capture
7154 /// from within the current scope. Only valid when the variable can be
7155 /// captured.
7156 ///
7157 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7158 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7159 /// This is useful when enclosing lambdas must speculatively capture
7160 /// variables that may or may not be used in certain specializations of
7161 /// a nested generic lambda.
7162 ///
7163 /// \returns true if an error occurred (i.e., the variable cannot be
7164 /// captured) and false if the capture succeeded.
7165 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7166 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7167 bool BuildAndDiagnose, QualType &CaptureType,
7168 QualType &DeclRefType,
7169 const unsigned *const FunctionScopeIndexToStopAt);
7170
7171 /// Try to capture the given variable.
7172 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7173 TryCaptureKind Kind = TryCaptureKind::Implicit,
7174 SourceLocation EllipsisLoc = SourceLocation());
7175
7176 /// Checks if the variable must be captured.
7177 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7178
7179 /// Given a variable, determine the type that a reference to that
7180 /// variable will have in the given scope.
7181 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7182
7183 /// Mark all of the declarations referenced within a particular AST node as
7184 /// referenced. Used when template instantiation instantiates a non-dependent
7185 /// type -- entities referenced by the type are now referenced.
7186 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7187
7188 /// Mark any declarations that appear within this expression or any
7189 /// potentially-evaluated subexpressions as "referenced".
7190 ///
7191 /// \param SkipLocalVariables If true, don't mark local variables as
7192 /// 'referenced'.
7193 /// \param StopAt Subexpressions that we shouldn't recurse into.
7194 void MarkDeclarationsReferencedInExpr(Expr *E,
7195 bool SkipLocalVariables = false,
7196 ArrayRef<const Expr *> StopAt = {});
7197
7198 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7199 /// conversion.
7200 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7201
7202 /// Conditionally issue a diagnostic based on the statements's reachability
7203 /// analysis.
7204 ///
7205 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7206 /// the function body is parsed, and then do a basic reachability analysis to
7207 /// determine if the statement is reachable. If it is unreachable, the
7208 /// diagnostic will not be emitted.
7209 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7210 const PartialDiagnostic &PD);
7211
7212 /// Conditionally issue a diagnostic based on the current
7213 /// evaluation context.
7214 ///
7215 /// \param Statement If Statement is non-null, delay reporting the
7216 /// diagnostic until the function body is parsed, and then do a basic
7217 /// reachability analysis to determine if the statement is reachable.
7218 /// If it is unreachable, the diagnostic will not be emitted.
7219 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7220 const PartialDiagnostic &PD);
7221 /// Similar, but diagnostic is only produced if all the specified statements
7222 /// are reachable.
7223 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7224 const PartialDiagnostic &PD);
7225
7226 // Primary Expressions.
7227 SourceRange getExprRange(Expr *E) const;
7228
7229 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7230 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7231 bool HasTrailingLParen, bool IsAddressOfOperand,
7232 CorrectionCandidateCallback *CCC = nullptr,
7233 bool IsInlineAsmIdentifier = false,
7234 Token *KeywordReplacement = nullptr);
7235
7236 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7237 /// possibly a list of template arguments.
7238 ///
7239 /// If this produces template arguments, it is permitted to call
7240 /// DecomposeTemplateName.
7241 ///
7242 /// This actually loses a lot of source location information for
7243 /// non-standard name kinds; we should consider preserving that in
7244 /// some way.
7245 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7246 TemplateArgumentListInfo &Buffer,
7247 DeclarationNameInfo &NameInfo,
7248 const TemplateArgumentListInfo *&TemplateArgs);
7249
7250 /// Diagnose a lookup that found results in an enclosing class during error
7251 /// recovery. This usually indicates that the results were found in a
7252 /// dependent base class that could not be searched as part of a template
7253 /// definition. Always issues a diagnostic (though this may be only a warning
7254 /// in MS compatibility mode).
7255 ///
7256 /// Return \c true if the error is unrecoverable, or \c false if the caller
7257 /// should attempt to recover using these lookup results.
7258 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7259
7260 /// Diagnose an empty lookup.
7261 ///
7262 /// \return false if new lookup candidates were found
7263 bool
7264 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7265 CorrectionCandidateCallback &CCC,
7266 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7267 ArrayRef<Expr *> Args = {},
7268 DeclContext *LookupCtx = nullptr);
7269
7270 /// If \p D cannot be odr-used in the current expression evaluation context,
7271 /// return a reason explaining why. Otherwise, return NOUR_None.
7272 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7273
7274 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7275 SourceLocation Loc,
7276 const CXXScopeSpec *SS = nullptr);
7277 DeclRefExpr *
7278 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7279 const DeclarationNameInfo &NameInfo,
7280 const CXXScopeSpec *SS = nullptr,
7281 NamedDecl *FoundD = nullptr,
7282 SourceLocation TemplateKWLoc = SourceLocation(),
7283 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7284
7285 /// BuildDeclRefExpr - Build an expression that references a
7286 /// declaration that does not require a closure capture.
7287 DeclRefExpr *
7288 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7289 const DeclarationNameInfo &NameInfo,
7290 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7291 SourceLocation TemplateKWLoc = SourceLocation(),
7292 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7293
7294 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7295 bool HasTrailingLParen);
7296
7297 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7298 /// declaration name, generally during template instantiation.
7299 /// There's a large number of things which don't need to be done along
7300 /// this path.
7301 ExprResult BuildQualifiedDeclarationNameExpr(
7302 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7303 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7304
7305 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7306 bool NeedsADL,
7307 bool AcceptInvalidDecl = false);
7308
7309 /// Complete semantic analysis for a reference to the given declaration.
7310 ExprResult BuildDeclarationNameExpr(
7311 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7312 NamedDecl *FoundD = nullptr,
7313 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7314 bool AcceptInvalidDecl = false);
7315
7316 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7317 // where Tokens representing function local predefined macros (such as
7318 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7319 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7320
7321 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7322 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7323 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7324
7325 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7326
7327 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7328 ExprResult ActOnCharacterConstant(const Token &Tok,
7329 Scope *UDLScope = nullptr);
7330 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7331 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7332 MultiExprArg Val);
7333 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7334 unsigned NumUserSpecifiedExprs,
7335 SourceLocation InitLoc,
7336 SourceLocation LParenLoc,
7337 SourceLocation RParenLoc);
7338
7339 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7340 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7341 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7342 /// from multiple tokens. However, the common case is that StringToks points
7343 /// to one string.
7344 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7345 Scope *UDLScope = nullptr);
7346
7347 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7348
7349 /// ControllingExprOrType is either an opaque pointer coming out of a
7350 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7351 /// into two so we don't take a void *, but that's awkward because one of
7352 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7353 /// itself to generic code very well.
7354 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7355 SourceLocation DefaultLoc,
7356 SourceLocation RParenLoc,
7357 bool PredicateIsExpr,
7358 void *ControllingExprOrType,
7359 ArrayRef<ParsedType> ArgTypes,
7360 ArrayRef<Expr *> ArgExprs);
7361 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7362 /// it'd be better to split this interface into two so we don't take a
7363 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7364 /// isn't a trivial change.
7365 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7366 SourceLocation DefaultLoc,
7367 SourceLocation RParenLoc,
7368 bool PredicateIsExpr,
7369 void *ControllingExprOrType,
7370 ArrayRef<TypeSourceInfo *> Types,
7371 ArrayRef<Expr *> Exprs);
7372
7373 // Binary/Unary Operators. 'Tok' is the token for the operator.
7374 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7375 Expr *InputExpr, bool IsAfterAmp = false);
7376 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7377 Expr *Input, bool IsAfterAmp = false);
7378
7379 /// Unary Operators. 'Tok' is the token for the operator.
7380 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7381 Expr *Input, bool IsAfterAmp = false);
7382
7383 /// Determine whether the given expression is a qualified member
7384 /// access expression, of a form that could be turned into a pointer to member
7385 /// with the address-of operator.
7386 bool isQualifiedMemberAccess(Expr *E);
7387 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7388 const Expr *Op,
7389 const CXXMethodDecl *MD);
7390
7391 /// CheckAddressOfOperand - The operand of & must be either a function
7392 /// designator or an lvalue designating an object. If it is an lvalue, the
7393 /// object cannot be declared with storage class register or be a bit field.
7394 /// Note: The usual conversions are *not* applied to the operand of the &
7395 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7396 /// In C++, the operand might be an overloaded function name, in which case
7397 /// we allow the '&' but retain the overloaded-function type.
7398 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7399
7400 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7401 /// _Alignas(type-name) .
7402 /// [dcl.align] An alignment-specifier of the form
7403 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7404 ///
7405 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7406 /// _Alignas(_Alignof(type-name)).
7407 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7408 SourceLocation OpLoc, SourceRange R);
7409 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7410 SourceLocation OpLoc, SourceRange R);
7411
7412 /// Build a sizeof or alignof expression given a type operand.
7413 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7414 SourceLocation OpLoc,
7415 UnaryExprOrTypeTrait ExprKind,
7416 SourceRange R);
7417
7418 /// Build a sizeof or alignof expression given an expression
7419 /// operand.
7420 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7421 UnaryExprOrTypeTrait ExprKind);
7422
7423 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7424 /// expr and the same for @c alignof and @c __alignof
7425 /// Note that the ArgRange is invalid if isType is false.
7426 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7427 UnaryExprOrTypeTrait ExprKind,
7428 bool IsType, void *TyOrEx,
7429 SourceRange ArgRange);
7430
7431 /// Check for operands with placeholder types and complain if found.
7432 /// Returns ExprError() if there was an error and no recovery was possible.
7433 ExprResult CheckPlaceholderExpr(Expr *E);
7434 bool CheckVecStepExpr(Expr *E);
7435
7436 /// Check the constraints on expression operands to unary type expression
7437 /// and type traits.
7438 ///
7439 /// Completes any types necessary and validates the constraints on the operand
7440 /// expression. The logic mostly mirrors the type-based overload, but may
7441 /// modify the expression as it completes the type for that expression through
7442 /// template instantiation, etc.
7443 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7444
7445 /// Check the constraints on operands to unary expression and type
7446 /// traits.
7447 ///
7448 /// This will complete any types necessary, and validate the various
7449 /// constraints on those operands.
7450 ///
7451 /// The UsualUnaryConversions() function is *not* called by this routine.
7452 /// C99 6.3.2.1p[2-4] all state:
7453 /// Except when it is the operand of the sizeof operator ...
7454 ///
7455 /// C++ [expr.sizeof]p4
7456 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7457 /// standard conversions are not applied to the operand of sizeof.
7458 ///
7459 /// This policy is followed for all of the unary trait expressions.
7460 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7461 SourceRange ExprRange,
7462 UnaryExprOrTypeTrait ExprKind,
7463 StringRef KWName);
7464
7465 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7466 tok::TokenKind Kind, Expr *Input);
7467
7468 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7469 MultiExprArg ArgExprs,
7470 SourceLocation RLoc);
7471 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7472 Expr *Idx, SourceLocation RLoc);
7473
7474 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7475 SourceLocation RBLoc);
7476
7477 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7478 Expr *ColumnIdx,
7479 SourceLocation RBLoc);
7480
7481 /// ConvertArgumentsForCall - Converts the arguments specified in
7482 /// Args/NumArgs to the parameter types of the function FDecl with
7483 /// function prototype Proto. Call is the call expression itself, and
7484 /// Fn is the function expression. For a C++ member function, this
7485 /// routine does not attempt to convert the object argument. Returns
7486 /// true if the call is ill-formed.
7487 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7488 const FunctionProtoType *Proto,
7489 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7490 bool ExecConfig = false);
7491
7492 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7493 /// array parameter, check that it is non-null, and that if it is formed by
7494 /// array-to-pointer decay, the underlying array is sufficiently large.
7495 ///
7496 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7497 /// the array type derivation, then for each call to the function, the value
7498 /// of the corresponding actual argument shall provide access to the first
7499 /// element of an array with at least as many elements as specified by the
7500 /// size expression.
7501 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7502 const Expr *ArgExpr);
7503
7504 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7505 /// This provides the location of the left/right parens and a list of comma
7506 /// locations.
7507 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7508 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7509 Expr *ExecConfig = nullptr);
7510
7511 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7512 /// This provides the location of the left/right parens and a list of comma
7513 /// locations.
7514 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7515 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7516 Expr *ExecConfig = nullptr,
7517 bool IsExecConfig = false,
7518 bool AllowRecovery = false);
7519
7520 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7521 // with the specified CallArgs
7522 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7523 MultiExprArg CallArgs);
7524
7525 using ADLCallKind = CallExpr::ADLCallKind;
7526
7527 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7528 /// i.e. an expression not of \p OverloadTy. The expression should
7529 /// unary-convert to an expression of function-pointer or
7530 /// block-pointer type.
7531 ///
7532 /// \param NDecl the declaration being called, if available
7533 ExprResult
7534 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7535 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7536 Expr *Config = nullptr, bool IsExecConfig = false,
7537 ADLCallKind UsesADL = ADLCallKind::NotADL);
7538
7539 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7540 ParsedType &Ty, SourceLocation RParenLoc,
7541 Expr *CastExpr);
7542
7543 /// Prepares for a scalar cast, performing all the necessary stages
7544 /// except the final cast and returning the kind required.
7545 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7546
7547 /// Build an altivec or OpenCL literal.
7548 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7549 SourceLocation RParenLoc, Expr *E,
7550 TypeSourceInfo *TInfo);
7551
7552 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7553 /// the ParenListExpr into a sequence of comma binary operators.
7554 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7555
7556 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7557 SourceLocation RParenLoc, Expr *InitExpr);
7558
7559 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7560 TypeSourceInfo *TInfo,
7561 SourceLocation RParenLoc,
7562 Expr *LiteralExpr);
7563
7564 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7565 SourceLocation RBraceLoc);
7566
7567 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7568 SourceLocation RBraceLoc);
7569
7570 /// Binary Operators. 'Tok' is the token for the operator.
7571 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7572 Expr *LHSExpr, Expr *RHSExpr);
7573 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7574 Expr *LHSExpr, Expr *RHSExpr,
7575 bool ForFoldExpression = false);
7576
7577 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7578 /// operator @p Opc at location @c TokLoc. This routine only supports
7579 /// built-in operations; ActOnBinOp handles overloaded operators.
7580 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7581 Expr *LHSExpr, Expr *RHSExpr,
7582 bool ForFoldExpression = false);
7583 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7584 UnresolvedSetImpl &Functions);
7585
7586 /// Look for instances where it is likely the comma operator is confused with
7587 /// another operator. There is an explicit list of acceptable expressions for
7588 /// the left hand side of the comma operator, otherwise emit a warning.
7589 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7590
7591 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7592 /// in the case of a the GNU conditional expr extension.
7593 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7594 SourceLocation ColonLoc, Expr *CondExpr,
7595 Expr *LHSExpr, Expr *RHSExpr);
7596
7597 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7598 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7599 LabelDecl *TheDecl);
7600
7601 void ActOnStartStmtExpr();
7602 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7603 SourceLocation RPLoc);
7604 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7605 SourceLocation RPLoc, unsigned TemplateDepth);
7606 // Handle the final expression in a statement expression.
7607 ExprResult ActOnStmtExprResult(ExprResult E);
7608 void ActOnStmtExprError();
7609
7610 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
7611 struct OffsetOfComponent {
7612 SourceLocation LocStart, LocEnd;
7613 bool isBrackets; // true if [expr], false if .ident
7614 union {
7615 IdentifierInfo *IdentInfo;
7616 Expr *E;
7617 } U;
7618 };
7619
7620 /// __builtin_offsetof(type, a.b[123][456].c)
7621 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7622 TypeSourceInfo *TInfo,
7623 ArrayRef<OffsetOfComponent> Components,
7624 SourceLocation RParenLoc);
7625 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7626 SourceLocation TypeLoc,
7627 ParsedType ParsedArgTy,
7628 ArrayRef<OffsetOfComponent> Components,
7629 SourceLocation RParenLoc);
7630
7631 // __builtin_choose_expr(constExpr, expr1, expr2)
7632 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7633 Expr *LHSExpr, Expr *RHSExpr,
7634 SourceLocation RPLoc);
7635
7636 // __builtin_va_arg(expr, type)
7637 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7638 SourceLocation RPLoc);
7639 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7640 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7641
7642 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7643 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7644 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7645 SourceLocation BuiltinLoc,
7646 SourceLocation RPLoc);
7647
7648 // #embed
7649 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7650 StringLiteral *BinaryData, StringRef FileName);
7651
7652 // Build a potentially resolved SourceLocExpr.
7653 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7654 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7655 DeclContext *ParentContext);
7656
7657 // __null
7658 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7659
7660 bool CheckCaseExpression(Expr *E);
7661
7662 //===------------------------- "Block" Extension ------------------------===//
7663
7664 /// ActOnBlockStart - This callback is invoked when a block literal is
7665 /// started.
7666 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7667
7668 /// ActOnBlockArguments - This callback allows processing of block arguments.
7669 /// If there are no arguments, this is still invoked.
7670 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7671 Scope *CurScope);
7672
7673 /// ActOnBlockError - If there is an error parsing a block, this callback
7674 /// is invoked to pop the information about the block from the action impl.
7675 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7676
7677 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7678 /// literal was successfully completed. ^(int x){...}
7679 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7680 Scope *CurScope);
7681
7682 //===---------------------------- Clang Extensions ----------------------===//
7683
7684 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7685 /// provided arguments.
7686 ///
7687 /// __builtin_convertvector( value, dst type )
7688 ///
7689 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7690 SourceLocation BuiltinLoc,
7691 SourceLocation RParenLoc);
7692
7693 //===---------------------------- OpenCL Features -----------------------===//
7694
7695 /// Parse a __builtin_astype expression.
7696 ///
7697 /// __builtin_astype( value, dst type )
7698 ///
7699 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7700 SourceLocation BuiltinLoc,
7701 SourceLocation RParenLoc);
7702
7703 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7704 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7705 SourceLocation BuiltinLoc,
7706 SourceLocation RParenLoc);
7707
7708 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7709 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7710 ArrayRef<Expr *> SubExprs,
7711 QualType T = QualType());
7712
7713 /// Cast a base object to a member's actual type.
7714 ///
7715 /// There are two relevant checks:
7716 ///
7717 /// C++ [class.access.base]p7:
7718 ///
7719 /// If a class member access operator [...] is used to access a non-static
7720 /// data member or non-static member function, the reference is ill-formed
7721 /// if the left operand [...] cannot be implicitly converted to a pointer to
7722 /// the naming class of the right operand.
7723 ///
7724 /// C++ [expr.ref]p7:
7725 ///
7726 /// If E2 is a non-static data member or a non-static member function, the
7727 /// program is ill-formed if the class of which E2 is directly a member is
7728 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7729 ///
7730 /// Note that the latter check does not consider access; the access of the
7731 /// "real" base class is checked as appropriate when checking the access of
7732 /// the member name.
7733 ExprResult PerformObjectMemberConversion(Expr *From,
7734 NestedNameSpecifier Qualifier,
7735 NamedDecl *FoundDecl,
7736 NamedDecl *Member);
7737
7738 /// CheckCallReturnType - Checks that a call expression's return type is
7739 /// complete. Returns true on failure. The location passed in is the location
7740 /// that best represents the call.
7741 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7742 CallExpr *CE, FunctionDecl *FD);
7743
7744 /// Emit a warning for all pending noderef expressions that we recorded.
7745 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7746
7747 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7748
7749 /// Instantiate or parse a C++ default argument expression as necessary.
7750 /// Return true on error.
7751 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7752 ParmVarDecl *Param, Expr *Init = nullptr,
7753 bool SkipImmediateInvocations = true);
7754
7755 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7756 /// the default expr if needed.
7757 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7758 ParmVarDecl *Param, Expr *Init = nullptr);
7759
7760 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7761 /// invocation.
7762 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7763
7764 void MarkExpressionAsImmediateEscalating(Expr *E);
7765
7766 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7767 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7768
7769 /// Abstract base class used for diagnosing integer constant
7770 /// expression violations.
7771 class VerifyICEDiagnoser {
7772 public:
7773 bool Suppress;
7774
7775 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7776
7777 virtual SemaDiagnosticBuilder
7778 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7779 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7780 SourceLocation Loc) = 0;
7781 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7782 virtual ~VerifyICEDiagnoser() {}
7783 };
7784
7785 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7786 /// and reports the appropriate diagnostics. Returns false on success.
7787 /// Can optionally return the value of the expression.
7788 ExprResult
7789 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7790 VerifyICEDiagnoser &Diagnoser,
7791 AllowFoldKind CanFold = AllowFoldKind::No);
7792 ExprResult
7793 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7794 unsigned DiagID,
7795 AllowFoldKind CanFold = AllowFoldKind::No);
7796 ExprResult
7797 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7798 AllowFoldKind CanFold = AllowFoldKind::No);
7799 ExprResult
7800 VerifyIntegerConstantExpression(Expr *E,
7801 AllowFoldKind CanFold = AllowFoldKind::No) {
7802 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7803 }
7804
7805 /// DiagnoseAssignmentAsCondition - Given that an expression is
7806 /// being used as a boolean condition, warn if it's an assignment.
7807 void DiagnoseAssignmentAsCondition(Expr *E);
7808
7809 /// Redundant parentheses over an equality comparison can indicate
7810 /// that the user intended an assignment used as condition.
7811 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7812
7813 class FullExprArg {
7814 public:
7815 FullExprArg() : E(nullptr) {}
7816 FullExprArg(Sema &actions) : E(nullptr) {}
7817
7818 ExprResult release() { return E; }
7819
7820 Expr *get() const { return E; }
7821
7822 Expr *operator->() { return E; }
7823
7824 private:
7825 // FIXME: No need to make the entire Sema class a friend when it's just
7826 // Sema::MakeFullExpr that needs access to the constructor below.
7827 friend class Sema;
7828
7829 explicit FullExprArg(Expr *expr) : E(expr) {}
7830
7831 Expr *E;
7832 };
7833
7834 FullExprArg MakeFullExpr(Expr *Arg) {
7835 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7836 }
7837 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7838 return FullExprArg(
7839 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7840 }
7841 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7842 ExprResult FE =
7843 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7844 /*DiscardedValue*/ DiscardedValue: true);
7845 return FullExprArg(FE.get());
7846 }
7847
7848 class ConditionResult {
7849 Decl *ConditionVar;
7850 ExprResult Condition;
7851 bool Invalid;
7852 std::optional<bool> KnownValue;
7853
7854 friend class Sema;
7855 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7856 bool IsConstexpr)
7857 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7858 if (IsConstexpr && Condition.get()) {
7859 if (std::optional<llvm::APSInt> Val =
7860 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7861 KnownValue = !!(*Val);
7862 }
7863 }
7864 }
7865 explicit ConditionResult(bool Invalid)
7866 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7867 KnownValue(std::nullopt) {}
7868
7869 public:
7870 ConditionResult() : ConditionResult(false) {}
7871 bool isInvalid() const { return Invalid; }
7872 std::pair<VarDecl *, Expr *> get() const {
7873 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7874 y: Condition.get());
7875 }
7876 std::optional<bool> getKnownValue() const { return KnownValue; }
7877 };
7878 static ConditionResult ConditionError() { return ConditionResult(true); }
7879
7880 /// CheckBooleanCondition - Diagnose problems involving the use of
7881 /// the given expression as a boolean condition (e.g. in an if
7882 /// statement). Also performs the standard function and array
7883 /// decays, possibly changing the input variable.
7884 ///
7885 /// \param Loc - A location associated with the condition, e.g. the
7886 /// 'if' keyword.
7887 /// \return true iff there were any errors
7888 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7889 bool IsConstexpr = false);
7890
7891 enum class ConditionKind {
7892 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7893 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7894 Switch ///< An integral condition for a 'switch' statement.
7895 };
7896
7897 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7898 ConditionKind CK, bool MissingOK = false);
7899
7900 QualType CheckConditionalOperands( // C99 6.5.15
7901 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7902 ExprObjectKind &OK, SourceLocation QuestionLoc);
7903
7904 /// Emit a specialized diagnostic when one expression is a null pointer
7905 /// constant and the other is not a pointer. Returns true if a diagnostic is
7906 /// emitted.
7907 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7908 SourceLocation QuestionLoc);
7909
7910 /// type checking for vector binary operators.
7911 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7912 SourceLocation Loc, bool IsCompAssign,
7913 bool AllowBothBool, bool AllowBoolConversion,
7914 bool AllowBoolOperation, bool ReportInvalid);
7915
7916 /// Return a signed ext_vector_type that is of identical size and number of
7917 /// elements. For floating point vectors, return an integer type of identical
7918 /// size and number of elements. In the non ext_vector_type case, search from
7919 /// the largest type to the smallest type to avoid cases where long long ==
7920 /// long, where long gets picked over long long.
7921 QualType GetSignedVectorType(QualType V);
7922 QualType GetSignedSizelessVectorType(QualType V);
7923
7924 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7925 /// operates on extended vector types. Instead of producing an IntTy result,
7926 /// like a scalar comparison, a vector comparison produces a vector of integer
7927 /// types.
7928 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7929 SourceLocation Loc,
7930 BinaryOperatorKind Opc);
7931 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7932 SourceLocation Loc,
7933 BinaryOperatorKind Opc);
7934 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7935 SourceLocation Loc,
7936 BinaryOperatorKind Opc);
7937 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7938 SourceLocation Loc,
7939 BinaryOperatorKind Opc);
7940 // type checking for sizeless vector binary operators.
7941 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7942 SourceLocation Loc, bool IsCompAssign,
7943 ArithConvKind OperationKind);
7944
7945 /// Type checking for matrix binary operators.
7946 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7947 SourceLocation Loc,
7948 bool IsCompAssign);
7949 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
7950 SourceLocation Loc, bool IsCompAssign);
7951
7952 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7953 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7954 /// VLST) allowed?
7955 ///
7956 /// This will also return false if the two given types do not make sense from
7957 /// the perspective of SVE bitcasts.
7958 bool isValidSveBitcast(QualType srcType, QualType destType);
7959
7960 /// Are the two types matrix types and do they have the same dimensions i.e.
7961 /// do they have the same number of rows and the same number of columns?
7962 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
7963
7964 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7965
7966 /// Are the two types lax-compatible vector types? That is, given
7967 /// that one of them is a vector, do they have equal storage sizes,
7968 /// where the storage size is the number of elements times the element
7969 /// size?
7970 ///
7971 /// This will also return false if either of the types is neither a
7972 /// vector nor a real type.
7973 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7974
7975 /// Is this a legal conversion between two types, one of which is
7976 /// known to be a vector type?
7977 bool isLaxVectorConversion(QualType srcType, QualType destType);
7978
7979 // This returns true if at least one of the types is an altivec vector.
7980 bool anyAltivecTypes(QualType srcType, QualType destType);
7981
7982 // type checking C++ declaration initializers (C++ [dcl.init]).
7983
7984 /// Check a cast of an unknown-any type. We intentionally only
7985 /// trigger this for C-style casts.
7986 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
7987 Expr *CastExpr, CastKind &CastKind,
7988 ExprValueKind &VK, CXXCastPath &Path);
7989
7990 /// Force an expression with unknown-type to an expression of the
7991 /// given type.
7992 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
7993
7994 /// Type-check an expression that's being passed to an
7995 /// __unknown_anytype parameter.
7996 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
7997 QualType &paramType);
7998
7999 // CheckMatrixCast - Check type constraints for matrix casts.
8000 // We allow casting between matrixes of the same dimensions i.e. when they
8001 // have the same number of rows and column. Returns true if the cast is
8002 // invalid.
8003 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8004 CastKind &Kind);
8005
8006 // CheckVectorCast - check type constraints for vectors.
8007 // Since vectors are an extension, there are no C standard reference for this.
8008 // We allow casting between vectors and integer datatypes of the same size.
8009 // returns true if the cast is invalid
8010 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8011 CastKind &Kind);
8012
8013 /// Prepare `SplattedExpr` for a vector splat operation, adding
8014 /// implicit casts if necessary.
8015 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8016
8017 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8018 /// implicit casts if necessary.
8019 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8020
8021 // CheckExtVectorCast - check type constraints for extended vectors.
8022 // Since vectors are an extension, there are no C standard reference for this.
8023 // We allow casting between vectors and integer datatypes of the same size,
8024 // or vectors and the element type of that vector.
8025 // returns the cast expr
8026 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8027 CastKind &Kind);
8028
8029 QualType PreferredConditionType(ConditionKind K) const {
8030 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8031 }
8032
8033 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8034 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8035 // promotes floating-piont types according to the language semantics.
8036 ExprResult UsualUnaryConversions(Expr *E);
8037
8038 // UsualUnaryFPConversions - promotes floating-point types according to the
8039 // current language semantics.
8040 ExprResult UsualUnaryFPConversions(Expr *E);
8041
8042 /// CallExprUnaryConversions - a special case of an unary conversion
8043 /// performed on a function designator of a call expression.
8044 ExprResult CallExprUnaryConversions(Expr *E);
8045
8046 // DefaultFunctionArrayConversion - converts functions and arrays
8047 // to their respective pointers (C99 6.3.2.1).
8048 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8049
8050 // DefaultFunctionArrayLvalueConversion - converts functions and
8051 // arrays to their respective pointers and performs the
8052 // lvalue-to-rvalue conversion.
8053 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8054 bool Diagnose = true);
8055
8056 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8057 // the operand. This function is a no-op if the operand has a function type
8058 // or an array type.
8059 ExprResult DefaultLvalueConversion(Expr *E);
8060
8061 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8062 // do not have a prototype. Integer promotions are performed on each
8063 // argument, and arguments that have type float are promoted to double.
8064 ExprResult DefaultArgumentPromotion(Expr *E);
8065
8066 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8067 const FunctionProtoType *Proto,
8068 Expr *Fn);
8069
8070 /// Determine the degree of POD-ness for an expression.
8071 /// Incomplete types are considered POD, since this check can be performed
8072 /// when we're in an unevaluated context.
8073 VarArgKind isValidVarArgType(const QualType &Ty);
8074
8075 /// Check to see if the given expression is a valid argument to a variadic
8076 /// function, issuing a diagnostic if not.
8077 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8078
8079 /// GatherArgumentsForCall - Collector argument expressions for various
8080 /// form of call prototypes.
8081 bool GatherArgumentsForCall(
8082 SourceLocation CallLoc, FunctionDecl *FDecl,
8083 const FunctionProtoType *Proto, unsigned FirstParam,
8084 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8085 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8086 bool AllowExplicit = false, bool IsListInitialization = false);
8087
8088 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8089 // will create a runtime trap if the resulting type is not a POD type.
8090 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8091 FunctionDecl *FDecl);
8092
8093 // Check that the usual arithmetic conversions can be performed on this pair
8094 // of expressions that might be of enumeration type.
8095 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8096 ArithConvKind ACK);
8097
8098 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8099 // operands and then handles various conversions that are common to binary
8100 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8101 // routine returns the first non-arithmetic type found. The client is
8102 // responsible for emitting appropriate error diagnostics.
8103 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8104 SourceLocation Loc, ArithConvKind ACK);
8105
8106 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8107 switch (ConvTy) {
8108 default:
8109 return false;
8110 case AssignConvertType::Compatible:
8111 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8112 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8113 return true;
8114 }
8115 llvm_unreachable("impossible");
8116 }
8117
8118 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8119 /// assignment conversion type specified by ConvTy. This returns true if the
8120 /// conversion was invalid or false if the conversion was accepted.
8121 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8122 QualType DstType, QualType SrcType,
8123 Expr *SrcExpr, AssignmentAction Action,
8124 bool *Complained = nullptr);
8125
8126 /// CheckAssignmentConstraints - Perform type checking for assignment,
8127 /// argument passing, variable initialization, and function return values.
8128 /// C99 6.5.16.
8129 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8130 QualType LHSType,
8131 QualType RHSType);
8132
8133 /// Check assignment constraints and optionally prepare for a conversion of
8134 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8135 /// is true.
8136 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8137 ExprResult &RHS, CastKind &Kind,
8138 bool ConvertRHS = true);
8139
8140 /// Check assignment constraints for an assignment of RHS to LHSType.
8141 ///
8142 /// \param LHSType The destination type for the assignment.
8143 /// \param RHS The source expression for the assignment.
8144 /// \param Diagnose If \c true, diagnostics may be produced when checking
8145 /// for assignability. If a diagnostic is produced, \p RHS will be
8146 /// set to ExprError(). Note that this function may still return
8147 /// without producing a diagnostic, even for an invalid assignment.
8148 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8149 /// in an audited Core Foundation API and does not need to be checked
8150 /// for ARC retain issues.
8151 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8152 /// conversions necessary to perform the assignment. If \c false,
8153 /// \p Diagnose must also be \c false.
8154 AssignConvertType CheckSingleAssignmentConstraints(
8155 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8156 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8157
8158 // If the lhs type is a transparent union, check whether we
8159 // can initialize the transparent union with the given expression.
8160 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8161 ExprResult &RHS);
8162
8163 /// the following "Check" methods will return a valid/converted QualType
8164 /// or a null QualType (indicating an error diagnostic was issued).
8165
8166 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8167 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8168 ExprResult &RHS);
8169
8170 /// Diagnose cases where a scalar was implicitly converted to a vector and
8171 /// diagnose the underlying types. Otherwise, diagnose the error
8172 /// as invalid vector logical operands for non-C++ cases.
8173 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8174 ExprResult &RHS);
8175
8176 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8177 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8178 BinaryOperatorKind Opc);
8179 QualType CheckRemainderOperands( // C99 6.5.5
8180 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8181 bool IsCompAssign = false);
8182 QualType CheckAdditionOperands( // C99 6.5.6
8183 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8184 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8185 QualType CheckSubtractionOperands( // C99 6.5.6
8186 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8187 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8188 QualType CheckShiftOperands( // C99 6.5.7
8189 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8190 BinaryOperatorKind Opc, bool IsCompAssign = false);
8191 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8192 QualType CheckCompareOperands( // C99 6.5.8/9
8193 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8194 BinaryOperatorKind Opc);
8195 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8196 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8197 BinaryOperatorKind Opc);
8198 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8199 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8200 BinaryOperatorKind Opc);
8201 // CheckAssignmentOperands is used for both simple and compound assignment.
8202 // For simple assignment, pass both expressions and a null converted type.
8203 // For compound assignment, pass both expressions and the converted type.
8204 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8205 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8206 BinaryOperatorKind Opc);
8207
8208 /// To be used for checking whether the arguments being passed to
8209 /// function exceeds the number of parameters expected for it.
8210 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8211 bool PartialOverloading = false) {
8212 // We check whether we're just after a comma in code-completion.
8213 if (NumArgs > 0 && PartialOverloading)
8214 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8215 return NumArgs > NumParams;
8216 }
8217
8218 /// Whether the AST is currently being rebuilt to correct immediate
8219 /// invocations. Immediate invocation candidates and references to consteval
8220 /// functions aren't tracked when this is set.
8221 bool RebuildingImmediateInvocation = false;
8222
8223 bool isAlwaysConstantEvaluatedContext() const {
8224 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8225 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8226 !Ctx.InConditionallyConstantEvaluateContext;
8227 }
8228
8229 /// Determines whether we are currently in a context that
8230 /// is not evaluated as per C++ [expr] p5.
8231 bool isUnevaluatedContext() const {
8232 return currentEvaluationContext().isUnevaluated();
8233 }
8234
8235 bool isImmediateFunctionContext() const {
8236 return currentEvaluationContext().isImmediateFunctionContext();
8237 }
8238
8239 bool isInLifetimeExtendingContext() const {
8240 return currentEvaluationContext().InLifetimeExtendingContext;
8241 }
8242
8243 bool needsRebuildOfDefaultArgOrInit() const {
8244 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8245 }
8246
8247 bool isCheckingDefaultArgumentOrInitializer() const {
8248 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8249 return (Ctx.Context ==
8250 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8251 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8252 }
8253
8254 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8255 InnermostDeclarationWithDelayedImmediateInvocations() const {
8256 assert(!ExprEvalContexts.empty() &&
8257 "Must be in an expression evaluation context");
8258 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8259 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8260 Ctx.DelayedDefaultInitializationContext)
8261 return Ctx.DelayedDefaultInitializationContext;
8262 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8263 Ctx.isUnevaluated())
8264 break;
8265 }
8266 return std::nullopt;
8267 }
8268
8269 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8270 OutermostDeclarationWithDelayedImmediateInvocations() const {
8271 assert(!ExprEvalContexts.empty() &&
8272 "Must be in an expression evaluation context");
8273 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8274 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8275 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8276 !Ctx.DelayedDefaultInitializationContext && Res)
8277 break;
8278 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8279 Ctx.isUnevaluated())
8280 break;
8281 Res = Ctx.DelayedDefaultInitializationContext;
8282 }
8283 return Res;
8284 }
8285
8286 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
8287 return getDefaultedFunctionKind(FD).asComparison();
8288 }
8289
8290 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8291 /// SelfAssigned when inside a CXXMethodDecl.
8292 const FieldDecl *
8293 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8294
8295 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8296
8297 template <typename... Ts>
8298 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8299 const Ts &...Args) {
8300 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8301 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8302 }
8303
8304 template <typename... Ts>
8305 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8306 const Ts &...Args) {
8307 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8308 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8309 }
8310
8311 /// Abstract class used to diagnose incomplete types.
8312 struct TypeDiagnoser {
8313 TypeDiagnoser() {}
8314
8315 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8316 virtual ~TypeDiagnoser() {}
8317 };
8318
8319 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8320 protected:
8321 unsigned DiagID;
8322 std::tuple<const Ts &...> Args;
8323
8324 template <std::size_t... Is>
8325 void emit(const SemaDiagnosticBuilder &DB,
8326 std::index_sequence<Is...>) const {
8327 // Apply all tuple elements to the builder in order.
8328 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8329 (void)Dummy;
8330 }
8331
8332 public:
8333 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8334 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8335 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8336 }
8337
8338 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8339 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8340 emit(DB, std::index_sequence_for<Ts...>());
8341 DB << T;
8342 }
8343 };
8344
8345 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8346 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8347 /// For example, a diagnostic with no other parameters would generally have
8348 /// the form "...%select{incomplete|sizeless}0 type %1...".
8349 template <typename... Ts>
8350 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8351 public:
8352 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8353 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8354
8355 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8356 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8357 this->emit(DB, std::index_sequence_for<Ts...>());
8358 DB << T->isSizelessType() << T;
8359 }
8360 };
8361
8362 /// Check an argument list for placeholders that we won't try to
8363 /// handle later.
8364 bool CheckArgsForPlaceholders(MultiExprArg args);
8365
8366 /// The C++ "std::source_location::__impl" struct, defined in
8367 /// \<source_location>.
8368 RecordDecl *StdSourceLocationImplDecl;
8369
8370 /// A stack of expression evaluation contexts.
8371 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8372
8373 // Set of failed immediate invocations to avoid double diagnosing.
8374 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8375
8376 /// List of SourceLocations where 'self' is implicitly retained inside a
8377 /// block.
8378 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8379 ImplicitlyRetainedSelfLocs;
8380
8381 /// Do an explicit extend of the given block pointer if we're in ARC.
8382 void maybeExtendBlockObject(ExprResult &E);
8383
8384 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8385 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8386 void DiagnosePrecisionLossInComplexDivision();
8387
8388private:
8389 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8390
8391 /// Methods for marking which expressions involve dereferencing a pointer
8392 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8393 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8394 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8395 /// `*p`, but need to check that `address of` is called on it. This requires
8396 /// keeping a container of all pending expressions and checking if the address
8397 /// of them are eventually taken.
8398 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8399 void CheckAddressOfNoDeref(const Expr *E);
8400
8401 ///@}
8402
8403 //
8404 //
8405 // -------------------------------------------------------------------------
8406 //
8407 //
8408
8409 /// \name C++ Expressions
8410 /// Implementations are in SemaExprCXX.cpp
8411 ///@{
8412
8413public:
8414 /// The C++ "std::bad_alloc" class, which is defined by the C++
8415 /// standard library.
8416 LazyDeclPtr StdBadAlloc;
8417
8418 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8419 /// standard library.
8420 LazyDeclPtr StdAlignValT;
8421
8422 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8423 RecordDecl *CXXTypeInfoDecl;
8424
8425 /// A flag to remember whether the implicit forms of operator new and delete
8426 /// have been declared.
8427 bool GlobalNewDeleteDeclared;
8428
8429 /// Delete-expressions to be analyzed at the end of translation unit
8430 ///
8431 /// This list contains class members, and locations of delete-expressions
8432 /// that could not be proven as to whether they mismatch with new-expression
8433 /// used in initializer of the field.
8434 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8435
8436 /// Handle the result of the special case name lookup for inheriting
8437 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8438 /// constructor names in member using declarations, even if 'X' is not the
8439 /// name of the corresponding type.
8440 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8441 SourceLocation NameLoc,
8442 const IdentifierInfo &Name);
8443
8444 ParsedType getConstructorName(const IdentifierInfo &II,
8445 SourceLocation NameLoc, Scope *S,
8446 CXXScopeSpec &SS, bool EnteringContext);
8447 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8448 Scope *S, CXXScopeSpec &SS,
8449 ParsedType ObjectType, bool EnteringContext);
8450
8451 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8452 ParsedType ObjectType);
8453
8454 /// Build a C++ typeid expression with a type operand.
8455 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8456 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8457
8458 /// Build a C++ typeid expression with an expression operand.
8459 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8460 Expr *Operand, SourceLocation RParenLoc);
8461
8462 /// ActOnCXXTypeid - Parse typeid( something ).
8463 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8464 bool isType, void *TyOrExpr,
8465 SourceLocation RParenLoc);
8466
8467 /// Build a Microsoft __uuidof expression with a type operand.
8468 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8469 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8470
8471 /// Build a Microsoft __uuidof expression with an expression operand.
8472 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8473 Expr *Operand, SourceLocation RParenLoc);
8474
8475 /// ActOnCXXUuidof - Parse __uuidof( something ).
8476 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8477 bool isType, void *TyOrExpr,
8478 SourceLocation RParenLoc);
8479
8480 //// ActOnCXXThis - Parse 'this' pointer.
8481 ExprResult ActOnCXXThis(SourceLocation Loc);
8482
8483 /// Check whether the type of 'this' is valid in the current context.
8484 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8485
8486 /// Build a CXXThisExpr and mark it referenced in the current context.
8487 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8488 void MarkThisReferenced(CXXThisExpr *This);
8489
8490 /// Try to retrieve the type of the 'this' pointer.
8491 ///
8492 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8493 QualType getCurrentThisType();
8494
8495 /// When non-NULL, the C++ 'this' expression is allowed despite the
8496 /// current context not being a non-static member function. In such cases,
8497 /// this provides the type used for 'this'.
8498 QualType CXXThisTypeOverride;
8499
8500 /// RAII object used to temporarily allow the C++ 'this' expression
8501 /// to be used, with the given qualifiers on the current class type.
8502 class CXXThisScopeRAII {
8503 Sema &S;
8504 QualType OldCXXThisTypeOverride;
8505 bool Enabled;
8506
8507 public:
8508 /// Introduce a new scope where 'this' may be allowed (when enabled),
8509 /// using the given declaration (which is either a class template or a
8510 /// class) along with the given qualifiers.
8511 /// along with the qualifiers placed on '*this'.
8512 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8513 bool Enabled = true);
8514
8515 ~CXXThisScopeRAII();
8516 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8517 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8518 };
8519
8520 /// Make sure the value of 'this' is actually available in the current
8521 /// context, if it is a potentially evaluated context.
8522 ///
8523 /// \param Loc The location at which the capture of 'this' occurs.
8524 ///
8525 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8526 /// capture list.
8527 ///
8528 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8529 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8530 /// This is useful when enclosing lambdas must speculatively capture
8531 /// 'this' that may or may not be used in certain specializations of
8532 /// a nested generic lambda (depending on whether the name resolves to
8533 /// a non-static member function or a static function).
8534 /// \return returns 'true' if failed, 'false' if success.
8535 bool CheckCXXThisCapture(
8536 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8537 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8538 bool ByCopy = false);
8539
8540 /// Determine whether the given type is the type of *this that is used
8541 /// outside of the body of a member function for a type that is currently
8542 /// being defined.
8543 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8544
8545 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8546 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8547
8548 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8549 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8550
8551 //// ActOnCXXThrow - Parse throw expressions.
8552 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8553 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8554 bool IsThrownVarInScope);
8555
8556 /// CheckCXXThrowOperand - Validate the operand of a throw.
8557 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8558
8559 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8560 /// Can be interpreted either as function-style casting ("int(x)")
8561 /// or class type construction ("ClassType(x,y,z)")
8562 /// or creation of a value-initialized type ("int()").
8563 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8564 SourceLocation LParenOrBraceLoc,
8565 MultiExprArg Exprs,
8566 SourceLocation RParenOrBraceLoc,
8567 bool ListInitialization);
8568
8569 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8570 SourceLocation LParenLoc,
8571 MultiExprArg Exprs,
8572 SourceLocation RParenLoc,
8573 bool ListInitialization);
8574
8575 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8576 ///
8577 /// E.g.:
8578 /// @code new (memory) int[size][4] @endcode
8579 /// or
8580 /// @code ::new Foo(23, "hello") @endcode
8581 ///
8582 /// \param StartLoc The first location of the expression.
8583 /// \param UseGlobal True if 'new' was prefixed with '::'.
8584 /// \param PlacementLParen Opening paren of the placement arguments.
8585 /// \param PlacementArgs Placement new arguments.
8586 /// \param PlacementRParen Closing paren of the placement arguments.
8587 /// \param TypeIdParens If the type is in parens, the source range.
8588 /// \param D The type to be allocated, as well as array dimensions.
8589 /// \param Initializer The initializing expression or initializer-list, or
8590 /// null if there is none.
8591 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8592 SourceLocation PlacementLParen,
8593 MultiExprArg PlacementArgs,
8594 SourceLocation PlacementRParen,
8595 SourceRange TypeIdParens, Declarator &D,
8596 Expr *Initializer);
8597 ExprResult
8598 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8599 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8600 SourceRange TypeIdParens, QualType AllocType,
8601 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8602 SourceRange DirectInitRange, Expr *Initializer);
8603
8604 /// Determine whether \p FD is an aligned allocation or deallocation
8605 /// function that is unavailable.
8606 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8607
8608 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8609 /// function that is unavailable.
8610 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8611 SourceLocation Loc);
8612
8613 /// Checks that a type is suitable as the allocated type
8614 /// in a new-expression.
8615 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8616 SourceRange R);
8617
8618 /// Finds the overloads of operator new and delete that are appropriate
8619 /// for the allocation.
8620 bool FindAllocationFunctions(
8621 SourceLocation StartLoc, SourceRange Range,
8622 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8623 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8624 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8625 FunctionDecl *&OperatorDelete, bool Diagnose = true);
8626
8627 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8628 /// delete. These are:
8629 /// @code
8630 /// // C++03:
8631 /// void* operator new(std::size_t) throw(std::bad_alloc);
8632 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8633 /// void operator delete(void *) throw();
8634 /// void operator delete[](void *) throw();
8635 /// // C++11:
8636 /// void* operator new(std::size_t);
8637 /// void* operator new[](std::size_t);
8638 /// void operator delete(void *) noexcept;
8639 /// void operator delete[](void *) noexcept;
8640 /// // C++1y:
8641 /// void* operator new(std::size_t);
8642 /// void* operator new[](std::size_t);
8643 /// void operator delete(void *) noexcept;
8644 /// void operator delete[](void *) noexcept;
8645 /// void operator delete(void *, std::size_t) noexcept;
8646 /// void operator delete[](void *, std::size_t) noexcept;
8647 /// @endcode
8648 /// Note that the placement and nothrow forms of new are *not* implicitly
8649 /// declared. Their use requires including \<new\>.
8650 void DeclareGlobalNewDelete();
8651 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8652 ArrayRef<QualType> Params);
8653
8654 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8655 DeclarationName Name, FunctionDecl *&Operator,
8656 ImplicitDeallocationParameters,
8657 bool Diagnose = true);
8658 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8659 ImplicitDeallocationParameters,
8660 DeclarationName Name,
8661 bool Diagnose = true);
8662 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8663 CXXRecordDecl *RD,
8664 bool Diagnose,
8665 bool LookForGlobal,
8666 DeclarationName Name);
8667
8668 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8669 /// @code ::delete ptr; @endcode
8670 /// or
8671 /// @code delete [] ptr; @endcode
8672 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8673 bool ArrayForm, Expr *Operand);
8674 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8675 bool IsDelete, bool CallCanBeVirtual,
8676 bool WarnOnNonAbstractTypes,
8677 SourceLocation DtorLoc);
8678
8679 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8680 Expr *Operand, SourceLocation RParen);
8681 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8682 SourceLocation RParen);
8683
8684 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8685 SourceLocation OpLoc,
8686 tok::TokenKind OpKind,
8687 ParsedType &ObjectType,
8688 bool &MayBePseudoDestructor);
8689
8690 ExprResult BuildPseudoDestructorExpr(
8691 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8692 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8693 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8694
8695 ExprResult ActOnPseudoDestructorExpr(
8696 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8697 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8698 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8699
8700 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8701 SourceLocation OpLoc,
8702 tok::TokenKind OpKind,
8703 SourceLocation TildeLoc,
8704 const DeclSpec &DS);
8705
8706 /// MaybeCreateExprWithCleanups - If the current full-expression
8707 /// requires any cleanups, surround it with a ExprWithCleanups node.
8708 /// Otherwise, just returns the passed-in expression.
8709 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8710 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8711 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8712
8713 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8714 return ActOnFinishFullExpr(
8715 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8716 }
8717 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8718 bool DiscardedValue, bool IsConstexpr = false,
8719 bool IsTemplateArgument = false);
8720 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8721
8722 /// Process the expression contained within a decltype. For such expressions,
8723 /// certain semantic checks on temporaries are delayed until this point, and
8724 /// are omitted for the 'topmost' call in the decltype expression. If the
8725 /// topmost call bound a temporary, strip that temporary off the expression.
8726 ExprResult ActOnDecltypeExpression(Expr *E);
8727
8728 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8729 bool IsUDSuffix);
8730
8731 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8732
8733 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8734 SourceLocation StmtLoc,
8735 ConditionKind CK);
8736
8737 /// Check the use of the given variable as a C++ condition in an if,
8738 /// while, do-while, or switch statement.
8739 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8740 SourceLocation StmtLoc, ConditionKind CK);
8741
8742 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8743 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8744
8745 /// Helper function to determine whether this is the (deprecated) C++
8746 /// conversion from a string literal to a pointer to non-const char or
8747 /// non-const wchar_t (for narrow and wide string literals,
8748 /// respectively).
8749 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8750
8751 /// PerformImplicitConversion - Perform an implicit conversion of the
8752 /// expression From to the type ToType using the pre-computed implicit
8753 /// conversion sequence ICS. Returns the converted
8754 /// expression. Action is the kind of conversion we're performing,
8755 /// used in the error message.
8756 ExprResult PerformImplicitConversion(
8757 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8758 AssignmentAction Action,
8759 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8760
8761 /// PerformImplicitConversion - Perform an implicit conversion of the
8762 /// expression From to the type ToType by following the standard
8763 /// conversion sequence SCS. Returns the converted
8764 /// expression. Flavor is the context in which we're performing this
8765 /// conversion, for use in error messages.
8766 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8767 const StandardConversionSequence &SCS,
8768 AssignmentAction Action,
8769 CheckedConversionKind CCK);
8770
8771 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8772
8773 /// Parsed one of the type trait support pseudo-functions.
8774 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8775 ArrayRef<ParsedType> Args,
8776 SourceLocation RParenLoc);
8777 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8778 ArrayRef<TypeSourceInfo *> Args,
8779 SourceLocation RParenLoc);
8780
8781 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8782 /// pseudo-functions.
8783 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8784 ParsedType LhsTy, Expr *DimExpr,
8785 SourceLocation RParen);
8786
8787 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8788 TypeSourceInfo *TSInfo, Expr *DimExpr,
8789 SourceLocation RParen);
8790
8791 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8792 /// pseudo-functions.
8793 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8794 Expr *Queried, SourceLocation RParen);
8795
8796 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8797 Expr *Queried, SourceLocation RParen);
8798
8799 QualType CheckPointerToMemberOperands( // C++ 5.5
8800 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8801 bool isIndirect);
8802 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8803 ExprResult &RHS,
8804 SourceLocation QuestionLoc);
8805
8806 //// Determines if a type is trivially relocatable
8807 /// according to the C++26 rules.
8808 // FIXME: This is in Sema because it requires
8809 // overload resolution, can we move to ASTContext?
8810 bool IsCXXTriviallyRelocatableType(QualType T);
8811 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8812
8813 /// Check the operands of ?: under C++ semantics.
8814 ///
8815 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8816 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8817 ///
8818 /// This function also implements GCC's vector extension and the
8819 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8820 /// permit the use of a?b:c where the type of a is that of a integer vector
8821 /// with the same number of elements and size as the vectors of b and c. If
8822 /// one of either b or c is a scalar it is implicitly converted to match the
8823 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8824 /// c are scalars, then b and c are checked and converted to the type of a if
8825 /// possible.
8826 ///
8827 /// The expressions are evaluated differently for GCC's and OpenCL's
8828 /// extensions. For the GCC extension, the ?: operator is evaluated as
8829 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8830 /// For the OpenCL extensions, the ?: operator is evaluated as
8831 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8832 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8833 QualType CXXCheckConditionalOperands( // C++ 5.16
8834 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8835 ExprObjectKind &OK, SourceLocation questionLoc);
8836
8837 /// Find a merged pointer type and convert the two expressions to it.
8838 ///
8839 /// This finds the composite pointer type for \p E1 and \p E2 according to
8840 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8841 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8842 /// ConvertArgs is \c true).
8843 ///
8844 /// \param Loc The location of the operator requiring these two expressions to
8845 /// be converted to the composite pointer type.
8846 ///
8847 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8848 /// type.
8849 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8850 bool ConvertArgs = true);
8851 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8852 ExprResult &E2, bool ConvertArgs = true) {
8853 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8854 QualType Composite =
8855 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8856 E1 = E1Tmp;
8857 E2 = E2Tmp;
8858 return Composite;
8859 }
8860
8861 /// MaybeBindToTemporary - If the passed in expression has a record type with
8862 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8863 /// it simply returns the passed in expression.
8864 ExprResult MaybeBindToTemporary(Expr *E);
8865
8866 /// IgnoredValueConversions - Given that an expression's result is
8867 /// syntactically ignored, perform any conversions that are
8868 /// required.
8869 ExprResult IgnoredValueConversions(Expr *E);
8870
8871 ExprResult CheckUnevaluatedOperand(Expr *E);
8872
8873 IfExistsResult
8874 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8875 const DeclarationNameInfo &TargetNameInfo);
8876
8877 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8878 SourceLocation KeywordLoc,
8879 bool IsIfExists, CXXScopeSpec &SS,
8880 UnqualifiedId &Name);
8881
8882 RequiresExprBodyDecl *
8883 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8884 ArrayRef<ParmVarDecl *> LocalParameters,
8885 Scope *BodyScope);
8886 void ActOnFinishRequiresExpr();
8887 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8888 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8889 CXXScopeSpec &SS,
8890 SourceLocation NameLoc,
8891 const IdentifierInfo *TypeName,
8892 TemplateIdAnnotation *TemplateId);
8893 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8894 SourceLocation NoexceptLoc);
8895 concepts::Requirement *ActOnCompoundRequirement(
8896 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8897 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8898 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8899 concepts::ExprRequirement *BuildExprRequirement(
8900 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8901 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8902 concepts::ExprRequirement *BuildExprRequirement(
8903 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8904 bool IsSatisfied, SourceLocation NoexceptLoc,
8905 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8906 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8907 concepts::TypeRequirement *BuildTypeRequirement(
8908 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8909 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8910 concepts::NestedRequirement *
8911 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8912 const ASTConstraintSatisfaction &Satisfaction);
8913 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8914 RequiresExprBodyDecl *Body,
8915 SourceLocation LParenLoc,
8916 ArrayRef<ParmVarDecl *> LocalParameters,
8917 SourceLocation RParenLoc,
8918 ArrayRef<concepts::Requirement *> Requirements,
8919 SourceLocation ClosingBraceLoc);
8920
8921private:
8922 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8923 bool IsDelete);
8924
8925 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8926 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8927 bool DeleteWasArrayForm);
8928
8929 ///@}
8930
8931 //
8932 //
8933 // -------------------------------------------------------------------------
8934 //
8935 //
8936
8937 /// \name Member Access Expressions
8938 /// Implementations are in SemaExprMember.cpp
8939 ///@{
8940
8941public:
8942 /// Check whether an expression might be an implicit class member access.
8943 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
8944 bool IsAddressOfOperand);
8945
8946 /// Builds an expression which might be an implicit member expression.
8947 ExprResult BuildPossibleImplicitMemberExpr(
8948 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8949 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8950
8951 /// Builds an implicit member access expression. The current context
8952 /// is known to be an instance method, and the given unqualified lookup
8953 /// set is known to contain only instance members, at least one of which
8954 /// is from an appropriate type.
8955 ExprResult
8956 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8957 LookupResult &R,
8958 const TemplateArgumentListInfo *TemplateArgs,
8959 bool IsDefiniteInstance, const Scope *S);
8960
8961 ExprResult ActOnDependentMemberExpr(
8962 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8963 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8964 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8965 const TemplateArgumentListInfo *TemplateArgs);
8966
8967 /// The main callback when the parser finds something like
8968 /// expression . [nested-name-specifier] identifier
8969 /// expression -> [nested-name-specifier] identifier
8970 /// where 'identifier' encompasses a fairly broad spectrum of
8971 /// possibilities, including destructor and operator references.
8972 ///
8973 /// \param OpKind either tok::arrow or tok::period
8974 /// \param ObjCImpDecl the current Objective-C \@implementation
8975 /// decl; this is an ugly hack around the fact that Objective-C
8976 /// \@implementations aren't properly put in the context chain
8977 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
8978 tok::TokenKind OpKind, CXXScopeSpec &SS,
8979 SourceLocation TemplateKWLoc,
8980 UnqualifiedId &Member, Decl *ObjCImpDecl);
8981
8982 MemberExpr *
8983 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
8984 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
8985 ValueDecl *Member, DeclAccessPair FoundDecl,
8986 bool HadMultipleCandidates,
8987 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
8988 ExprValueKind VK, ExprObjectKind OK,
8989 const TemplateArgumentListInfo *TemplateArgs = nullptr);
8990
8991 // Check whether the declarations we found through a nested-name
8992 // specifier in a member expression are actually members of the base
8993 // type. The restriction here is:
8994 //
8995 // C++ [expr.ref]p2:
8996 // ... In these cases, the id-expression shall name a
8997 // member of the class or of one of its base classes.
8998 //
8999 // So it's perfectly legitimate for the nested-name specifier to name
9000 // an unrelated class, and for us to find an overload set including
9001 // decls from classes which are not superclasses, as long as the decl
9002 // we actually pick through overload resolution is from a superclass.
9003 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9004 const CXXScopeSpec &SS,
9005 const LookupResult &R);
9006
9007 // This struct is for use by ActOnMemberAccess to allow
9008 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9009 // changing the access operator from a '.' to a '->' (to see if that is the
9010 // change needed to fix an error about an unknown member, e.g. when the class
9011 // defines a custom operator->).
9012 struct ActOnMemberAccessExtraArgs {
9013 Scope *S;
9014 UnqualifiedId &Id;
9015 Decl *ObjCImpDecl;
9016 };
9017
9018 ExprResult BuildMemberReferenceExpr(
9019 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9020 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9021 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9022 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9023 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9024
9025 ExprResult
9026 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9027 bool IsArrow, const CXXScopeSpec &SS,
9028 SourceLocation TemplateKWLoc,
9029 NamedDecl *FirstQualifierInScope, LookupResult &R,
9030 const TemplateArgumentListInfo *TemplateArgs,
9031 const Scope *S, bool SuppressQualifierCheck = false,
9032 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9033
9034 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9035 SourceLocation OpLoc,
9036 const CXXScopeSpec &SS, FieldDecl *Field,
9037 DeclAccessPair FoundDecl,
9038 const DeclarationNameInfo &MemberNameInfo);
9039
9040 /// Perform conversions on the LHS of a member access expression.
9041 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9042
9043 ExprResult BuildAnonymousStructUnionMemberReference(
9044 const CXXScopeSpec &SS, SourceLocation nameLoc,
9045 IndirectFieldDecl *indirectField,
9046 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9047 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9048
9049private:
9050 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9051
9052 ///@}
9053
9054 //
9055 //
9056 // -------------------------------------------------------------------------
9057 //
9058 //
9059
9060 /// \name Initializers
9061 /// Implementations are in SemaInit.cpp
9062 ///@{
9063
9064public:
9065 /// Stack of types that correspond to the parameter entities that are
9066 /// currently being copy-initialized. Can be empty.
9067 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9068
9069 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9070 AggregateDeductionCandidates;
9071
9072 bool IsStringInit(Expr *Init, const ArrayType *AT);
9073
9074 /// Determine whether we can perform aggregate initialization for the purposes
9075 /// of overload resolution.
9076 bool CanPerformAggregateInitializationForOverloadResolution(
9077 const InitializedEntity &Entity, InitListExpr *From);
9078
9079 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9080 SourceLocation EqualOrColonLoc,
9081 bool GNUSyntax, ExprResult Init);
9082
9083 /// Check that the lifetime of the initializer (and its subobjects) is
9084 /// sufficient for initializing the entity, and perform lifetime extension
9085 /// (when permitted) if not.
9086 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9087
9088 MaterializeTemporaryExpr *
9089 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9090 bool BoundToLvalueReference);
9091
9092 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9093 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9094 /// we don't have xvalues there.
9095 ExprResult TemporaryMaterializationConversion(Expr *E);
9096
9097 ExprResult PerformQualificationConversion(
9098 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9099 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9100
9101 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9102 ExprResult Init);
9103 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9104 SourceLocation EqualLoc, ExprResult Init,
9105 bool TopLevelOfInitList = false,
9106 bool AllowExplicit = false);
9107
9108 QualType DeduceTemplateSpecializationFromInitializer(
9109 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9110 const InitializationKind &Kind, MultiExprArg Init);
9111
9112 ///@}
9113
9114 //
9115 //
9116 // -------------------------------------------------------------------------
9117 //
9118 //
9119
9120 /// \name C++ Lambda Expressions
9121 /// Implementations are in SemaLambda.cpp
9122 ///@{
9123
9124public:
9125 /// Create a new lambda closure type.
9126 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9127 TypeSourceInfo *Info,
9128 unsigned LambdaDependencyKind,
9129 LambdaCaptureDefault CaptureDefault);
9130
9131 /// Number lambda for linkage purposes if necessary.
9132 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9133 std::optional<CXXRecordDecl::LambdaNumbering>
9134 NumberingOverride = std::nullopt);
9135
9136 /// Endow the lambda scope info with the relevant properties.
9137 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9138 SourceRange IntroducerRange,
9139 LambdaCaptureDefault CaptureDefault,
9140 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9141 bool Mutable);
9142
9143 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9144 CXXRecordDecl *Class);
9145
9146 void AddTemplateParametersToLambdaCallOperator(
9147 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9148 TemplateParameterList *TemplateParams);
9149
9150 void
9151 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9152 SourceLocation CallOperatorLoc,
9153 const AssociatedConstraint &TrailingRequiresClause,
9154 TypeSourceInfo *MethodTyInfo,
9155 ConstexprSpecKind ConstexprKind, StorageClass SC,
9156 ArrayRef<ParmVarDecl *> Params,
9157 bool HasExplicitResultType);
9158
9159 /// Returns true if the explicit object parameter was invalid.
9160 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9161 SourceLocation CallLoc);
9162
9163 /// Perform initialization analysis of the init-capture and perform
9164 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9165 /// not being used to initialize a reference.
9166 ParsedType actOnLambdaInitCaptureInitialization(
9167 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9168 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9169 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9170 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9171 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9172 }
9173 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9174 SourceLocation EllipsisLoc,
9175 UnsignedOrNone NumExpansions,
9176 IdentifierInfo *Id,
9177 bool DirectInit, Expr *&Init);
9178
9179 /// Create a dummy variable within the declcontext of the lambda's
9180 /// call operator, for name lookup purposes for a lambda init capture.
9181 ///
9182 /// CodeGen handles emission of lambda captures, ignoring these dummy
9183 /// variables appropriately.
9184 VarDecl *createLambdaInitCaptureVarDecl(
9185 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9186 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9187
9188 /// Add an init-capture to a lambda scope.
9189 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9190
9191 /// Note that we have finished the explicit captures for the
9192 /// given lambda.
9193 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9194
9195 /// Deduce a block or lambda's return type based on the return
9196 /// statements present in the body.
9197 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9198
9199 /// Once the Lambdas capture are known, we can start to create the closure,
9200 /// call operator method, and keep track of the captures.
9201 /// We do the capture lookup here, but they are not actually captured until
9202 /// after we know what the qualifiers of the call operator are.
9203 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9204 Scope *CurContext);
9205
9206 /// This is called after parsing the explicit template parameter list
9207 /// on a lambda (if it exists) in C++2a.
9208 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9209 SourceLocation LAngleLoc,
9210 ArrayRef<NamedDecl *> TParams,
9211 SourceLocation RAngleLoc,
9212 ExprResult RequiresClause);
9213
9214 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9215 SourceLocation MutableLoc);
9216
9217 void ActOnLambdaClosureParameters(
9218 Scope *LambdaScope,
9219 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9220
9221 /// ActOnStartOfLambdaDefinition - This is called just before we start
9222 /// parsing the body of a lambda; it analyzes the explicit captures and
9223 /// arguments, and sets up various data-structures for the body of the
9224 /// lambda.
9225 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9226 Declarator &ParamInfo, const DeclSpec &DS);
9227
9228 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9229 /// is invoked to pop the information about the lambda.
9230 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9231 bool IsInstantiation = false);
9232
9233 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9234 /// was successfully completed.
9235 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9236
9237 /// Does copying/destroying the captured variable have side effects?
9238 bool CaptureHasSideEffects(const sema::Capture &From);
9239
9240 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9241 /// diagnostic is emitted.
9242 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9243 SourceRange FixItRange,
9244 const sema::Capture &From);
9245
9246 /// Build a FieldDecl suitable to hold the given capture.
9247 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
9248
9249 /// Initialize the given capture with a suitable expression.
9250 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9251 SourceLocation ImplicitCaptureLoc,
9252 bool IsOpenMPMapping = false);
9253
9254 /// Complete a lambda-expression having processed and attached the
9255 /// lambda body.
9256 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9257
9258 /// Get the return type to use for a lambda's conversion function(s) to
9259 /// function pointer type, given the type of the call operator.
9260 QualType
9261 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9262 CallingConv CC);
9263
9264 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9265 SourceLocation ConvLocation,
9266 CXXConversionDecl *Conv, Expr *Src);
9267
9268 class LambdaScopeForCallOperatorInstantiationRAII
9269 : private FunctionScopeRAII {
9270 public:
9271 LambdaScopeForCallOperatorInstantiationRAII(
9272 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9273 LocalInstantiationScope &Scope,
9274 bool ShouldAddDeclsFromParentScope = true);
9275 };
9276
9277 /// Compute the mangling number context for a lambda expression or
9278 /// block literal. Also return the extra mangling decl if any.
9279 ///
9280 /// \param DC - The DeclContext containing the lambda expression or
9281 /// block literal.
9282 std::tuple<MangleNumberingContext *, Decl *>
9283 getCurrentMangleNumberContext(const DeclContext *DC);
9284
9285 ///@}
9286
9287 //
9288 //
9289 // -------------------------------------------------------------------------
9290 //
9291 //
9292
9293 /// \name Name Lookup
9294 ///
9295 /// These routines provide name lookup that is used during semantic
9296 /// analysis to resolve the various kinds of names (identifiers,
9297 /// overloaded operator names, constructor names, etc.) into zero or
9298 /// more declarations within a particular scope. The major entry
9299 /// points are LookupName, which performs unqualified name lookup,
9300 /// and LookupQualifiedName, which performs qualified name lookup.
9301 ///
9302 /// All name lookup is performed based on some specific criteria,
9303 /// which specify what names will be visible to name lookup and how
9304 /// far name lookup should work. These criteria are important both
9305 /// for capturing language semantics (certain lookups will ignore
9306 /// certain names, for example) and for performance, since name
9307 /// lookup is often a bottleneck in the compilation of C++. Name
9308 /// lookup criteria is specified via the LookupCriteria enumeration.
9309 ///
9310 /// The results of name lookup can vary based on the kind of name
9311 /// lookup performed, the current language, and the translation
9312 /// unit. In C, for example, name lookup will either return nothing
9313 /// (no entity found) or a single declaration. In C++, name lookup
9314 /// can additionally refer to a set of overloaded functions or
9315 /// result in an ambiguity. All of the possible results of name
9316 /// lookup are captured by the LookupResult class, which provides
9317 /// the ability to distinguish among them.
9318 ///
9319 /// Implementations are in SemaLookup.cpp
9320 ///@{
9321
9322public:
9323 /// Tracks whether we are in a context where typo correction is
9324 /// disabled.
9325 bool DisableTypoCorrection;
9326
9327 /// The number of typos corrected by CorrectTypo.
9328 unsigned TyposCorrected;
9329
9330 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9331 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9332
9333 /// A cache containing identifiers for which typo correction failed and
9334 /// their locations, so that repeated attempts to correct an identifier in a
9335 /// given location are ignored if typo correction already failed for it.
9336 IdentifierSourceLocations TypoCorrectionFailures;
9337
9338 /// SpecialMemberOverloadResult - The overloading result for a special member
9339 /// function.
9340 ///
9341 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9342 /// integer are used to determine whether overload resolution succeeded.
9343 class SpecialMemberOverloadResult {
9344 public:
9345 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9346
9347 private:
9348 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9349
9350 public:
9351 SpecialMemberOverloadResult() {}
9352 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9353 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9354
9355 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9356 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9357
9358 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9359 void setKind(Kind K) { Pair.setInt(K); }
9360 };
9361
9362 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9363 public SpecialMemberOverloadResult {
9364 public:
9365 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9366 : FastFoldingSetNode(ID) {}
9367 };
9368
9369 /// A cache of special member function overload resolution results
9370 /// for C++ records.
9371 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9372
9373 enum class AcceptableKind { Visible, Reachable };
9374
9375 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9376 // TODO: make this is a typesafe union.
9377 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9378 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9379
9380 /// Describes the kind of name lookup to perform.
9381 enum LookupNameKind {
9382 /// Ordinary name lookup, which finds ordinary names (functions,
9383 /// variables, typedefs, etc.) in C and most kinds of names
9384 /// (functions, variables, members, types, etc.) in C++.
9385 LookupOrdinaryName = 0,
9386 /// Tag name lookup, which finds the names of enums, classes,
9387 /// structs, and unions.
9388 LookupTagName,
9389 /// Label name lookup.
9390 LookupLabel,
9391 /// Member name lookup, which finds the names of
9392 /// class/struct/union members.
9393 LookupMemberName,
9394 /// Look up of an operator name (e.g., operator+) for use with
9395 /// operator overloading. This lookup is similar to ordinary name
9396 /// lookup, but will ignore any declarations that are class members.
9397 LookupOperatorName,
9398 /// Look up a name following ~ in a destructor name. This is an ordinary
9399 /// lookup, but prefers tags to typedefs.
9400 LookupDestructorName,
9401 /// Look up of a name that precedes the '::' scope resolution
9402 /// operator in C++. This lookup completely ignores operator, object,
9403 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9404 LookupNestedNameSpecifierName,
9405 /// Look up a namespace name within a C++ using directive or
9406 /// namespace alias definition, ignoring non-namespace names (C++
9407 /// [basic.lookup.udir]p1).
9408 LookupNamespaceName,
9409 /// Look up all declarations in a scope with the given name,
9410 /// including resolved using declarations. This is appropriate
9411 /// for checking redeclarations for a using declaration.
9412 LookupUsingDeclName,
9413 /// Look up an ordinary name that is going to be redeclared as a
9414 /// name with linkage. This lookup ignores any declarations that
9415 /// are outside of the current scope unless they have linkage. See
9416 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9417 LookupRedeclarationWithLinkage,
9418 /// Look up a friend of a local class. This lookup does not look
9419 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9420 LookupLocalFriendName,
9421 /// Look up the name of an Objective-C protocol.
9422 LookupObjCProtocolName,
9423 /// Look up implicit 'self' parameter of an objective-c method.
9424 LookupObjCImplicitSelfParam,
9425 /// Look up the name of an OpenMP user-defined reduction operation.
9426 LookupOMPReductionName,
9427 /// Look up the name of an OpenMP user-defined mapper.
9428 LookupOMPMapperName,
9429 /// Look up any declaration with any name.
9430 LookupAnyName
9431 };
9432
9433 /// The possible outcomes of name lookup for a literal operator.
9434 enum LiteralOperatorLookupResult {
9435 /// The lookup resulted in an error.
9436 LOLR_Error,
9437 /// The lookup found no match but no diagnostic was issued.
9438 LOLR_ErrorNoDiagnostic,
9439 /// The lookup found a single 'cooked' literal operator, which
9440 /// expects a normal literal to be built and passed to it.
9441 LOLR_Cooked,
9442 /// The lookup found a single 'raw' literal operator, which expects
9443 /// a string literal containing the spelling of the literal token.
9444 LOLR_Raw,
9445 /// The lookup found an overload set of literal operator templates,
9446 /// which expect the characters of the spelling of the literal token to be
9447 /// passed as a non-type template argument pack.
9448 LOLR_Template,
9449 /// The lookup found an overload set of literal operator templates,
9450 /// which expect the character type and characters of the spelling of the
9451 /// string literal token to be passed as template arguments.
9452 LOLR_StringTemplatePack,
9453 };
9454
9455 SpecialMemberOverloadResult
9456 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9457 bool VolatileArg, bool RValueThis, bool ConstThis,
9458 bool VolatileThis);
9459
9460 RedeclarationKind forRedeclarationInCurContext() const;
9461
9462 /// Look up a name, looking for a single declaration. Return
9463 /// null if the results were absent, ambiguous, or overloaded.
9464 ///
9465 /// It is preferable to use the elaborated form and explicitly handle
9466 /// ambiguity and overloaded.
9467 NamedDecl *LookupSingleName(
9468 Scope *S, DeclarationName Name, SourceLocation Loc,
9469 LookupNameKind NameKind,
9470 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9471
9472 /// Lookup a builtin function, when name lookup would otherwise
9473 /// fail.
9474 bool LookupBuiltin(LookupResult &R);
9475 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9476
9477 /// Perform unqualified name lookup starting from a given
9478 /// scope.
9479 ///
9480 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9481 /// used to find names within the current scope. For example, 'x' in
9482 /// @code
9483 /// int x;
9484 /// int f() {
9485 /// return x; // unqualified name look finds 'x' in the global scope
9486 /// }
9487 /// @endcode
9488 ///
9489 /// Different lookup criteria can find different names. For example, a
9490 /// particular scope can have both a struct and a function of the same
9491 /// name, and each can be found by certain lookup criteria. For more
9492 /// information about lookup criteria, see the documentation for the
9493 /// class LookupCriteria.
9494 ///
9495 /// @param S The scope from which unqualified name lookup will
9496 /// begin. If the lookup criteria permits, name lookup may also search
9497 /// in the parent scopes.
9498 ///
9499 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9500 /// look up and the lookup kind), and is updated with the results of lookup
9501 /// including zero or more declarations and possibly additional information
9502 /// used to diagnose ambiguities.
9503 ///
9504 /// @returns \c true if lookup succeeded and false otherwise.
9505 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9506 bool ForceNoCPlusPlus = false);
9507
9508 /// Perform qualified name lookup into a given context.
9509 ///
9510 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9511 /// names when the context of those names is explicit specified, e.g.,
9512 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9513 ///
9514 /// Different lookup criteria can find different names. For example, a
9515 /// particular scope can have both a struct and a function of the same
9516 /// name, and each can be found by certain lookup criteria. For more
9517 /// information about lookup criteria, see the documentation for the
9518 /// class LookupCriteria.
9519 ///
9520 /// \param R captures both the lookup criteria and any lookup results found.
9521 ///
9522 /// \param LookupCtx The context in which qualified name lookup will
9523 /// search. If the lookup criteria permits, name lookup may also search
9524 /// in the parent contexts or (for C++ classes) base classes.
9525 ///
9526 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9527 /// occurs as part of unqualified name lookup.
9528 ///
9529 /// \returns true if lookup succeeded, false if it failed.
9530 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9531 bool InUnqualifiedLookup = false);
9532
9533 /// Performs qualified name lookup or special type of lookup for
9534 /// "__super::" scope specifier.
9535 ///
9536 /// This routine is a convenience overload meant to be called from contexts
9537 /// that need to perform a qualified name lookup with an optional C++ scope
9538 /// specifier that might require special kind of lookup.
9539 ///
9540 /// \param R captures both the lookup criteria and any lookup results found.
9541 ///
9542 /// \param LookupCtx The context in which qualified name lookup will
9543 /// search.
9544 ///
9545 /// \param SS An optional C++ scope-specifier.
9546 ///
9547 /// \returns true if lookup succeeded, false if it failed.
9548 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9549 CXXScopeSpec &SS);
9550
9551 /// Performs name lookup for a name that was parsed in the
9552 /// source code, and may contain a C++ scope specifier.
9553 ///
9554 /// This routine is a convenience routine meant to be called from
9555 /// contexts that receive a name and an optional C++ scope specifier
9556 /// (e.g., "N::M::x"). It will then perform either qualified or
9557 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9558 /// respectively) on the given name and return those results. It will
9559 /// perform a special type of lookup for "__super::" scope specifier.
9560 ///
9561 /// @param S The scope from which unqualified name lookup will
9562 /// begin.
9563 ///
9564 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9565 ///
9566 /// @param EnteringContext Indicates whether we are going to enter the
9567 /// context of the scope-specifier SS (if present).
9568 ///
9569 /// @returns True if any decls were found (but possibly ambiguous)
9570 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9571 QualType ObjectType, bool AllowBuiltinCreation = false,
9572 bool EnteringContext = false);
9573
9574 /// Perform qualified name lookup into all base classes of the given
9575 /// class.
9576 ///
9577 /// \param R captures both the lookup criteria and any lookup results found.
9578 ///
9579 /// \param Class The context in which qualified name lookup will
9580 /// search. Name lookup will search in all base classes merging the results.
9581 ///
9582 /// @returns True if any decls were found (but possibly ambiguous)
9583 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9584
9585 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9586 UnresolvedSetImpl &Functions);
9587
9588 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9589 /// If GnuLabelLoc is a valid source location, then this is a definition
9590 /// of an __label__ label name, otherwise it is a normal label definition
9591 /// or use.
9592 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9593 SourceLocation GnuLabelLoc = SourceLocation());
9594
9595 /// Perform a name lookup for a label with the specified name; this does not
9596 /// create a new label if the lookup fails.
9597 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9598
9599 /// Look up the constructors for the given class.
9600 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9601
9602 /// Look up the default constructor for the given class.
9603 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9604
9605 /// Look up the copying constructor for the given class.
9606 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9607 unsigned Quals);
9608
9609 /// Look up the copying assignment operator for the given class.
9610 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9611 bool RValueThis, unsigned ThisQuals);
9612
9613 /// Look up the moving constructor for the given class.
9614 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9615 unsigned Quals);
9616
9617 /// Look up the moving assignment operator for the given class.
9618 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9619 bool RValueThis, unsigned ThisQuals);
9620
9621 /// Look for the destructor of the given class.
9622 ///
9623 /// During semantic analysis, this routine should be used in lieu of
9624 /// CXXRecordDecl::getDestructor().
9625 ///
9626 /// \returns The destructor for this class.
9627 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9628
9629 /// Force the declaration of any implicitly-declared members of this
9630 /// class.
9631 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9632
9633 /// Make a merged definition of an existing hidden definition \p ND
9634 /// visible at the specified location.
9635 void makeMergedDefinitionVisible(NamedDecl *ND);
9636
9637 /// Check ODR hashes for C/ObjC when merging types from modules.
9638 /// Differently from C++, actually parse the body and reject in case
9639 /// of a mismatch.
9640 template <typename T,
9641 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9642 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9643 if (Duplicate->getODRHash() != Previous->getODRHash())
9644 return false;
9645
9646 // Make the previous decl visible.
9647 makeMergedDefinitionVisible(ND: Previous);
9648 return true;
9649 }
9650
9651 /// Get the set of additional modules that should be checked during
9652 /// name lookup. A module and its imports become visible when instanting a
9653 /// template defined within it.
9654 llvm::DenseSet<Module *> &getLookupModules();
9655
9656 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9657 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9658
9659 /// Determine if the template parameter \p D has a visible default argument.
9660 bool
9661 hasVisibleDefaultArgument(const NamedDecl *D,
9662 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9663 /// Determine if the template parameter \p D has a reachable default argument.
9664 bool hasReachableDefaultArgument(
9665 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9666 /// Determine if the template parameter \p D has a reachable default argument.
9667 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9668 llvm::SmallVectorImpl<Module *> *Modules,
9669 Sema::AcceptableKind Kind);
9670
9671 /// Determine if there is a visible declaration of \p D that is an explicit
9672 /// specialization declaration for a specialization of a template. (For a
9673 /// member specialization, use hasVisibleMemberSpecialization.)
9674 bool hasVisibleExplicitSpecialization(
9675 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9676 /// Determine if there is a reachable declaration of \p D that is an explicit
9677 /// specialization declaration for a specialization of a template. (For a
9678 /// member specialization, use hasReachableMemberSpecialization.)
9679 bool hasReachableExplicitSpecialization(
9680 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9681
9682 /// Determine if there is a visible declaration of \p D that is a member
9683 /// specialization declaration (as opposed to an instantiated declaration).
9684 bool hasVisibleMemberSpecialization(
9685 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9686 /// Determine if there is a reachable declaration of \p D that is a member
9687 /// specialization declaration (as opposed to an instantiated declaration).
9688 bool hasReachableMemberSpecialization(
9689 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9690
9691 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9692
9693 /// Determine whether any declaration of an entity is visible.
9694 bool
9695 hasVisibleDeclaration(const NamedDecl *D,
9696 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9697 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9698 }
9699
9700 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9701 llvm::SmallVectorImpl<Module *> *Modules);
9702 /// Determine whether any declaration of an entity is reachable.
9703 bool
9704 hasReachableDeclaration(const NamedDecl *D,
9705 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9706 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9707 }
9708 bool hasReachableDeclarationSlow(
9709 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9710
9711 void diagnoseTypo(const TypoCorrection &Correction,
9712 const PartialDiagnostic &TypoDiag,
9713 bool ErrorRecovery = true);
9714
9715 /// Diagnose a successfully-corrected typo. Separated from the correction
9716 /// itself to allow external validation of the result, etc.
9717 ///
9718 /// \param Correction The result of performing typo correction.
9719 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9720 /// string added to it (and usually also a fixit).
9721 /// \param PrevNote A note to use when indicating the location of the entity
9722 /// to which we are correcting. Will have the correction string added
9723 /// to it.
9724 /// \param ErrorRecovery If \c true (the default), the caller is going to
9725 /// recover from the typo as if the corrected string had been typed.
9726 /// In this case, \c PDiag must be an error, and we will attach a fixit
9727 /// to it.
9728 void diagnoseTypo(const TypoCorrection &Correction,
9729 const PartialDiagnostic &TypoDiag,
9730 const PartialDiagnostic &PrevNote,
9731 bool ErrorRecovery = true);
9732
9733 /// Find the associated classes and namespaces for
9734 /// argument-dependent lookup for a call with the given set of
9735 /// arguments.
9736 ///
9737 /// This routine computes the sets of associated classes and associated
9738 /// namespaces searched by argument-dependent lookup
9739 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9740 void FindAssociatedClassesAndNamespaces(
9741 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9742 AssociatedNamespaceSet &AssociatedNamespaces,
9743 AssociatedClassSet &AssociatedClasses);
9744
9745 /// Produce a diagnostic describing the ambiguity that resulted
9746 /// from name lookup.
9747 ///
9748 /// \param Result The result of the ambiguous lookup to be diagnosed.
9749 void DiagnoseAmbiguousLookup(LookupResult &Result);
9750
9751 /// LookupLiteralOperator - Determine which literal operator should be used
9752 /// for a user-defined literal, per C++11 [lex.ext].
9753 ///
9754 /// Normal overload resolution is not used to select which literal operator to
9755 /// call for a user-defined literal. Look up the provided literal operator
9756 /// name, and filter the results to the appropriate set for the given argument
9757 /// types.
9758 LiteralOperatorLookupResult
9759 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9760 bool AllowRaw, bool AllowTemplate,
9761 bool AllowStringTemplate, bool DiagnoseMissing,
9762 StringLiteral *StringLit = nullptr);
9763
9764 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9765 ArrayRef<Expr *> Args, ADLResult &Functions);
9766
9767 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9768 VisibleDeclConsumer &Consumer,
9769 bool IncludeGlobalScope = true,
9770 bool LoadExternal = true);
9771 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9772 VisibleDeclConsumer &Consumer,
9773 bool IncludeGlobalScope = true,
9774 bool IncludeDependentBases = false,
9775 bool LoadExternal = true);
9776
9777 /// Try to "correct" a typo in the source code by finding
9778 /// visible declarations whose names are similar to the name that was
9779 /// present in the source code.
9780 ///
9781 /// \param TypoName the \c DeclarationNameInfo structure that contains
9782 /// the name that was present in the source code along with its location.
9783 ///
9784 /// \param LookupKind the name-lookup criteria used to search for the name.
9785 ///
9786 /// \param S the scope in which name lookup occurs.
9787 ///
9788 /// \param SS the nested-name-specifier that precedes the name we're
9789 /// looking for, if present.
9790 ///
9791 /// \param CCC A CorrectionCandidateCallback object that provides further
9792 /// validation of typo correction candidates. It also provides flags for
9793 /// determining the set of keywords permitted.
9794 ///
9795 /// \param MemberContext if non-NULL, the context in which to look for
9796 /// a member access expression.
9797 ///
9798 /// \param EnteringContext whether we're entering the context described by
9799 /// the nested-name-specifier SS.
9800 ///
9801 /// \param OPT when non-NULL, the search for visible declarations will
9802 /// also walk the protocols in the qualified interfaces of \p OPT.
9803 ///
9804 /// \returns a \c TypoCorrection containing the corrected name if the typo
9805 /// along with information such as the \c NamedDecl where the corrected name
9806 /// was declared, and any additional \c NestedNameSpecifier needed to access
9807 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9808 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9809 Sema::LookupNameKind LookupKind, Scope *S,
9810 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9811 CorrectTypoKind Mode,
9812 DeclContext *MemberContext = nullptr,
9813 bool EnteringContext = false,
9814 const ObjCObjectPointerType *OPT = nullptr,
9815 bool RecordFailure = true);
9816
9817 /// Kinds of missing import. Note, the values of these enumerators correspond
9818 /// to %select values in diagnostics.
9819 enum class MissingImportKind {
9820 Declaration,
9821 Definition,
9822 DefaultArgument,
9823 ExplicitSpecialization,
9824 PartialSpecialization
9825 };
9826
9827 /// Diagnose that the specified declaration needs to be visible but
9828 /// isn't, and suggest a module import that would resolve the problem.
9829 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9830 MissingImportKind MIK, bool Recover = true);
9831 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9832 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9833 MissingImportKind MIK, bool Recover);
9834
9835 /// Called on #pragma clang __debug dump II
9836 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9837
9838 /// Called on #pragma clang __debug dump E
9839 void ActOnPragmaDump(Expr *E);
9840
9841private:
9842 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9843 //
9844 // The boolean value will be true to indicate that the namespace was loaded
9845 // from an AST/PCH file, or false otherwise.
9846 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9847
9848 /// Whether we have already loaded known namespaces from an extenal
9849 /// source.
9850 bool LoadedExternalKnownNamespaces;
9851
9852 bool CppLookupName(LookupResult &R, Scope *S);
9853
9854 /// Determine if we could use all the declarations in the module.
9855 bool isUsableModule(const Module *M);
9856
9857 /// Helper for CorrectTypo used to create and populate a new
9858 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9859 /// skipped entirely.
9860 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9861 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9862 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9863 DeclContext *MemberContext, bool EnteringContext,
9864 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9865
9866 /// Cache for module units which is usable for current module.
9867 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9868
9869 /// Record the typo correction failure and return an empty correction.
9870 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9871 bool RecordFailure = true) {
9872 if (RecordFailure)
9873 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9874 return TypoCorrection();
9875 }
9876
9877 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9878
9879 /// Determine whether two declarations should be linked together, given that
9880 /// the old declaration might not be visible and the new declaration might
9881 /// not have external linkage.
9882 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9883 const NamedDecl *New) {
9884 if (isVisible(D: Old))
9885 return true;
9886 // See comment in below overload for why it's safe to compute the linkage
9887 // of the new declaration here.
9888 if (New->isExternallyDeclarable()) {
9889 assert(Old->isExternallyDeclarable() &&
9890 "should not have found a non-externally-declarable previous decl");
9891 return true;
9892 }
9893 return false;
9894 }
9895 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9896
9897 ///@}
9898
9899 //
9900 //
9901 // -------------------------------------------------------------------------
9902 //
9903 //
9904
9905 /// \name Modules
9906 /// Implementations are in SemaModule.cpp
9907 ///@{
9908
9909public:
9910 /// Get the module unit whose scope we are currently within.
9911 Module *getCurrentModule() const {
9912 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9913 }
9914
9915 /// Is the module scope we are an implementation unit?
9916 bool currentModuleIsImplementation() const {
9917 return ModuleScopes.empty()
9918 ? false
9919 : ModuleScopes.back().Module->isModuleImplementation();
9920 }
9921
9922 // When loading a non-modular PCH files, this is used to restore module
9923 // visibility.
9924 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9925 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
9926 }
9927
9928 enum class ModuleDeclKind {
9929 Interface, ///< 'export module X;'
9930 Implementation, ///< 'module X;'
9931 PartitionInterface, ///< 'export module X:Y;'
9932 PartitionImplementation, ///< 'module X:Y;'
9933 };
9934
9935 /// An enumeration to represent the transition of states in parsing module
9936 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9937 /// an error in state transition, the state is set to NotACXX20Module.
9938 enum class ModuleImportState {
9939 FirstDecl, ///< Parsing the first decl in a TU.
9940 GlobalFragment, ///< after 'module;' but before 'module X;'
9941 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9942 ImportFinished, ///< after any non-import decl.
9943 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9944 ///< non-import decl.
9945 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9946 ///< non-import decl has already been seen.
9947 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9948 };
9949
9950 /// The parser has processed a module-declaration that begins the definition
9951 /// of a module interface or implementation.
9952 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
9953 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9954 ModuleIdPath Path, ModuleIdPath Partition,
9955 ModuleImportState &ImportState,
9956 bool SeenNoTrivialPPDirective);
9957
9958 /// The parser has processed a global-module-fragment declaration that begins
9959 /// the definition of the global module fragment of the current module unit.
9960 /// \param ModuleLoc The location of the 'module' keyword.
9961 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
9962
9963 /// The parser has processed a private-module-fragment declaration that begins
9964 /// the definition of the private module fragment of the current module unit.
9965 /// \param ModuleLoc The location of the 'module' keyword.
9966 /// \param PrivateLoc The location of the 'private' keyword.
9967 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
9968 SourceLocation PrivateLoc);
9969
9970 /// The parser has processed a module import declaration.
9971 ///
9972 /// \param StartLoc The location of the first token in the declaration. This
9973 /// could be the location of an '@', 'export', or 'import'.
9974 /// \param ExportLoc The location of the 'export' keyword, if any.
9975 /// \param ImportLoc The location of the 'import' keyword.
9976 /// \param Path The module toplevel name as an access path.
9977 /// \param IsPartition If the name is for a partition.
9978 DeclResult ActOnModuleImport(SourceLocation StartLoc,
9979 SourceLocation ExportLoc,
9980 SourceLocation ImportLoc, ModuleIdPath Path,
9981 bool IsPartition = false);
9982 DeclResult ActOnModuleImport(SourceLocation StartLoc,
9983 SourceLocation ExportLoc,
9984 SourceLocation ImportLoc, Module *M,
9985 ModuleIdPath Path = {});
9986
9987 /// The parser has processed a module import translated from a
9988 /// #include or similar preprocessing directive.
9989 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9990 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
9991
9992 /// The parsed has entered a submodule.
9993 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
9994 /// The parser has left a submodule.
9995 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
9996
9997 /// Create an implicit import of the given module at the given
9998 /// source location, for error recovery, if possible.
9999 ///
10000 /// This routine is typically used when an entity found by name lookup
10001 /// is actually hidden within a module that we know about but the user
10002 /// has forgotten to import.
10003 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10004 Module *Mod);
10005
10006 /// We have parsed the start of an export declaration, including the '{'
10007 /// (if present).
10008 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10009 SourceLocation LBraceLoc);
10010
10011 /// Complete the definition of an export declaration.
10012 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10013 SourceLocation RBraceLoc);
10014
10015private:
10016 /// The parser has begun a translation unit to be compiled as a C++20
10017 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10018 void HandleStartOfHeaderUnit();
10019
10020 struct ModuleScope {
10021 SourceLocation BeginLoc;
10022 clang::Module *Module = nullptr;
10023 VisibleModuleSet OuterVisibleModules;
10024 };
10025 /// The modules we're currently parsing.
10026 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10027
10028 /// For an interface unit, this is the implicitly imported interface unit.
10029 clang::Module *ThePrimaryInterface = nullptr;
10030
10031 /// The explicit global module fragment of the current translation unit.
10032 /// The explicit Global Module Fragment, as specified in C++
10033 /// [module.global.frag].
10034 clang::Module *TheGlobalModuleFragment = nullptr;
10035
10036 /// The implicit global module fragments of the current translation unit.
10037 ///
10038 /// The contents in the implicit global module fragment can't be discarded.
10039 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10040
10041 /// Namespace definitions that we will export when they finish.
10042 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10043
10044 /// In a C++ standard module, inline declarations require a definition to be
10045 /// present at the end of a definition domain. This set holds the decls to
10046 /// be checked at the end of the TU.
10047 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10048
10049 /// Helper function to judge if we are in module purview.
10050 /// Return false if we are not in a module.
10051 bool isCurrentModulePurview() const;
10052
10053 /// Enter the scope of the explicit global module fragment.
10054 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10055 /// Leave the scope of the explicit global module fragment.
10056 void PopGlobalModuleFragment();
10057
10058 /// Enter the scope of an implicit global module fragment.
10059 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10060 /// Leave the scope of an implicit global module fragment.
10061 void PopImplicitGlobalModuleFragment();
10062
10063 VisibleModuleSet VisibleModules;
10064
10065 /// Whether we had imported any named modules.
10066 bool HadImportedNamedModules = false;
10067 /// The set of instantiations we need to check if they references TU-local
10068 /// entity from TUs. This only makes sense if we imported any named modules.
10069 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10070 PendingCheckReferenceForTULocal;
10071 /// Implement [basic.link]p18, which requires that we can't use TU-local
10072 /// entities from other TUs (ignoring header units).
10073 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10074 SourceLocation PointOfInstantiation);
10075 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10076 /// module interface or module partition.
10077 void checkExposure(const TranslationUnitDecl *TU);
10078
10079 ///@}
10080
10081 //
10082 //
10083 // -------------------------------------------------------------------------
10084 //
10085 //
10086
10087 /// \name C++ Overloading
10088 /// Implementations are in SemaOverload.cpp
10089 ///@{
10090
10091public:
10092 /// Whether deferrable diagnostics should be deferred.
10093 bool DeferDiags = false;
10094
10095 /// RAII class to control scope of DeferDiags.
10096 class DeferDiagsRAII {
10097 Sema &S;
10098 bool SavedDeferDiags = false;
10099
10100 public:
10101 DeferDiagsRAII(Sema &S, bool DeferDiags)
10102 : S(S), SavedDeferDiags(S.DeferDiags) {
10103 S.DeferDiags = SavedDeferDiags || DeferDiags;
10104 }
10105 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10106 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10107 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10108 };
10109
10110 /// Flag indicating if Sema is building a recovery call expression.
10111 ///
10112 /// This flag is used to avoid building recovery call expressions
10113 /// if Sema is already doing so, which would cause infinite recursions.
10114 bool IsBuildingRecoveryCallExpr;
10115
10116 /// Determine whether the given New declaration is an overload of the
10117 /// declarations in Old. This routine returns OverloadKind::Match or
10118 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10119 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10120 /// Old declarations aren't functions (or function templates) at all. When it
10121 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10122 /// will point to the decl that New cannot be overloaded with. This decl may
10123 /// be a UsingShadowDecl on top of the underlying declaration.
10124 ///
10125 /// Example: Given the following input:
10126 ///
10127 /// void f(int, float); // #1
10128 /// void f(int, int); // #2
10129 /// int f(int, int); // #3
10130 ///
10131 /// When we process #1, there is no previous declaration of "f", so IsOverload
10132 /// will not be used.
10133 ///
10134 /// When we process #2, Old contains only the FunctionDecl for #1. By
10135 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10136 /// they have different signatures), so this routine returns
10137 /// OverloadKind::Overload; MatchedDecl is unchanged.
10138 ///
10139 /// When we process #3, Old is an overload set containing #1 and #2. We
10140 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10141 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10142 /// types of functions are not part of the signature), IsOverload returns
10143 /// OverloadKind::Match and MatchedDecl will be set to point to the
10144 /// FunctionDecl for #2.
10145 ///
10146 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10147 /// class by a using declaration. The rules for whether to hide shadow
10148 /// declarations ignore some properties which otherwise figure into a function
10149 /// template's signature.
10150 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10151 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10152 bool UseMemberUsingDeclRules);
10153 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10154 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10155
10156 // Checks whether MD constitutes an override the base class method BaseMD.
10157 // When checking for overrides, the object object members are ignored.
10158 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10159 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10160
10161 enum class AllowedExplicit {
10162 /// Allow no explicit functions to be used.
10163 None,
10164 /// Allow explicit conversion functions but not explicit constructors.
10165 Conversions,
10166 /// Allow both explicit conversion functions and explicit constructors.
10167 All
10168 };
10169
10170 ImplicitConversionSequence TryImplicitConversion(
10171 Expr *From, QualType ToType, bool SuppressUserConversions,
10172 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10173 bool AllowObjCWritebackConversion);
10174
10175 /// PerformImplicitConversion - Perform an implicit conversion of the
10176 /// expression From to the type ToType. Returns the
10177 /// converted expression. Flavor is the kind of conversion we're
10178 /// performing, used in the error message. If @p AllowExplicit,
10179 /// explicit user-defined conversions are permitted.
10180 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10181 AssignmentAction Action,
10182 bool AllowExplicit = false);
10183
10184 /// IsIntegralPromotion - Determines whether the conversion from the
10185 /// expression From (whose potentially-adjusted type is FromType) to
10186 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10187 /// sets PromotedType to the promoted type.
10188 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10189
10190 /// IsFloatingPointPromotion - Determines whether the conversion from
10191 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10192 /// returns true and sets PromotedType to the promoted type.
10193 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10194
10195 /// Determine if a conversion is a complex promotion.
10196 ///
10197 /// A complex promotion is defined as a complex -> complex conversion
10198 /// where the conversion between the underlying real types is a
10199 /// floating-point or integral promotion.
10200 bool IsComplexPromotion(QualType FromType, QualType ToType);
10201
10202 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10203 /// FromType to ToType involves an OverflowBehaviorType FromType being
10204 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10205 /// If so, returns true and sets FromType to ToType.
10206 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10207
10208 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10209 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10210 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10211 /// ToType.
10212 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10213
10214 /// IsPointerConversion - Determines whether the conversion of the
10215 /// expression From, which has the (possibly adjusted) type FromType,
10216 /// can be converted to the type ToType via a pointer conversion (C++
10217 /// 4.10). If so, returns true and places the converted type (that
10218 /// might differ from ToType in its cv-qualifiers at some level) into
10219 /// ConvertedType.
10220 ///
10221 /// This routine also supports conversions to and from block pointers
10222 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10223 /// pointers to interfaces. FIXME: Once we've determined the
10224 /// appropriate overloading rules for Objective-C, we may want to
10225 /// split the Objective-C checks into a different routine; however,
10226 /// GCC seems to consider all of these conversions to be pointer
10227 /// conversions, so for now they live here. IncompatibleObjC will be
10228 /// set if the conversion is an allowed Objective-C conversion that
10229 /// should result in a warning.
10230 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10231 bool InOverloadResolution, QualType &ConvertedType,
10232 bool &IncompatibleObjC);
10233
10234 /// isObjCPointerConversion - Determines whether this is an
10235 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10236 /// with the same arguments and return values.
10237 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10238 QualType &ConvertedType, bool &IncompatibleObjC);
10239 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10240 QualType &ConvertedType);
10241
10242 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10243 /// for equality of their parameter types. Caller has already checked that
10244 /// they have same number of parameters. If the parameters are different,
10245 /// ArgPos will have the parameter index of the first different parameter.
10246 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10247 /// reverse order. That's useful if one of the functions is being used as a
10248 /// C++20 synthesized operator overload with a reversed parameter order.
10249 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10250 ArrayRef<QualType> New,
10251 unsigned *ArgPos = nullptr,
10252 bool Reversed = false);
10253
10254 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10255 const FunctionProtoType *NewType,
10256 unsigned *ArgPos = nullptr,
10257 bool Reversed = false);
10258
10259 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10260 const FunctionDecl *NewFunction,
10261 unsigned *ArgPos = nullptr,
10262 bool Reversed = false);
10263
10264 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10265 /// function types. Catches different number of parameter, mismatch in
10266 /// parameter types, and different return types.
10267 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10268 QualType ToType);
10269
10270 /// CheckPointerConversion - Check the pointer conversion from the
10271 /// expression From to the type ToType. This routine checks for
10272 /// ambiguous or inaccessible derived-to-base pointer
10273 /// conversions for which IsPointerConversion has already returned
10274 /// true. It returns true and produces a diagnostic if there was an
10275 /// error, or returns false otherwise.
10276 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10277 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10278 bool Diagnose = true);
10279
10280 /// IsMemberPointerConversion - Determines whether the conversion of the
10281 /// expression From, which has the (possibly adjusted) type FromType, can be
10282 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10283 /// If so, returns true and places the converted type (that might differ from
10284 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10285 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10286 bool InOverloadResolution,
10287 QualType &ConvertedType);
10288
10289 enum class MemberPointerConversionResult {
10290 Success,
10291 DifferentPointee,
10292 NotDerived,
10293 Ambiguous,
10294 Virtual,
10295 Inaccessible
10296 };
10297 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10298 /// CheckMemberPointerConversion - Check the member pointer conversion from
10299 /// the expression From to the type ToType. This routine checks for ambiguous
10300 /// or virtual or inaccessible base-to-derived member pointer conversions for
10301 /// which IsMemberPointerConversion has already returned true. It produces a
10302 // diagnostic if there was an error.
10303 MemberPointerConversionResult CheckMemberPointerConversion(
10304 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10305 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10306 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10307
10308 /// IsQualificationConversion - Determines whether the conversion from
10309 /// an rvalue of type FromType to ToType is a qualification conversion
10310 /// (C++ 4.4).
10311 ///
10312 /// \param ObjCLifetimeConversion Output parameter that will be set to
10313 /// indicate when the qualification conversion involves a change in the
10314 /// Objective-C object lifetime.
10315 bool IsQualificationConversion(QualType FromType, QualType ToType,
10316 bool CStyle, bool &ObjCLifetimeConversion);
10317
10318 /// Determine whether the conversion from FromType to ToType is a valid
10319 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10320 /// More precisely, this method checks whether FromType can be transformed
10321 /// into an exact match for ToType, by transforming its extended function
10322 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10323 /// or "noexcept", or by stripping "noescape" for arguments).
10324 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10325
10326 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10327 /// `ResultTy` to `ToType`.
10328 bool TryFunctionConversion(QualType FromType, QualType ToType,
10329 QualType &ResultTy) const;
10330
10331 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10332 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10333 DeclarationName Name,
10334 OverloadCandidateSet &CandidateSet,
10335 FunctionDecl *Fn, MultiExprArg Args,
10336 bool IsMember = false);
10337
10338 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10339 FunctionDecl *Fun);
10340 ExprResult PerformImplicitObjectArgumentInitialization(
10341 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10342 CXXMethodDecl *Method);
10343
10344 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10345 /// of the expression From to bool (C++0x [conv]p3).
10346 ExprResult PerformContextuallyConvertToBool(Expr *From);
10347
10348 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10349 /// conversion of the expression From to an Objective-C pointer type.
10350 /// Returns a valid but null ExprResult if no conversion sequence exists.
10351 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10352
10353 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10354 CCEKind CCE,
10355 NamedDecl *Dest = nullptr);
10356
10357 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10358 llvm::APSInt &Value, CCEKind CCE);
10359 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10360 APValue &Value, CCEKind CCE,
10361 NamedDecl *Dest = nullptr);
10362
10363 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10364 /// That is a converted constant expression
10365 /// (which was built with BuildConvertedConstantExpression)
10366 ExprResult
10367 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10368 CCEKind CCE, bool RequireInt,
10369 const APValue &PreNarrowingValue);
10370
10371 /// Abstract base class used to perform a contextual implicit
10372 /// conversion from an expression to any type passing a filter.
10373 class ContextualImplicitConverter {
10374 public:
10375 bool Suppress;
10376 bool SuppressConversion;
10377
10378 ContextualImplicitConverter(bool Suppress = false,
10379 bool SuppressConversion = false)
10380 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10381
10382 /// Determine whether the specified type is a valid destination type
10383 /// for this conversion.
10384 virtual bool match(QualType T) = 0;
10385
10386 /// Emits a diagnostic complaining that the expression does not have
10387 /// integral or enumeration type.
10388 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10389 QualType T) = 0;
10390
10391 /// Emits a diagnostic when the expression has incomplete class type.
10392 virtual SemaDiagnosticBuilder
10393 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10394
10395 /// Emits a diagnostic when the only matching conversion function
10396 /// is explicit.
10397 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10398 SourceLocation Loc,
10399 QualType T,
10400 QualType ConvTy) = 0;
10401
10402 /// Emits a note for the explicit conversion function.
10403 virtual SemaDiagnosticBuilder
10404 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10405
10406 /// Emits a diagnostic when there are multiple possible conversion
10407 /// functions.
10408 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10409 QualType T) = 0;
10410
10411 /// Emits a note for one of the candidate conversions.
10412 virtual SemaDiagnosticBuilder
10413 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10414
10415 /// Emits a diagnostic when we picked a conversion function
10416 /// (for cases when we are not allowed to pick a conversion function).
10417 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10418 SourceLocation Loc,
10419 QualType T,
10420 QualType ConvTy) = 0;
10421
10422 virtual ~ContextualImplicitConverter() {}
10423 };
10424
10425 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10426 bool AllowScopedEnumerations;
10427
10428 public:
10429 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10430 bool SuppressConversion)
10431 : ContextualImplicitConverter(Suppress, SuppressConversion),
10432 AllowScopedEnumerations(AllowScopedEnumerations) {}
10433
10434 /// Match an integral or (possibly scoped) enumeration type.
10435 bool match(QualType T) override;
10436
10437 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10438 QualType T) override {
10439 return diagnoseNotInt(S, Loc, T);
10440 }
10441
10442 /// Emits a diagnostic complaining that the expression does not have
10443 /// integral or enumeration type.
10444 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10445 QualType T) = 0;
10446 };
10447
10448 /// Perform a contextual implicit conversion.
10449 ExprResult
10450 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10451 ContextualImplicitConverter &Converter);
10452
10453 /// ReferenceCompareResult - Expresses the result of comparing two
10454 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10455 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10456 enum ReferenceCompareResult {
10457 /// Ref_Incompatible - The two types are incompatible, so direct
10458 /// reference binding is not possible.
10459 Ref_Incompatible = 0,
10460 /// Ref_Related - The two types are reference-related, which means
10461 /// that their unqualified forms (T1 and T2) are either the same
10462 /// or T1 is a base class of T2.
10463 Ref_Related,
10464 /// Ref_Compatible - The two types are reference-compatible.
10465 Ref_Compatible
10466 };
10467
10468 // Fake up a scoped enumeration that still contextually converts to bool.
10469 struct ReferenceConversionsScope {
10470 /// The conversions that would be performed on an lvalue of type T2 when
10471 /// binding a reference of type T1 to it, as determined when evaluating
10472 /// whether T1 is reference-compatible with T2.
10473 enum ReferenceConversions {
10474 Qualification = 0x1,
10475 NestedQualification = 0x2,
10476 Function = 0x4,
10477 DerivedToBase = 0x8,
10478 ObjC = 0x10,
10479 ObjCLifetime = 0x20,
10480
10481 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10482 };
10483 };
10484 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10485
10486 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10487 /// determine whether they are reference-compatible,
10488 /// reference-related, or incompatible, for use in C++ initialization by
10489 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10490 /// type, and the first type (T1) is the pointee type of the reference
10491 /// type being initialized.
10492 ReferenceCompareResult
10493 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10494 ReferenceConversions *Conv = nullptr);
10495
10496 /// AddOverloadCandidate - Adds the given function to the set of
10497 /// candidate functions, using the given function call arguments. If
10498 /// @p SuppressUserConversions, then don't allow user-defined
10499 /// conversions via constructors or conversion operators.
10500 ///
10501 /// \param PartialOverloading true if we are performing "partial" overloading
10502 /// based on an incomplete set of function arguments. This feature is used by
10503 /// code completion.
10504 void AddOverloadCandidate(
10505 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10506 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10507 bool PartialOverloading = false, bool AllowExplicit = true,
10508 bool AllowExplicitConversion = false,
10509 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10510 ConversionSequenceList EarlyConversions = {},
10511 OverloadCandidateParamOrder PO = {},
10512 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10513
10514 /// Add all of the function declarations in the given function set to
10515 /// the overload candidate set.
10516 void AddFunctionCandidates(
10517 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10518 OverloadCandidateSet &CandidateSet,
10519 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10520 bool SuppressUserConversions = false, bool PartialOverloading = false,
10521 bool FirstArgumentIsBase = false);
10522
10523 /// AddMethodCandidate - Adds a named decl (which is some kind of
10524 /// method) as a method candidate to the given overload set.
10525 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10526 Expr::Classification ObjectClassification,
10527 ArrayRef<Expr *> Args,
10528 OverloadCandidateSet &CandidateSet,
10529 bool SuppressUserConversion = false,
10530 OverloadCandidateParamOrder PO = {});
10531
10532 /// AddMethodCandidate - Adds the given C++ member function to the set
10533 /// of candidate functions, using the given function call arguments
10534 /// and the object argument (@c Object). For example, in a call
10535 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10536 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10537 /// allow user-defined conversions via constructors or conversion
10538 /// operators.
10539 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10540 CXXRecordDecl *ActingContext, QualType ObjectType,
10541 Expr::Classification ObjectClassification,
10542 ArrayRef<Expr *> Args,
10543 OverloadCandidateSet &CandidateSet,
10544 bool SuppressUserConversions = false,
10545 bool PartialOverloading = false,
10546 ConversionSequenceList EarlyConversions = {},
10547 OverloadCandidateParamOrder PO = {},
10548 bool StrictPackMatch = false);
10549
10550 /// Add a C++ member function template as a candidate to the candidate
10551 /// set, using template argument deduction to produce an appropriate member
10552 /// function template specialization.
10553 void AddMethodTemplateCandidate(
10554 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10555 CXXRecordDecl *ActingContext,
10556 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10557 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10558 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10559 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10560
10561 /// Add a C++ function template specialization as a candidate
10562 /// in the candidate set, using template argument deduction to produce
10563 /// an appropriate function template specialization.
10564 void AddTemplateOverloadCandidate(
10565 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10566 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10567 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10568 bool PartialOverloading = false, bool AllowExplicit = true,
10569 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10570 OverloadCandidateParamOrder PO = {},
10571 bool AggregateCandidateDeduction = false);
10572
10573 struct CheckNonDependentConversionsFlag {
10574 /// Do not consider any user-defined conversions when constructing the
10575 /// initializing sequence.
10576 bool SuppressUserConversions;
10577
10578 /// Before constructing the initializing sequence, we check whether the
10579 /// parameter type and argument type contain any user defined conversions.
10580 /// If so, do not initialize them. This effectively bypasses some undesired
10581 /// instantiation before checking constaints, which might otherwise result
10582 /// in non-SFINAE errors e.g. recursive constraints.
10583 bool OnlyInitializeNonUserDefinedConversions;
10584
10585 CheckNonDependentConversionsFlag(
10586 bool SuppressUserConversions,
10587 bool OnlyInitializeNonUserDefinedConversions)
10588 : SuppressUserConversions(SuppressUserConversions),
10589 OnlyInitializeNonUserDefinedConversions(
10590 OnlyInitializeNonUserDefinedConversions) {}
10591 };
10592
10593 /// Check that implicit conversion sequences can be formed for each argument
10594 /// whose corresponding parameter has a non-dependent type, per DR1391's
10595 /// [temp.deduct.call]p10.
10596 bool CheckNonDependentConversions(
10597 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10598 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10599 ConversionSequenceList &Conversions,
10600 CheckNonDependentConversionsFlag UserConversionFlag,
10601 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10602 Expr::Classification ObjectClassification = {},
10603 OverloadCandidateParamOrder PO = {});
10604
10605 /// AddConversionCandidate - Add a C++ conversion function as a
10606 /// candidate in the candidate set (C++ [over.match.conv],
10607 /// C++ [over.match.copy]). From is the expression we're converting from,
10608 /// and ToType is the type that we're eventually trying to convert to
10609 /// (which may or may not be the same type as the type that the
10610 /// conversion function produces).
10611 void AddConversionCandidate(
10612 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10613 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10614 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10615 bool AllowExplicit, bool AllowResultConversion = true,
10616 bool StrictPackMatch = false);
10617
10618 /// Adds a conversion function template specialization
10619 /// candidate to the overload set, using template argument deduction
10620 /// to deduce the template arguments of the conversion function
10621 /// template from the type that we are converting to (C++
10622 /// [temp.deduct.conv]).
10623 void AddTemplateConversionCandidate(
10624 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10625 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10626 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10627 bool AllowExplicit, bool AllowResultConversion = true);
10628
10629 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10630 /// converts the given @c Object to a function pointer via the
10631 /// conversion function @c Conversion, and then attempts to call it
10632 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10633 /// the type of function that we'll eventually be calling.
10634 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10635 DeclAccessPair FoundDecl,
10636 CXXRecordDecl *ActingContext,
10637 const FunctionProtoType *Proto, Expr *Object,
10638 ArrayRef<Expr *> Args,
10639 OverloadCandidateSet &CandidateSet);
10640
10641 /// Add all of the non-member operator function declarations in the given
10642 /// function set to the overload candidate set.
10643 void AddNonMemberOperatorCandidates(
10644 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10645 OverloadCandidateSet &CandidateSet,
10646 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10647
10648 /// Add overload candidates for overloaded operators that are
10649 /// member functions.
10650 ///
10651 /// Add the overloaded operator candidates that are member functions
10652 /// for the operator Op that was used in an operator expression such
10653 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10654 /// CandidateSet will store the added overload candidates. (C++
10655 /// [over.match.oper]).
10656 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10657 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10658 OverloadCandidateSet &CandidateSet,
10659 OverloadCandidateParamOrder PO = {});
10660
10661 /// AddBuiltinCandidate - Add a candidate for a built-in
10662 /// operator. ResultTy and ParamTys are the result and parameter types
10663 /// of the built-in candidate, respectively. Args and NumArgs are the
10664 /// arguments being passed to the candidate. IsAssignmentOperator
10665 /// should be true when this built-in candidate is an assignment
10666 /// operator. NumContextualBoolArguments is the number of arguments
10667 /// (at the beginning of the argument list) that will be contextually
10668 /// converted to bool.
10669 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10670 OverloadCandidateSet &CandidateSet,
10671 bool IsAssignmentOperator = false,
10672 unsigned NumContextualBoolArguments = 0);
10673
10674 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10675 /// operator overloads to the candidate set (C++ [over.built]), based
10676 /// on the operator @p Op and the arguments given. For example, if the
10677 /// operator is a binary '+', this routine might add "int
10678 /// operator+(int, int)" to cover integer addition.
10679 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10680 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10681 OverloadCandidateSet &CandidateSet);
10682
10683 /// Add function candidates found via argument-dependent lookup
10684 /// to the set of overloading candidates.
10685 ///
10686 /// This routine performs argument-dependent name lookup based on the
10687 /// given function name (which may also be an operator name) and adds
10688 /// all of the overload candidates found by ADL to the overload
10689 /// candidate set (C++ [basic.lookup.argdep]).
10690 void AddArgumentDependentLookupCandidates(
10691 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10692 TemplateArgumentListInfo *ExplicitTemplateArgs,
10693 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10694
10695 /// Check the enable_if expressions on the given function. Returns the first
10696 /// failing attribute, or NULL if they were all successful.
10697 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10698 ArrayRef<Expr *> Args,
10699 bool MissingImplicitThis = false);
10700
10701 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10702 /// non-ArgDependent DiagnoseIfAttrs.
10703 ///
10704 /// Argument-dependent diagnose_if attributes should be checked each time a
10705 /// function is used as a direct callee of a function call.
10706 ///
10707 /// Returns true if any errors were emitted.
10708 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10709 const Expr *ThisArg,
10710 ArrayRef<const Expr *> Args,
10711 SourceLocation Loc);
10712
10713 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10714 /// ArgDependent DiagnoseIfAttrs.
10715 ///
10716 /// Argument-independent diagnose_if attributes should be checked on every use
10717 /// of a function.
10718 ///
10719 /// Returns true if any errors were emitted.
10720 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10721 SourceLocation Loc);
10722
10723 /// Determine if \p A and \p B are equivalent internal linkage declarations
10724 /// from different modules, and thus an ambiguity error can be downgraded to
10725 /// an extension warning.
10726 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10727 const NamedDecl *B);
10728 void diagnoseEquivalentInternalLinkageDeclarations(
10729 SourceLocation Loc, const NamedDecl *D,
10730 ArrayRef<const NamedDecl *> Equiv);
10731
10732 // Emit as a 'note' the specific overload candidate
10733 void NoteOverloadCandidate(
10734 const NamedDecl *Found, const FunctionDecl *Fn,
10735 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10736 QualType DestType = QualType(), bool TakingAddress = false);
10737
10738 // Emit as a series of 'note's all template and non-templates identified by
10739 // the expression Expr
10740 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10741 bool TakingAddress = false);
10742
10743 /// Returns whether the given function's address can be taken or not,
10744 /// optionally emitting a diagnostic if the address can't be taken.
10745 ///
10746 /// Returns false if taking the address of the function is illegal.
10747 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10748 bool Complain = false,
10749 SourceLocation Loc = SourceLocation());
10750
10751 // [PossiblyAFunctionType] --> [Return]
10752 // NonFunctionType --> NonFunctionType
10753 // R (A) --> R(A)
10754 // R (*)(A) --> R (A)
10755 // R (&)(A) --> R (A)
10756 // R (S::*)(A) --> R (A)
10757 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10758
10759 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10760 /// an overloaded function (C++ [over.over]), where @p From is an
10761 /// expression with overloaded function type and @p ToType is the type
10762 /// we're trying to resolve to. For example:
10763 ///
10764 /// @code
10765 /// int f(double);
10766 /// int f(int);
10767 ///
10768 /// int (*pfd)(double) = f; // selects f(double)
10769 /// @endcode
10770 ///
10771 /// This routine returns the resulting FunctionDecl if it could be
10772 /// resolved, and NULL otherwise. When @p Complain is true, this
10773 /// routine will emit diagnostics if there is an error.
10774 FunctionDecl *
10775 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10776 bool Complain, DeclAccessPair &Found,
10777 bool *pHadMultipleCandidates = nullptr);
10778
10779 /// Given an expression that refers to an overloaded function, try to
10780 /// resolve that function to a single function that can have its address
10781 /// taken. This will modify `Pair` iff it returns non-null.
10782 ///
10783 /// This routine can only succeed if from all of the candidates in the
10784 /// overload set for SrcExpr that can have their addresses taken, there is one
10785 /// candidate that is more constrained than the rest.
10786 FunctionDecl *
10787 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10788
10789 /// Given an overloaded function, tries to turn it into a non-overloaded
10790 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10791 /// will perform access checks, diagnose the use of the resultant decl, and,
10792 /// if requested, potentially perform a function-to-pointer decay.
10793 ///
10794 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10795 /// Otherwise, returns true. This may emit diagnostics and return true.
10796 bool resolveAndFixAddressOfSingleOverloadCandidate(
10797 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10798
10799 /// Given an expression that refers to an overloaded function, try to
10800 /// resolve that overloaded function expression down to a single function.
10801 ///
10802 /// This routine can only resolve template-ids that refer to a single function
10803 /// template, where that template-id refers to a single template whose
10804 /// template arguments are either provided by the template-id or have
10805 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10806 ///
10807 /// If no template-ids are found, no diagnostics are emitted and NULL is
10808 /// returned.
10809 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10810 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10811 TemplateSpecCandidateSet *FailedTSC = nullptr,
10812 bool ForTypeDeduction = false);
10813
10814 // Resolve and fix an overloaded expression that can be resolved
10815 // because it identifies a single function template specialization.
10816 //
10817 // Last three arguments should only be supplied if Complain = true
10818 //
10819 // Return true if it was logically possible to so resolve the
10820 // expression, regardless of whether or not it succeeded. Always
10821 // returns true if 'complain' is set.
10822 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10823 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10824 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10825 QualType DestTypeForComplaining = QualType(),
10826 unsigned DiagIDForComplaining = 0);
10827
10828 /// Add the overload candidates named by callee and/or found by argument
10829 /// dependent lookup to the given overload set.
10830 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10831 ArrayRef<Expr *> Args,
10832 OverloadCandidateSet &CandidateSet,
10833 bool PartialOverloading = false);
10834
10835 /// Add the call candidates from the given set of lookup results to the given
10836 /// overload set. Non-function lookup results are ignored.
10837 void AddOverloadedCallCandidates(
10838 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10839 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10840
10841 // An enum used to represent the different possible results of building a
10842 // range-based for loop.
10843 enum ForRangeStatus {
10844 FRS_Success,
10845 FRS_NoViableFunction,
10846 FRS_DiagnosticIssued
10847 };
10848
10849 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10850 /// given LookupResult is non-empty, it is assumed to describe a member which
10851 /// will be invoked. Otherwise, the function will be found via argument
10852 /// dependent lookup.
10853 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10854 /// otherwise CallExpr is set to ExprError() and some non-success value
10855 /// is returned.
10856 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10857 SourceLocation RangeLoc,
10858 const DeclarationNameInfo &NameInfo,
10859 LookupResult &MemberLookup,
10860 OverloadCandidateSet *CandidateSet,
10861 Expr *Range, ExprResult *CallExpr);
10862
10863 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10864 /// (which eventually refers to the declaration Func) and the call
10865 /// arguments Args/NumArgs, attempt to resolve the function call down
10866 /// to a specific function. If overload resolution succeeds, returns
10867 /// the call expression produced by overload resolution.
10868 /// Otherwise, emits diagnostics and returns ExprError.
10869 ExprResult BuildOverloadedCallExpr(
10870 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10871 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10872 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10873
10874 /// Constructs and populates an OverloadedCandidateSet from
10875 /// the given function.
10876 /// \returns true when an the ExprResult output parameter has been set.
10877 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10878 MultiExprArg Args, SourceLocation RParenLoc,
10879 OverloadCandidateSet *CandidateSet,
10880 ExprResult *Result);
10881
10882 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10883 NestedNameSpecifierLoc NNSLoc,
10884 DeclarationNameInfo DNI,
10885 const UnresolvedSetImpl &Fns,
10886 bool PerformADL = true);
10887
10888 /// Create a unary operation that may resolve to an overloaded
10889 /// operator.
10890 ///
10891 /// \param OpLoc The location of the operator itself (e.g., '*').
10892 ///
10893 /// \param Opc The UnaryOperatorKind that describes this operator.
10894 ///
10895 /// \param Fns The set of non-member functions that will be
10896 /// considered by overload resolution. The caller needs to build this
10897 /// set based on the context using, e.g.,
10898 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10899 /// set should not contain any member functions; those will be added
10900 /// by CreateOverloadedUnaryOp().
10901 ///
10902 /// \param Input The input argument.
10903 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10904 UnaryOperatorKind Opc,
10905 const UnresolvedSetImpl &Fns, Expr *input,
10906 bool RequiresADL = true);
10907
10908 /// Perform lookup for an overloaded binary operator.
10909 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10910 OverloadedOperatorKind Op,
10911 const UnresolvedSetImpl &Fns,
10912 ArrayRef<Expr *> Args, bool RequiresADL = true);
10913
10914 /// Create a binary operation that may resolve to an overloaded
10915 /// operator.
10916 ///
10917 /// \param OpLoc The location of the operator itself (e.g., '+').
10918 ///
10919 /// \param Opc The BinaryOperatorKind that describes this operator.
10920 ///
10921 /// \param Fns The set of non-member functions that will be
10922 /// considered by overload resolution. The caller needs to build this
10923 /// set based on the context using, e.g.,
10924 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10925 /// set should not contain any member functions; those will be added
10926 /// by CreateOverloadedBinOp().
10927 ///
10928 /// \param LHS Left-hand argument.
10929 /// \param RHS Right-hand argument.
10930 /// \param PerformADL Whether to consider operator candidates found by ADL.
10931 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10932 /// C++20 operator rewrites.
10933 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10934 /// the function in question. Such a function is never a candidate in
10935 /// our overload resolution. This also enables synthesizing a three-way
10936 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10937 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
10938 const UnresolvedSetImpl &Fns, Expr *LHS,
10939 Expr *RHS, bool RequiresADL = true,
10940 bool AllowRewrittenCandidates = true,
10941 FunctionDecl *DefaultedFn = nullptr);
10942 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
10943 const UnresolvedSetImpl &Fns,
10944 Expr *LHS, Expr *RHS,
10945 FunctionDecl *DefaultedFn);
10946
10947 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10948 SourceLocation RLoc, Expr *Base,
10949 MultiExprArg Args);
10950
10951 /// BuildCallToMemberFunction - Build a call to a member
10952 /// function. MemExpr is the expression that refers to the member
10953 /// function (and includes the object parameter), Args/NumArgs are the
10954 /// arguments to the function call (not including the object
10955 /// parameter). The caller needs to validate that the member
10956 /// expression refers to a non-static member function or an overloaded
10957 /// member function.
10958 ExprResult BuildCallToMemberFunction(
10959 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10960 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10961 bool IsExecConfig = false, bool AllowRecovery = false);
10962
10963 /// BuildCallToObjectOfClassType - Build a call to an object of class
10964 /// type (C++ [over.call.object]), which can end up invoking an
10965 /// overloaded function call operator (@c operator()) or performing a
10966 /// user-defined conversion on the object argument.
10967 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
10968 SourceLocation LParenLoc,
10969 MultiExprArg Args,
10970 SourceLocation RParenLoc);
10971
10972 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
10973 /// (if one exists), where @c Base is an expression of class type and
10974 /// @c Member is the name of the member we're trying to find.
10975 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
10976 SourceLocation OpLoc,
10977 bool *NoArrowOperatorFound = nullptr);
10978
10979 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
10980 CXXConversionDecl *Method,
10981 bool HadMultipleCandidates);
10982
10983 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
10984 /// to a literal operator described by the provided lookup results.
10985 ExprResult BuildLiteralOperatorCall(
10986 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
10987 SourceLocation LitEndLoc,
10988 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10989
10990 /// FixOverloadedFunctionReference - E is an expression that refers to
10991 /// a C++ overloaded function (possibly with some parentheses and
10992 /// perhaps a '&' around it). We have resolved the overloaded function
10993 /// to the function declaration Fn, so patch up the expression E to
10994 /// refer (possibly indirectly) to Fn. Returns the new expr.
10995 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
10996 FunctionDecl *Fn);
10997 ExprResult FixOverloadedFunctionReference(ExprResult,
10998 DeclAccessPair FoundDecl,
10999 FunctionDecl *Fn);
11000
11001 /// - Returns a selector which best matches given argument list or
11002 /// nullptr if none could be found
11003 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11004 bool IsInstance,
11005 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11006
11007 ///@}
11008
11009 //
11010 //
11011 // -------------------------------------------------------------------------
11012 //
11013 //
11014
11015 /// \name Statements
11016 /// Implementations are in SemaStmt.cpp
11017 ///@{
11018
11019public:
11020 /// Stack of active SEH __finally scopes. Can be empty.
11021 SmallVector<Scope *, 2> CurrentSEHFinally;
11022
11023 /// Stack of '_Defer' statements that are currently being parsed, as well
11024 /// as the locations of their '_Defer' keywords. Can be empty.
11025 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11026
11027 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11028 StmtResult ActOnExprStmtError();
11029
11030 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11031 bool HasLeadingEmptyMacro = false);
11032
11033 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11034 SourceLocation EndLoc);
11035 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11036
11037 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11038 /// whose result is unused, warn.
11039 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11040
11041 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11042 void ActOnAfterCompoundStatementLeadingPragmas();
11043 void ActOnFinishOfCompoundStmt();
11044 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11045 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11046
11047 sema::CompoundScopeInfo &getCurCompoundScope() const;
11048
11049 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11050 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11051 SourceLocation DotDotDotLoc, ExprResult RHS,
11052 SourceLocation ColonLoc);
11053
11054 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11055 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11056
11057 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11058 SourceLocation ColonLoc, Stmt *SubStmt,
11059 Scope *CurScope);
11060 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11061 SourceLocation ColonLoc, Stmt *SubStmt);
11062
11063 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11064 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11065 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11066 Stmt *SubStmt);
11067
11068 /// Check whether the given statement can have musttail applied to it,
11069 /// issuing a diagnostic and returning false if not. In the success case,
11070 /// the statement is rewritten to remove implicit nodes from the return
11071 /// value.
11072 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11073
11074 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11075 SourceLocation LParenLoc, Stmt *InitStmt,
11076 ConditionResult Cond, SourceLocation RParenLoc,
11077 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11078 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11079 SourceLocation LParenLoc, Stmt *InitStmt,
11080 ConditionResult Cond, SourceLocation RParenLoc,
11081 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11082
11083 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11084
11085 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11086 SourceLocation LParenLoc, Stmt *InitStmt,
11087 ConditionResult Cond,
11088 SourceLocation RParenLoc);
11089 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11090 Stmt *Body);
11091
11092 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11093 /// integer not in the range of enum values.
11094 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11095 Expr *SrcExpr);
11096
11097 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11098 ConditionResult Cond, SourceLocation RParenLoc,
11099 Stmt *Body);
11100 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11101 SourceLocation WhileLoc, SourceLocation CondLParen,
11102 Expr *Cond, SourceLocation CondRParen);
11103
11104 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11105 Stmt *First, ConditionResult Second,
11106 FullExprArg Third, SourceLocation RParenLoc,
11107 Stmt *Body);
11108
11109 /// In an Objective C collection iteration statement:
11110 /// for (x in y)
11111 /// x can be an arbitrary l-value expression. Bind it up as a
11112 /// full-expression.
11113 StmtResult ActOnForEachLValueExpr(Expr *E);
11114
11115 enum BuildForRangeKind {
11116 /// Initial building of a for-range statement.
11117 BFRK_Build,
11118 /// Instantiation or recovery rebuild of a for-range statement. Don't
11119 /// attempt any typo-correction.
11120 BFRK_Rebuild,
11121 /// Determining whether a for-range statement could be built. Avoid any
11122 /// unnecessary or irreversible actions.
11123 BFRK_Check
11124 };
11125
11126 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11127 ///
11128 /// C++11 [stmt.ranged]:
11129 /// A range-based for statement is equivalent to
11130 ///
11131 /// {
11132 /// auto && __range = range-init;
11133 /// for ( auto __begin = begin-expr,
11134 /// __end = end-expr;
11135 /// __begin != __end;
11136 /// ++__begin ) {
11137 /// for-range-declaration = *__begin;
11138 /// statement
11139 /// }
11140 /// }
11141 ///
11142 /// The body of the loop is not available yet, since it cannot be analysed
11143 /// until we have determined the type of the for-range-declaration.
11144 StmtResult ActOnCXXForRangeStmt(
11145 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11146 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11147 SourceLocation RParenLoc, BuildForRangeKind Kind,
11148 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11149
11150 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11151 StmtResult BuildCXXForRangeStmt(
11152 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11153 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11154 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11155 BuildForRangeKind Kind,
11156 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11157
11158 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11159 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11160 /// body cannot be performed until after the type of the range variable is
11161 /// determined.
11162 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11163
11164 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11165 LabelDecl *TheDecl);
11166 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11167 SourceLocation StarLoc, Expr *DestExp);
11168 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11169 LabelDecl *Label, SourceLocation LabelLoc);
11170 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11171 LabelDecl *Label, SourceLocation LabelLoc);
11172
11173 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11174 void ActOnDeferStmtError(Scope *CurScope);
11175 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11176
11177 struct NamedReturnInfo {
11178 const VarDecl *Candidate;
11179
11180 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11181 Status S;
11182
11183 bool isMoveEligible() const { return S != None; };
11184 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11185 };
11186 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11187
11188 /// Determine whether the given expression might be move-eligible or
11189 /// copy-elidable in either a (co_)return statement or throw expression,
11190 /// without considering function return type, if applicable.
11191 ///
11192 /// \param E The expression being returned from the function or block,
11193 /// being thrown, or being co_returned from a coroutine. This expression
11194 /// might be modified by the implementation.
11195 ///
11196 /// \param Mode Overrides detection of current language mode
11197 /// and uses the rules for C++23.
11198 ///
11199 /// \returns An aggregate which contains the Candidate and isMoveEligible
11200 /// and isCopyElidable methods. If Candidate is non-null, it means
11201 /// isMoveEligible() would be true under the most permissive language
11202 /// standard.
11203 NamedReturnInfo getNamedReturnInfo(
11204 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11205
11206 /// Determine whether the given NRVO candidate variable is move-eligible or
11207 /// copy-elidable, without considering function return type.
11208 ///
11209 /// \param VD The NRVO candidate variable.
11210 ///
11211 /// \returns An aggregate which contains the Candidate and isMoveEligible
11212 /// and isCopyElidable methods. If Candidate is non-null, it means
11213 /// isMoveEligible() would be true under the most permissive language
11214 /// standard.
11215 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11216
11217 /// Updates given NamedReturnInfo's move-eligible and
11218 /// copy-elidable statuses, considering the function
11219 /// return type criteria as applicable to return statements.
11220 ///
11221 /// \param Info The NamedReturnInfo object to update.
11222 ///
11223 /// \param ReturnType This is the return type of the function.
11224 /// \returns The copy elision candidate, in case the initial return expression
11225 /// was copy elidable, or nullptr otherwise.
11226 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11227 QualType ReturnType);
11228
11229 /// Perform the initialization of a potentially-movable value, which
11230 /// is the result of return value.
11231 ///
11232 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11233 /// treat returned lvalues as rvalues in certain cases (to prefer move
11234 /// construction), then falls back to treating them as lvalues if that failed.
11235 ExprResult
11236 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11237 const NamedReturnInfo &NRInfo, Expr *Value,
11238 bool SupressSimplerImplicitMoves = false);
11239
11240 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11241
11242 /// Deduce the return type for a function from a returned expression, per
11243 /// C++1y [dcl.spec.auto]p6.
11244 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11245 SourceLocation ReturnLoc, Expr *RetExpr,
11246 const AutoType *AT);
11247
11248 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11249 Scope *CurScope);
11250 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11251 bool AllowRecovery = false);
11252
11253 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11254 /// for capturing scopes.
11255 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11256 NamedReturnInfo &NRInfo,
11257 bool SupressSimplerImplicitMoves);
11258
11259 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11260 /// and creates a proper catch handler from them.
11261 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11262 Stmt *HandlerBlock);
11263
11264 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11265 /// handlers and creates a try statement from them.
11266 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11267 ArrayRef<Stmt *> Handlers);
11268
11269 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11270
11271 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11272 SourceLocation TryLoc, Stmt *TryBlock,
11273 Stmt *Handler);
11274 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11275 Stmt *Block);
11276 void ActOnStartSEHFinallyBlock();
11277 void ActOnAbortSEHFinallyBlock();
11278 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11279 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11280
11281 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11282 bool IsIfExists,
11283 NestedNameSpecifierLoc QualifierLoc,
11284 DeclarationNameInfo NameInfo,
11285 Stmt *Nested);
11286 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11287 bool IsIfExists, CXXScopeSpec &SS,
11288 UnqualifiedId &Name, Stmt *Nested);
11289
11290 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11291 CapturedRegionKind Kind, unsigned NumParams);
11292 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11293 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11294 CapturedRegionKind Kind,
11295 ArrayRef<CapturedParamNameType> Params,
11296 unsigned OpenMPCaptureLevel = 0);
11297 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11298 void ActOnCapturedRegionError();
11299 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11300 SourceLocation Loc,
11301 unsigned NumParams);
11302
11303private:
11304 /// Check whether the given statement can have musttail applied to it,
11305 /// issuing a diagnostic and returning false if not.
11306 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11307
11308 /// Check if the given expression contains 'break' or 'continue'
11309 /// statement that produces control flow different from GCC.
11310 void CheckBreakContinueBinding(Expr *E);
11311
11312 ///@}
11313
11314 //
11315 //
11316 // -------------------------------------------------------------------------
11317 //
11318 //
11319
11320 /// \name `inline asm` Statement
11321 /// Implementations are in SemaStmtAsm.cpp
11322 ///@{
11323
11324public:
11325 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11326 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11327 bool IsVolatile, unsigned NumOutputs,
11328 unsigned NumInputs, IdentifierInfo **Names,
11329 MultiExprArg Constraints, MultiExprArg Exprs,
11330 Expr *AsmString, MultiExprArg Clobbers,
11331 unsigned NumLabels, SourceLocation RParenLoc);
11332
11333 void FillInlineAsmIdentifierInfo(Expr *Res,
11334 llvm::InlineAsmIdentifierInfo &Info);
11335 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11336 SourceLocation TemplateKWLoc,
11337 UnqualifiedId &Id,
11338 bool IsUnevaluatedContext);
11339 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11340 SourceLocation AsmLoc);
11341 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11342 SourceLocation AsmLoc);
11343 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11344 ArrayRef<Token> AsmToks, StringRef AsmString,
11345 unsigned NumOutputs, unsigned NumInputs,
11346 ArrayRef<StringRef> Constraints,
11347 ArrayRef<StringRef> Clobbers,
11348 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11349 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11350 SourceLocation Location, bool AlwaysCreate);
11351
11352 ///@}
11353
11354 //
11355 //
11356 // -------------------------------------------------------------------------
11357 //
11358 //
11359
11360 /// \name Statement Attribute Handling
11361 /// Implementations are in SemaStmtAttr.cpp
11362 ///@{
11363
11364public:
11365 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11366 const AttributeCommonInfo &A);
11367 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11368 const AttributeCommonInfo &A);
11369
11370 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11371 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11372
11373 /// Process the attributes before creating an attributed statement. Returns
11374 /// the semantic attributes that have been processed.
11375 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11376 SmallVectorImpl<const Attr *> &OutAttrs);
11377
11378 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11379 SourceRange Range);
11380 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11381 const IdentifierInfo *AttrName,
11382 SourceRange Range);
11383
11384 ///@}
11385
11386 //
11387 //
11388 // -------------------------------------------------------------------------
11389 //
11390 //
11391
11392 /// \name C++ Templates
11393 /// Implementations are in SemaTemplate.cpp
11394 ///@{
11395
11396public:
11397 // Saves the current floating-point pragma stack and clear it in this Sema.
11398 class FpPragmaStackSaveRAII {
11399 public:
11400 FpPragmaStackSaveRAII(Sema &S)
11401 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11402 S.FpPragmaStack.Stack.clear();
11403 }
11404 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11405 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11406 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11407
11408 private:
11409 Sema &S;
11410 PragmaStack<FPOptionsOverride> SavedStack;
11411 };
11412
11413 void resetFPOptions(FPOptions FPO) {
11414 CurFPFeatures = FPO;
11415 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11416 }
11417
11418 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11419 return llvm::ArrayRef(InventedParameterInfos.begin() +
11420 InventedParameterInfosStart,
11421 InventedParameterInfos.end());
11422 }
11423
11424 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11425 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11426 FunctionScopes.end());
11427 }
11428
11429 typedef llvm::MapVector<const FunctionDecl *,
11430 std::unique_ptr<LateParsedTemplate>>
11431 LateParsedTemplateMapT;
11432 LateParsedTemplateMapT LateParsedTemplateMap;
11433
11434 /// Determine the number of levels of enclosing template parameters. This is
11435 /// only usable while parsing. Note that this does not include dependent
11436 /// contexts in which no template parameters have yet been declared, such as
11437 /// in a terse function template or generic lambda before the first 'auto' is
11438 /// encountered.
11439 unsigned getTemplateDepth(Scope *S) const;
11440
11441 void FilterAcceptableTemplateNames(LookupResult &R,
11442 bool AllowFunctionTemplates = true,
11443 bool AllowDependent = true);
11444 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11445 bool AllowFunctionTemplates = true,
11446 bool AllowDependent = true,
11447 bool AllowNonTemplateFunctions = false);
11448 /// Try to interpret the lookup result D as a template-name.
11449 ///
11450 /// \param D A declaration found by name lookup.
11451 /// \param AllowFunctionTemplates Whether function templates should be
11452 /// considered valid results.
11453 /// \param AllowDependent Whether unresolved using declarations (that might
11454 /// name templates) should be considered valid results.
11455 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11456 bool AllowFunctionTemplates = true,
11457 bool AllowDependent = true);
11458
11459 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11460 /// Whether and why a template name is required in this lookup.
11461 class RequiredTemplateKind {
11462 public:
11463 /// Template name is required if TemplateKWLoc is valid.
11464 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11465 : TemplateKW(TemplateKWLoc) {}
11466 /// Template name is unconditionally required.
11467 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11468
11469 SourceLocation getTemplateKeywordLoc() const {
11470 return TemplateKW.value_or(u: SourceLocation());
11471 }
11472 bool hasTemplateKeyword() const {
11473 return getTemplateKeywordLoc().isValid();
11474 }
11475 bool isRequired() const { return TemplateKW != SourceLocation(); }
11476 explicit operator bool() const { return isRequired(); }
11477
11478 private:
11479 std::optional<SourceLocation> TemplateKW;
11480 };
11481
11482 enum class AssumedTemplateKind {
11483 /// This is not assumed to be a template name.
11484 None,
11485 /// This is assumed to be a template name because lookup found nothing.
11486 FoundNothing,
11487 /// This is assumed to be a template name because lookup found one or more
11488 /// functions (but no function templates).
11489 FoundFunctions,
11490 };
11491
11492 bool
11493 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11494 QualType ObjectType, bool EnteringContext,
11495 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11496 AssumedTemplateKind *ATK = nullptr,
11497 bool AllowTypoCorrection = true);
11498
11499 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11500 bool hasTemplateKeyword,
11501 const UnqualifiedId &Name,
11502 ParsedType ObjectType, bool EnteringContext,
11503 TemplateTy &Template,
11504 bool &MemberOfUnknownSpecialization,
11505 bool Disambiguation = false);
11506
11507 /// Try to resolve an undeclared template name as a type template.
11508 ///
11509 /// Sets II to the identifier corresponding to the template name, and updates
11510 /// Name to a corresponding (typo-corrected) type template name and TNK to
11511 /// the corresponding kind, if possible.
11512 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11513 TemplateNameKind &TNK,
11514 SourceLocation NameLoc,
11515 IdentifierInfo *&II);
11516
11517 /// Determine whether a particular identifier might be the name in a C++1z
11518 /// deduction-guide declaration.
11519 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11520 SourceLocation NameLoc, CXXScopeSpec &SS,
11521 ParsedTemplateTy *Template = nullptr);
11522
11523 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11524 SourceLocation IILoc, Scope *S,
11525 const CXXScopeSpec *SS,
11526 TemplateTy &SuggestedTemplate,
11527 TemplateNameKind &SuggestedKind);
11528
11529 /// Determine whether we would be unable to instantiate this template (because
11530 /// it either has no definition, or is in the process of being instantiated).
11531 bool DiagnoseUninstantiableTemplate(
11532 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11533 bool InstantiatedFromMember, const NamedDecl *Pattern,
11534 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11535 bool Complain = true, bool *Unreachable = nullptr);
11536
11537 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11538 /// that the template parameter 'PrevDecl' is being shadowed by a new
11539 /// declaration at location Loc. Returns true to indicate that this is
11540 /// an error, and false otherwise.
11541 ///
11542 /// \param Loc The location of the declaration that shadows a template
11543 /// parameter.
11544 ///
11545 /// \param PrevDecl The template parameter that the declaration shadows.
11546 ///
11547 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11548 /// a warning for compatibility with older versions of clang.
11549 /// Ignored when MSVC compatibility is enabled.
11550 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11551 bool SupportedForCompatibility = false);
11552
11553 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11554 /// the parameter D to reference the templated declaration and return a
11555 /// pointer to the template declaration. Otherwise, do nothing to D and return
11556 /// null.
11557 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11558
11559 /// ActOnTypeParameter - Called when a C++ template type parameter
11560 /// (e.g., "typename T") has been parsed. Typename specifies whether
11561 /// the keyword "typename" was used to declare the type parameter
11562 /// (otherwise, "class" was used), and KeyLoc is the location of the
11563 /// "class" or "typename" keyword. ParamName is the name of the
11564 /// parameter (NULL indicates an unnamed template parameter) and
11565 /// ParamNameLoc is the location of the parameter name (if any).
11566 /// If the type parameter has a default argument, it will be added
11567 /// later via ActOnTypeParameterDefault.
11568 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11569 SourceLocation EllipsisLoc,
11570 SourceLocation KeyLoc,
11571 IdentifierInfo *ParamName,
11572 SourceLocation ParamNameLoc, unsigned Depth,
11573 unsigned Position, SourceLocation EqualLoc,
11574 ParsedType DefaultArg, bool HasTypeConstraint);
11575
11576 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11577
11578 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11579 TemplateIdAnnotation *TypeConstraint,
11580 TemplateTypeParmDecl *ConstrainedParameter,
11581 SourceLocation EllipsisLoc);
11582 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11583 TemplateIdAnnotation *TypeConstraint,
11584 TemplateTypeParmDecl *ConstrainedParameter,
11585 SourceLocation EllipsisLoc,
11586 bool AllowUnexpandedPack);
11587
11588 /// Attach a type-constraint to a template parameter.
11589 /// \returns true if an error occurred. This can happen if the
11590 /// immediately-declared constraint could not be formed (e.g. incorrect number
11591 /// of arguments for the named concept).
11592 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11593 DeclarationNameInfo NameInfo,
11594 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11595 const TemplateArgumentListInfo *TemplateArgs,
11596 TemplateTypeParmDecl *ConstrainedParameter,
11597 SourceLocation EllipsisLoc);
11598
11599 bool AttachTypeConstraint(AutoTypeLoc TL,
11600 NonTypeTemplateParmDecl *NewConstrainedParm,
11601 NonTypeTemplateParmDecl *OrigConstrainedParm,
11602 SourceLocation EllipsisLoc);
11603
11604 /// Require the given type to be a structural type, and diagnose if it is not.
11605 ///
11606 /// \return \c true if an error was produced.
11607 bool RequireStructuralType(QualType T, SourceLocation Loc);
11608
11609 /// Check that the type of a non-type template parameter is
11610 /// well-formed.
11611 ///
11612 /// \returns the (possibly-promoted) parameter type if valid;
11613 /// otherwise, produces a diagnostic and returns a NULL type.
11614 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11615 SourceLocation Loc);
11616 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11617
11618 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11619 unsigned Depth, unsigned Position,
11620 SourceLocation EqualLoc,
11621 Expr *DefaultArg);
11622
11623 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11624 /// parameter (e.g. T in template <template \<typename> class T> class array)
11625 /// has been parsed. S is the current scope.
11626 NamedDecl *ActOnTemplateTemplateParameter(
11627 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11628 bool TypenameKeyword, TemplateParameterList *Params,
11629 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11630 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11631 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11632
11633 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11634 /// constrained by RequiresClause, that contains the template parameters in
11635 /// Params.
11636 TemplateParameterList *ActOnTemplateParameterList(
11637 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11638 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11639 SourceLocation RAngleLoc, Expr *RequiresClause);
11640
11641 /// The context in which we are checking a template parameter list.
11642 enum TemplateParamListContext {
11643 // For this context, Class, Variable, TypeAlias, and non-pack Template
11644 // Template Parameters are treated uniformly.
11645 TPC_Other,
11646
11647 TPC_FunctionTemplate,
11648 TPC_ClassTemplateMember,
11649 TPC_FriendClassTemplate,
11650 TPC_FriendFunctionTemplate,
11651 TPC_FriendFunctionTemplateDefinition,
11652 TPC_TemplateTemplateParameterPack,
11653 };
11654
11655 /// Checks the validity of a template parameter list, possibly
11656 /// considering the template parameter list from a previous
11657 /// declaration.
11658 ///
11659 /// If an "old" template parameter list is provided, it must be
11660 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11661 /// template parameter list.
11662 ///
11663 /// \param NewParams Template parameter list for a new template
11664 /// declaration. This template parameter list will be updated with any
11665 /// default arguments that are carried through from the previous
11666 /// template parameter list.
11667 ///
11668 /// \param OldParams If provided, template parameter list from a
11669 /// previous declaration of the same template. Default template
11670 /// arguments will be merged from the old template parameter list to
11671 /// the new template parameter list.
11672 ///
11673 /// \param TPC Describes the context in which we are checking the given
11674 /// template parameter list.
11675 ///
11676 /// \param SkipBody If we might have already made a prior merged definition
11677 /// of this template visible, the corresponding body-skipping information.
11678 /// Default argument redefinition is not an error when skipping such a body,
11679 /// because (under the ODR) we can assume the default arguments are the same
11680 /// as the prior merged definition.
11681 ///
11682 /// \returns true if an error occurred, false otherwise.
11683 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11684 TemplateParameterList *OldParams,
11685 TemplateParamListContext TPC,
11686 SkipBodyInfo *SkipBody = nullptr);
11687
11688 /// Match the given template parameter lists to the given scope
11689 /// specifier, returning the template parameter list that applies to the
11690 /// name.
11691 ///
11692 /// \param DeclStartLoc the start of the declaration that has a scope
11693 /// specifier or a template parameter list.
11694 ///
11695 /// \param DeclLoc The location of the declaration itself.
11696 ///
11697 /// \param SS the scope specifier that will be matched to the given template
11698 /// parameter lists. This scope specifier precedes a qualified name that is
11699 /// being declared.
11700 ///
11701 /// \param TemplateId The template-id following the scope specifier, if there
11702 /// is one. Used to check for a missing 'template<>'.
11703 ///
11704 /// \param ParamLists the template parameter lists, from the outermost to the
11705 /// innermost template parameter lists.
11706 ///
11707 /// \param IsFriend Whether to apply the slightly different rules for
11708 /// matching template parameters to scope specifiers in friend
11709 /// declarations.
11710 ///
11711 /// \param IsMemberSpecialization will be set true if the scope specifier
11712 /// denotes a fully-specialized type, and therefore this is a declaration of
11713 /// a member specialization.
11714 ///
11715 /// \returns the template parameter list, if any, that corresponds to the
11716 /// name that is preceded by the scope specifier @p SS. This template
11717 /// parameter list may have template parameters (if we're declaring a
11718 /// template) or may have no template parameters (if we're declaring a
11719 /// template specialization), or may be NULL (if what we're declaring isn't
11720 /// itself a template).
11721 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11722 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11723 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11724 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11725 bool &IsMemberSpecialization, bool &Invalid,
11726 bool SuppressDiagnostic = false);
11727
11728 /// Returns the template parameter list with all default template argument
11729 /// information.
11730 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11731
11732 DeclResult CheckClassTemplate(
11733 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11734 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11735 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11736 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11737 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11738 TemplateParameterList **OuterTemplateParamLists,
11739 SkipBodyInfo *SkipBody = nullptr);
11740
11741 /// Translates template arguments as provided by the parser
11742 /// into template arguments used by semantic analysis.
11743 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11744 TemplateArgumentListInfo &Out);
11745
11746 /// Convert a parsed type into a parsed template argument. This is mostly
11747 /// trivial, except that we may have parsed a C++17 deduced class template
11748 /// specialization type, in which case we should form a template template
11749 /// argument instead of a type template argument.
11750 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11751
11752 void NoteAllFoundTemplates(TemplateName Name);
11753
11754 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11755 TemplateName Template,
11756 SourceLocation TemplateLoc,
11757 TemplateArgumentListInfo &TemplateArgs,
11758 Scope *Scope, bool ForNestedNameSpecifier);
11759
11760 TypeResult
11761 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11762 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11763 SourceLocation TemplateKWLoc, TemplateTy Template,
11764 const IdentifierInfo *TemplateII,
11765 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11766 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11767 bool IsCtorOrDtorName = false, bool IsClassName = false,
11768 ImplicitTypenameContext AllowImplicitTypename =
11769 ImplicitTypenameContext::No);
11770
11771 /// Parsed an elaborated-type-specifier that refers to a template-id,
11772 /// such as \c class T::template apply<U>.
11773 TypeResult ActOnTagTemplateIdType(
11774 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11775 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11776 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11777 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11778
11779 DeclResult ActOnVarTemplateSpecialization(
11780 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11781 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11782 StorageClass SC, bool IsPartialSpecialization);
11783
11784 /// Get the specialization of the given variable template corresponding to
11785 /// the specified argument list, or a null-but-valid result if the arguments
11786 /// are dependent.
11787 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11788 SourceLocation TemplateLoc,
11789 SourceLocation TemplateNameLoc,
11790 const TemplateArgumentListInfo &TemplateArgs,
11791 bool SetWrittenArgs);
11792
11793 /// Form a reference to the specialization of the given variable template
11794 /// corresponding to the specified argument list, or a null-but-valid result
11795 /// if the arguments are dependent.
11796 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11797 const DeclarationNameInfo &NameInfo,
11798 VarTemplateDecl *Template, NamedDecl *FoundD,
11799 SourceLocation TemplateLoc,
11800 const TemplateArgumentListInfo *TemplateArgs);
11801
11802 ExprResult CheckVarOrConceptTemplateTemplateId(
11803 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
11804 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
11805 const TemplateArgumentListInfo *TemplateArgs);
11806
11807 ExprResult
11808 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11809 const DeclarationNameInfo &ConceptNameInfo,
11810 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11811 const TemplateArgumentListInfo *TemplateArgs,
11812 bool DoCheckConstraintSatisfaction = true);
11813
11814 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11815 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11816 bool TemplateKeyword, TemplateDecl *TD,
11817 SourceLocation Loc);
11818
11819 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11820 SourceLocation TemplateKWLoc, LookupResult &R,
11821 bool RequiresADL,
11822 const TemplateArgumentListInfo *TemplateArgs);
11823
11824 // We actually only call this from template instantiation.
11825 ExprResult
11826 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11827 const DeclarationNameInfo &NameInfo,
11828 const TemplateArgumentListInfo *TemplateArgs,
11829 bool IsAddressOfOperand);
11830
11831 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11832 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11833 }
11834
11835 TemplateArgument
11836 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11837 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11838 if (Arg.isPackExpansion())
11839 Arg = Arg.getPackExpansionPattern();
11840 return Arg;
11841 }
11842
11843 ExprResult BuildSubstNonTypeTemplateParmExpr(
11844 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
11845 SourceLocation loc, TemplateArgument Replacement,
11846 UnsignedOrNone PackIndex, bool Final);
11847
11848 /// Form a template name from a name that is syntactically required to name a
11849 /// template, either due to use of the 'template' keyword or because a name in
11850 /// this syntactic context is assumed to name a template (C++
11851 /// [temp.names]p2-4).
11852 ///
11853 /// This action forms a template name given the name of the template and its
11854 /// optional scope specifier. This is used when the 'template' keyword is used
11855 /// or when the parsing context unambiguously treats a following '<' as
11856 /// introducing a template argument list. Note that this may produce a
11857 /// non-dependent template name if we can perform the lookup now and identify
11858 /// the named template.
11859 ///
11860 /// For example, given "x.MetaFun::template apply", the scope specifier
11861 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11862 /// of the "template" keyword, and "apply" is the \p Name.
11863 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11864 SourceLocation TemplateKWLoc,
11865 const UnqualifiedId &Name,
11866 ParsedType ObjectType,
11867 bool EnteringContext, TemplateTy &Template,
11868 bool AllowInjectedClassName = false);
11869
11870 DeclResult ActOnClassTemplateSpecialization(
11871 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11872 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11873 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11874 MultiTemplateParamsArg TemplateParameterLists,
11875 SkipBodyInfo *SkipBody = nullptr);
11876
11877 /// Check the non-type template arguments of a class template
11878 /// partial specialization according to C++ [temp.class.spec]p9.
11879 ///
11880 /// \param TemplateNameLoc the location of the template name.
11881 /// \param PrimaryTemplate the template parameters of the primary class
11882 /// template.
11883 /// \param NumExplicit the number of explicitly-specified template arguments.
11884 /// \param TemplateArgs the template arguments of the class template
11885 /// partial specialization.
11886 ///
11887 /// \returns \c true if there was an error, \c false otherwise.
11888 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11889 TemplateDecl *PrimaryTemplate,
11890 unsigned NumExplicitArgs,
11891 ArrayRef<TemplateArgument> Args);
11892 void CheckTemplatePartialSpecialization(
11893 ClassTemplatePartialSpecializationDecl *Partial);
11894 void CheckTemplatePartialSpecialization(
11895 VarTemplatePartialSpecializationDecl *Partial);
11896
11897 Decl *ActOnTemplateDeclarator(Scope *S,
11898 MultiTemplateParamsArg TemplateParameterLists,
11899 Declarator &D);
11900
11901 /// Diagnose cases where we have an explicit template specialization
11902 /// before/after an explicit template instantiation, producing diagnostics
11903 /// for those cases where they are required and determining whether the
11904 /// new specialization/instantiation will have any effect.
11905 ///
11906 /// \param NewLoc the location of the new explicit specialization or
11907 /// instantiation.
11908 ///
11909 /// \param NewTSK the kind of the new explicit specialization or
11910 /// instantiation.
11911 ///
11912 /// \param PrevDecl the previous declaration of the entity.
11913 ///
11914 /// \param PrevTSK the kind of the old explicit specialization or
11915 /// instantiatin.
11916 ///
11917 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11918 /// declaration was instantiated (either implicitly or explicitly).
11919 ///
11920 /// \param HasNoEffect will be set to true to indicate that the new
11921 /// specialization or instantiation has no effect and should be ignored.
11922 ///
11923 /// \returns true if there was an error that should prevent the introduction
11924 /// of the new declaration into the AST, false otherwise.
11925 bool CheckSpecializationInstantiationRedecl(
11926 SourceLocation NewLoc,
11927 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11928 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11929 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11930
11931 /// Perform semantic analysis for the given dependent function
11932 /// template specialization.
11933 ///
11934 /// The only possible way to get a dependent function template specialization
11935 /// is with a friend declaration, like so:
11936 ///
11937 /// \code
11938 /// template \<class T> void foo(T);
11939 /// template \<class T> class A {
11940 /// friend void foo<>(T);
11941 /// };
11942 /// \endcode
11943 ///
11944 /// There really isn't any useful analysis we can do here, so we
11945 /// just store the information.
11946 bool CheckDependentFunctionTemplateSpecialization(
11947 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11948 LookupResult &Previous);
11949
11950 /// Perform semantic analysis for the given function template
11951 /// specialization.
11952 ///
11953 /// This routine performs all of the semantic analysis required for an
11954 /// explicit function template specialization. On successful completion,
11955 /// the function declaration \p FD will become a function template
11956 /// specialization.
11957 ///
11958 /// \param FD the function declaration, which will be updated to become a
11959 /// function template specialization.
11960 ///
11961 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11962 /// if any. Note that this may be valid info even when 0 arguments are
11963 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11964 /// as it anyway contains info on the angle brackets locations.
11965 ///
11966 /// \param Previous the set of declarations that may be specialized by
11967 /// this function specialization.
11968 ///
11969 /// \param QualifiedFriend whether this is a lookup for a qualified friend
11970 /// declaration with no explicit template argument list that might be
11971 /// befriending a function template specialization.
11972 bool CheckFunctionTemplateSpecialization(
11973 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
11974 LookupResult &Previous, bool QualifiedFriend = false);
11975
11976 /// Perform semantic analysis for the given non-template member
11977 /// specialization.
11978 ///
11979 /// This routine performs all of the semantic analysis required for an
11980 /// explicit member function specialization. On successful completion,
11981 /// the function declaration \p FD will become a member function
11982 /// specialization.
11983 ///
11984 /// \param Member the member declaration, which will be updated to become a
11985 /// specialization.
11986 ///
11987 /// \param Previous the set of declarations, one of which may be specialized
11988 /// by this function specialization; the set will be modified to contain the
11989 /// redeclared member.
11990 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
11991 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
11992
11993 // Explicit instantiation of a class template specialization
11994 DeclResult ActOnExplicitInstantiation(
11995 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
11996 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
11997 TemplateTy Template, SourceLocation TemplateNameLoc,
11998 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
11999 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12000
12001 // Explicit instantiation of a member class of a class template.
12002 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12003 SourceLocation TemplateLoc,
12004 unsigned TagSpec, SourceLocation KWLoc,
12005 CXXScopeSpec &SS, IdentifierInfo *Name,
12006 SourceLocation NameLoc,
12007 const ParsedAttributesView &Attr);
12008
12009 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12010 SourceLocation TemplateLoc,
12011 Declarator &D);
12012
12013 /// If the given template parameter has a default template
12014 /// argument, substitute into that default template argument and
12015 /// return the corresponding template argument.
12016 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12017 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12018 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12019 ArrayRef<TemplateArgument> SugaredConverted,
12020 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12021
12022 /// Returns the top most location responsible for the definition of \p N.
12023 /// If \p N is a a template specialization, this is the location
12024 /// of the top of the instantiation stack.
12025 /// Otherwise, the location of \p N is returned.
12026 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12027
12028 /// Specifies the context in which a particular template
12029 /// argument is being checked.
12030 enum CheckTemplateArgumentKind {
12031 /// The template argument was specified in the code or was
12032 /// instantiated with some deduced template arguments.
12033 CTAK_Specified,
12034
12035 /// The template argument was deduced via template argument
12036 /// deduction.
12037 CTAK_Deduced,
12038
12039 /// The template argument was deduced from an array bound
12040 /// via template argument deduction.
12041 CTAK_DeducedFromArrayBound
12042 };
12043
12044 struct CheckTemplateArgumentInfo {
12045 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12046 bool MatchingTTP = false)
12047 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12048 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12049 CheckTemplateArgumentInfo &
12050 operator=(const CheckTemplateArgumentInfo &) = delete;
12051
12052 /// The checked, converted argument will be added to the
12053 /// end of these vectors.
12054 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12055
12056 /// The check is being performed in the context of partial ordering.
12057 bool PartialOrdering;
12058
12059 /// If true, assume these template arguments are
12060 /// the injected template arguments for a template template parameter.
12061 /// This will relax the requirement that all its possible uses are valid:
12062 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12063 /// during instantiation.
12064 bool MatchingTTP;
12065
12066 /// Is set to true when, in the context of TTP matching, a pack parameter
12067 /// matches non-pack arguments.
12068 bool StrictPackMatch = false;
12069 };
12070
12071 /// Check that the given template argument corresponds to the given
12072 /// template parameter.
12073 ///
12074 /// \param Param The template parameter against which the argument will be
12075 /// checked.
12076 ///
12077 /// \param Arg The template argument, which may be updated due to conversions.
12078 ///
12079 /// \param Template The template in which the template argument resides.
12080 ///
12081 /// \param TemplateLoc The location of the template name for the template
12082 /// whose argument list we're matching.
12083 ///
12084 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12085 /// the template argument list.
12086 ///
12087 /// \param ArgumentPackIndex The index into the argument pack where this
12088 /// argument will be placed. Only valid if the parameter is a parameter pack.
12089 ///
12090 /// \param CTAK Describes how we arrived at this particular template argument:
12091 /// explicitly written, deduced, etc.
12092 ///
12093 /// \returns true on error, false otherwise.
12094 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12095 NamedDecl *Template, SourceLocation TemplateLoc,
12096 SourceLocation RAngleLoc,
12097 unsigned ArgumentPackIndex,
12098 CheckTemplateArgumentInfo &CTAI,
12099 CheckTemplateArgumentKind CTAK);
12100
12101 /// Check that the given template arguments can be provided to
12102 /// the given template, converting the arguments along the way.
12103 ///
12104 /// \param Template The template to which the template arguments are being
12105 /// provided.
12106 ///
12107 /// \param TemplateLoc The location of the template name in the source.
12108 ///
12109 /// \param TemplateArgs The list of template arguments. If the template is
12110 /// a template template parameter, this function may extend the set of
12111 /// template arguments to also include substituted, defaulted template
12112 /// arguments.
12113 ///
12114 /// \param PartialTemplateArgs True if the list of template arguments is
12115 /// intentionally partial, e.g., because we're checking just the initial
12116 /// set of template arguments.
12117 ///
12118 /// \param Converted Will receive the converted, canonicalized template
12119 /// arguments.
12120 ///
12121 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12122 /// contain the converted forms of the template arguments as written.
12123 /// Otherwise, \p TemplateArgs will not be modified.
12124 ///
12125 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12126 /// receive true if the cause for the error is the associated constraints of
12127 /// the template not being satisfied by the template arguments.
12128 ///
12129 /// \param DefaultArgs any default arguments from template specialization
12130 /// deduction.
12131 ///
12132 /// \returns true if an error occurred, false otherwise.
12133 bool CheckTemplateArgumentList(TemplateDecl *Template,
12134 SourceLocation TemplateLoc,
12135 TemplateArgumentListInfo &TemplateArgs,
12136 const DefaultArguments &DefaultArgs,
12137 bool PartialTemplateArgs,
12138 CheckTemplateArgumentInfo &CTAI,
12139 bool UpdateArgsWithConversions = true,
12140 bool *ConstraintsNotSatisfied = nullptr);
12141
12142 bool CheckTemplateArgumentList(
12143 TemplateDecl *Template, TemplateParameterList *Params,
12144 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12145 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12146 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12147 bool *ConstraintsNotSatisfied = nullptr);
12148
12149 bool CheckTemplateTypeArgument(
12150 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12151 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12152 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12153
12154 /// Check a template argument against its corresponding
12155 /// template type parameter.
12156 ///
12157 /// This routine implements the semantics of C++ [temp.arg.type]. It
12158 /// returns true if an error occurred, and false otherwise.
12159 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12160
12161 /// Check a template argument against its corresponding
12162 /// non-type template parameter.
12163 ///
12164 /// This routine implements the semantics of C++ [temp.arg.nontype].
12165 /// If an error occurred, it returns ExprError(); otherwise, it
12166 /// returns the converted template argument. \p ParamType is the
12167 /// type of the non-type template parameter after it has been instantiated.
12168 ExprResult CheckTemplateArgument(NamedDecl *Param,
12169 QualType InstantiatedParamType, Expr *Arg,
12170 TemplateArgument &SugaredConverted,
12171 TemplateArgument &CanonicalConverted,
12172 bool StrictCheck,
12173 CheckTemplateArgumentKind CTAK);
12174
12175 /// Check a template argument against its corresponding
12176 /// template template parameter.
12177 ///
12178 /// This routine implements the semantics of C++ [temp.arg.template].
12179 /// It returns true if an error occurred, and false otherwise.
12180 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12181 TemplateParameterList *Params,
12182 TemplateArgumentLoc &Arg,
12183 bool PartialOrdering,
12184 bool *StrictPackMatch);
12185
12186 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12187 TemplateTemplateParmDecl *Param,
12188 const TemplateArgumentLoc &Arg);
12189
12190 void NoteTemplateLocation(const NamedDecl &Decl,
12191 std::optional<SourceRange> ParamRange = {});
12192 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12193
12194 /// Given a non-type template argument that refers to a
12195 /// declaration and the type of its corresponding non-type template
12196 /// parameter, produce an expression that properly refers to that
12197 /// declaration.
12198 /// FIXME: This is used in some contexts where the resulting expression
12199 /// doesn't need to live too long. It would be useful if this function
12200 /// could return a temporary expression.
12201 ExprResult BuildExpressionFromDeclTemplateArgument(
12202 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
12203 NamedDecl *TemplateParam = nullptr);
12204 ExprResult
12205 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12206 SourceLocation Loc);
12207
12208 /// Enumeration describing how template parameter lists are compared
12209 /// for equality.
12210 enum TemplateParameterListEqualKind {
12211 /// We are matching the template parameter lists of two templates
12212 /// that might be redeclarations.
12213 ///
12214 /// \code
12215 /// template<typename T> struct X;
12216 /// template<typename T> struct X;
12217 /// \endcode
12218 TPL_TemplateMatch,
12219
12220 /// We are matching the template parameter lists of two template
12221 /// template parameters as part of matching the template parameter lists
12222 /// of two templates that might be redeclarations.
12223 ///
12224 /// \code
12225 /// template<template<int I> class TT> struct X;
12226 /// template<template<int Value> class Other> struct X;
12227 /// \endcode
12228 TPL_TemplateTemplateParmMatch,
12229
12230 /// We are determining whether the template-parameters are equivalent
12231 /// according to C++ [temp.over.link]/6. This comparison does not consider
12232 /// constraints.
12233 ///
12234 /// \code
12235 /// template<C1 T> void f(T);
12236 /// template<C2 T> void f(T);
12237 /// \endcode
12238 TPL_TemplateParamsEquivalent,
12239 };
12240
12241 // A struct to represent the 'new' declaration, which is either itself just
12242 // the named decl, or the important information we need about it in order to
12243 // do constraint comparisons.
12244 class TemplateCompareNewDeclInfo {
12245 const NamedDecl *ND = nullptr;
12246 const DeclContext *DC = nullptr;
12247 const DeclContext *LexicalDC = nullptr;
12248 SourceLocation Loc;
12249
12250 public:
12251 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12252 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12253 const DeclContext *LexicalDeclCtx,
12254 SourceLocation Loc)
12255
12256 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12257 assert(DC && LexicalDC &&
12258 "Constructor only for cases where we have the information to put "
12259 "in here");
12260 }
12261
12262 // If this was constructed with no information, we cannot do substitution
12263 // for constraint comparison, so make sure we can check that.
12264 bool isInvalid() const { return !ND && !DC; }
12265
12266 const NamedDecl *getDecl() const { return ND; }
12267
12268 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12269
12270 const DeclContext *getLexicalDeclContext() const {
12271 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12272 }
12273
12274 const DeclContext *getDeclContext() const {
12275 return ND ? ND->getDeclContext() : DC;
12276 }
12277
12278 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12279 };
12280
12281 /// Determine whether the given template parameter lists are
12282 /// equivalent.
12283 ///
12284 /// \param New The new template parameter list, typically written in the
12285 /// source code as part of a new template declaration.
12286 ///
12287 /// \param Old The old template parameter list, typically found via
12288 /// name lookup of the template declared with this template parameter
12289 /// list.
12290 ///
12291 /// \param Complain If true, this routine will produce a diagnostic if
12292 /// the template parameter lists are not equivalent.
12293 ///
12294 /// \param Kind describes how we are to match the template parameter lists.
12295 ///
12296 /// \param TemplateArgLoc If this source location is valid, then we
12297 /// are actually checking the template parameter list of a template
12298 /// argument (New) against the template parameter list of its
12299 /// corresponding template template parameter (Old). We produce
12300 /// slightly different diagnostics in this scenario.
12301 ///
12302 /// \returns True if the template parameter lists are equal, false
12303 /// otherwise.
12304 bool TemplateParameterListsAreEqual(
12305 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12306 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12307 TemplateParameterListEqualKind Kind,
12308 SourceLocation TemplateArgLoc = SourceLocation());
12309
12310 bool TemplateParameterListsAreEqual(
12311 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12312 TemplateParameterListEqualKind Kind,
12313 SourceLocation TemplateArgLoc = SourceLocation()) {
12314 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12315 Kind, TemplateArgLoc);
12316 }
12317
12318 /// Check whether a template can be declared within this scope.
12319 ///
12320 /// If the template declaration is valid in this scope, returns
12321 /// false. Otherwise, issues a diagnostic and returns true.
12322 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12323
12324 /// Called when the parser has parsed a C++ typename
12325 /// specifier, e.g., "typename T::type".
12326 ///
12327 /// \param S The scope in which this typename type occurs.
12328 /// \param TypenameLoc the location of the 'typename' keyword
12329 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12330 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12331 /// \param IdLoc the location of the identifier.
12332 /// \param IsImplicitTypename context where T::type refers to a type.
12333 TypeResult ActOnTypenameType(
12334 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12335 const IdentifierInfo &II, SourceLocation IdLoc,
12336 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12337
12338 /// Called when the parser has parsed a C++ typename
12339 /// specifier that ends in a template-id, e.g.,
12340 /// "typename MetaFun::template apply<T1, T2>".
12341 ///
12342 /// \param S The scope in which this typename type occurs.
12343 /// \param TypenameLoc the location of the 'typename' keyword
12344 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12345 /// \param TemplateLoc the location of the 'template' keyword, if any.
12346 /// \param TemplateName The template name.
12347 /// \param TemplateII The identifier used to name the template.
12348 /// \param TemplateIILoc The location of the template name.
12349 /// \param LAngleLoc The location of the opening angle bracket ('<').
12350 /// \param TemplateArgs The template arguments.
12351 /// \param RAngleLoc The location of the closing angle bracket ('>').
12352 TypeResult
12353 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12354 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12355 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12356 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12357 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12358
12359 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12360 SourceLocation KeywordLoc,
12361 NestedNameSpecifierLoc QualifierLoc,
12362 const IdentifierInfo &II, SourceLocation IILoc,
12363 TypeSourceInfo **TSI, bool DeducedTSTContext);
12364
12365 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12366 SourceLocation KeywordLoc,
12367 NestedNameSpecifierLoc QualifierLoc,
12368 const IdentifierInfo &II, SourceLocation IILoc,
12369 bool DeducedTSTContext = true);
12370
12371 /// Rebuilds a type within the context of the current instantiation.
12372 ///
12373 /// The type \p T is part of the type of an out-of-line member definition of
12374 /// a class template (or class template partial specialization) that was
12375 /// parsed and constructed before we entered the scope of the class template
12376 /// (or partial specialization thereof). This routine will rebuild that type
12377 /// now that we have entered the declarator's scope, which may produce
12378 /// different canonical types, e.g.,
12379 ///
12380 /// \code
12381 /// template<typename T>
12382 /// struct X {
12383 /// typedef T* pointer;
12384 /// pointer data();
12385 /// };
12386 ///
12387 /// template<typename T>
12388 /// typename X<T>::pointer X<T>::data() { ... }
12389 /// \endcode
12390 ///
12391 /// Here, the type "typename X<T>::pointer" will be created as a
12392 /// DependentNameType, since we do not know that we can look into X<T> when we
12393 /// parsed the type. This function will rebuild the type, performing the
12394 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12395 /// canonical type is the same as the canonical type of T*, allowing the
12396 /// return types of the out-of-line definition and the declaration to match.
12397 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12398 SourceLocation Loc,
12399 DeclarationName Name);
12400 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12401
12402 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12403
12404 /// Rebuild the template parameters now that we know we're in a current
12405 /// instantiation.
12406 bool
12407 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12408
12409 /// Produces a formatted string that describes the binding of
12410 /// template parameters to template arguments.
12411 std::string
12412 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12413 const TemplateArgumentList &Args);
12414
12415 std::string
12416 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12417 const TemplateArgument *Args,
12418 unsigned NumArgs);
12419
12420 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12421 SourceLocation Less,
12422 SourceLocation Greater);
12423
12424 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12425 /// was just parsed. This is only possible with an explicit scope
12426 /// specifier naming a dependent type.
12427 ExprResult ActOnDependentIdExpression(
12428 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12429 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12430 const TemplateArgumentListInfo *TemplateArgs);
12431
12432 ExprResult
12433 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12434 SourceLocation TemplateKWLoc,
12435 const DeclarationNameInfo &NameInfo,
12436 const TemplateArgumentListInfo *TemplateArgs);
12437
12438 // Calculates whether the expression Constraint depends on an enclosing
12439 // template, for the purposes of [temp.friend] p9.
12440 // TemplateDepth is the 'depth' of the friend function, which is used to
12441 // compare whether a declaration reference is referring to a containing
12442 // template, or just the current friend function. A 'lower' TemplateDepth in
12443 // the AST refers to a 'containing' template. As the constraint is
12444 // uninstantiated, this is relative to the 'top' of the TU.
12445 bool
12446 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12447 unsigned TemplateDepth,
12448 const Expr *Constraint);
12449
12450 /// Find the failed Boolean condition within a given Boolean
12451 /// constant expression, and describe it with a string.
12452 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12453
12454 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12455
12456 ConceptDecl *ActOnStartConceptDefinition(
12457 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12458 const IdentifierInfo *Name, SourceLocation NameLoc);
12459
12460 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12461 Expr *ConstraintExpr,
12462 const ParsedAttributesView &Attrs);
12463
12464 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12465 bool &AddToScope);
12466 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12467
12468 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12469 const CXXScopeSpec &SS,
12470 const IdentifierInfo *Name,
12471 SourceLocation TagLoc, SourceLocation NameLoc);
12472
12473 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12474 CachedTokens &Toks);
12475 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12476 bool IsInsideALocalClassWithinATemplateFunction();
12477
12478 /// We've found a use of a templated declaration that would trigger an
12479 /// implicit instantiation. Check that any relevant explicit specializations
12480 /// and partial specializations are visible/reachable, and diagnose if not.
12481 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12482 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12483
12484 ///@}
12485
12486 //
12487 //
12488 // -------------------------------------------------------------------------
12489 //
12490 //
12491
12492 /// \name C++ Template Argument Deduction
12493 /// Implementations are in SemaTemplateDeduction.cpp
12494 ///@{
12495
12496public:
12497 class SFINAETrap;
12498
12499 struct SFINAEContextBase {
12500 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12501 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12502
12503 protected:
12504 Sema &S;
12505 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12506 SFINAEContextBase(const SFINAEContextBase &) = delete;
12507 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12508
12509 private:
12510 SFINAETrap *Prev;
12511 };
12512
12513 struct NonSFINAEContext : SFINAEContextBase {
12514 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12515 };
12516
12517 /// RAII class used to determine whether SFINAE has
12518 /// trapped any errors that occur during template argument
12519 /// deduction.
12520 class SFINAETrap : SFINAEContextBase {
12521 bool HasErrorOcurred = false;
12522 bool WithAccessChecking = false;
12523 bool PrevLastDiagnosticIgnored =
12524 S.getDiagnostics().isLastDiagnosticIgnored();
12525 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12526
12527 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12528 bool WithAccessChecking)
12529 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12530 DeductionInfo(Info) {}
12531
12532 public:
12533 /// \param WithAccessChecking If true, discard all diagnostics (from the
12534 /// immediate context) instead of adding them to the currently active
12535 /// \ref TemplateDeductionInfo.
12536 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12537 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12538
12539 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12540 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12541
12542 ~SFINAETrap() {
12543 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12544 }
12545
12546 SFINAETrap(const SFINAETrap &) = delete;
12547 SFINAETrap &operator=(const SFINAETrap &) = delete;
12548
12549 sema::TemplateDeductionInfo *getDeductionInfo() const {
12550 return DeductionInfo;
12551 }
12552
12553 /// Determine whether any SFINAE errors have been trapped.
12554 bool hasErrorOccurred() const { return HasErrorOcurred; }
12555 void setErrorOccurred() { HasErrorOcurred = true; }
12556
12557 bool withAccessChecking() const { return WithAccessChecking; }
12558 };
12559
12560 /// RAII class used to indicate that we are performing provisional
12561 /// semantic analysis to determine the validity of a construct, so
12562 /// typo-correction and diagnostics in the immediate context (not within
12563 /// implicitly-instantiated templates) should be suppressed.
12564 class TentativeAnalysisScope {
12565 Sema &SemaRef;
12566 // FIXME: Using a SFINAETrap for this is a hack.
12567 SFINAETrap Trap;
12568 bool PrevDisableTypoCorrection;
12569
12570 public:
12571 explicit TentativeAnalysisScope(Sema &SemaRef)
12572 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12573 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12574 SemaRef.DisableTypoCorrection = true;
12575 }
12576 ~TentativeAnalysisScope() {
12577 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12578 }
12579
12580 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12581 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12582 };
12583
12584 /// For each declaration that involved template argument deduction, the
12585 /// set of diagnostics that were suppressed during that template argument
12586 /// deduction.
12587 ///
12588 /// FIXME: Serialize this structure to the AST file.
12589 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12590 SuppressedDiagnosticsMap;
12591 SuppressedDiagnosticsMap SuppressedDiagnostics;
12592
12593 /// Compare types for equality with respect to possibly compatible
12594 /// function types (noreturn adjustment, implicit calling conventions). If any
12595 /// of parameter and argument is not a function, just perform type comparison.
12596 ///
12597 /// \param P the template parameter type.
12598 ///
12599 /// \param A the argument type.
12600 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12601
12602 /// Allocate a TemplateArgumentLoc where all locations have
12603 /// been initialized to the given location.
12604 ///
12605 /// \param Arg The template argument we are producing template argument
12606 /// location information for.
12607 ///
12608 /// \param NTTPType For a declaration template argument, the type of
12609 /// the non-type template parameter that corresponds to this template
12610 /// argument. Can be null if no type sugar is available to add to the
12611 /// type from the template argument.
12612 ///
12613 /// \param Loc The source location to use for the resulting template
12614 /// argument.
12615 TemplateArgumentLoc
12616 getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType,
12617 SourceLocation Loc,
12618 NamedDecl *TemplateParam = nullptr);
12619
12620 /// Get a template argument mapping the given template parameter to itself,
12621 /// e.g. for X in \c template<int X>, this would return an expression template
12622 /// argument referencing X.
12623 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12624 SourceLocation Location);
12625
12626 /// Adjust the type \p ArgFunctionType to match the calling convention,
12627 /// noreturn, and optionally the exception specification of \p FunctionType.
12628 /// Deduction often wants to ignore these properties when matching function
12629 /// types.
12630 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12631 bool AdjustExceptionSpec = false);
12632
12633 TemplateDeductionResult
12634 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12635 ArrayRef<TemplateArgument> TemplateArgs,
12636 sema::TemplateDeductionInfo &Info);
12637
12638 TemplateDeductionResult
12639 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12640 ArrayRef<TemplateArgument> TemplateArgs,
12641 sema::TemplateDeductionInfo &Info);
12642
12643 /// Deduce the template arguments of the given template from \p FromType.
12644 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12645 /// [over.match.class.deduct]p4.
12646 ///
12647 /// It only supports class or type alias templates.
12648 TemplateDeductionResult
12649 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12650 sema::TemplateDeductionInfo &Info);
12651
12652 TemplateDeductionResult DeduceTemplateArguments(
12653 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12654 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12655 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12656 bool NumberOfArgumentsMustMatch);
12657
12658 /// Substitute the explicitly-provided template arguments into the
12659 /// given function template according to C++ [temp.arg.explicit].
12660 ///
12661 /// \param FunctionTemplate the function template into which the explicit
12662 /// template arguments will be substituted.
12663 ///
12664 /// \param ExplicitTemplateArgs the explicitly-specified template
12665 /// arguments.
12666 ///
12667 /// \param Deduced the deduced template arguments, which will be populated
12668 /// with the converted and checked explicit template arguments.
12669 ///
12670 /// \param ParamTypes will be populated with the instantiated function
12671 /// parameters.
12672 ///
12673 /// \param FunctionType if non-NULL, the result type of the function template
12674 /// will also be instantiated and the pointed-to value will be updated with
12675 /// the instantiated function type.
12676 ///
12677 /// \param Info if substitution fails for any reason, this object will be
12678 /// populated with more information about the failure.
12679 ///
12680 /// \returns TemplateDeductionResult::Success if substitution was successful,
12681 /// or some failure condition.
12682 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12683 FunctionTemplateDecl *FunctionTemplate,
12684 TemplateArgumentListInfo &ExplicitTemplateArgs,
12685 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12686 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12687 sema::TemplateDeductionInfo &Info);
12688
12689 /// brief A function argument from which we performed template argument
12690 // deduction for a call.
12691 struct OriginalCallArg {
12692 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12693 unsigned ArgIdx, QualType OriginalArgType)
12694 : OriginalParamType(OriginalParamType),
12695 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12696 OriginalArgType(OriginalArgType) {}
12697
12698 QualType OriginalParamType;
12699 bool DecomposedParam;
12700 unsigned ArgIdx;
12701 QualType OriginalArgType;
12702 };
12703
12704 /// Finish template argument deduction for a function template,
12705 /// checking the deduced template arguments for completeness and forming
12706 /// the function template specialization.
12707 ///
12708 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12709 /// which the deduced argument types should be compared.
12710 /// \param CheckNonDependent Callback before substituting into the declaration
12711 /// with the deduced template arguments.
12712 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12713 /// some breakages introduced by CWG2369, where non-user-defined conversions
12714 /// are checked first before the constraints.
12715 TemplateDeductionResult FinishTemplateArgumentDeduction(
12716 FunctionTemplateDecl *FunctionTemplate,
12717 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12718 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12719 sema::TemplateDeductionInfo &Info,
12720 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12721 bool PartialOverloading, bool PartialOrdering,
12722 bool ForOverloadSetAddressResolution,
12723 llvm::function_ref<bool(bool)> CheckNonDependent =
12724 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12725 return false;
12726 });
12727
12728 /// Perform template argument deduction from a function call
12729 /// (C++ [temp.deduct.call]).
12730 ///
12731 /// \param FunctionTemplate the function template for which we are performing
12732 /// template argument deduction.
12733 ///
12734 /// \param ExplicitTemplateArgs the explicit template arguments provided
12735 /// for this call.
12736 ///
12737 /// \param Args the function call arguments
12738 ///
12739 /// \param Specialization if template argument deduction was successful,
12740 /// this will be set to the function template specialization produced by
12741 /// template argument deduction.
12742 ///
12743 /// \param Info the argument will be updated to provide additional information
12744 /// about template argument deduction.
12745 ///
12746 /// \param CheckNonDependent A callback to invoke to check conversions for
12747 /// non-dependent parameters, between deduction and substitution, per DR1391.
12748 /// If this returns true, substitution will be skipped and we return
12749 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12750 /// passed the parameter types (after substituting explicit template
12751 /// arguments).
12752 ///
12753 /// \returns the result of template argument deduction.
12754 TemplateDeductionResult DeduceTemplateArguments(
12755 FunctionTemplateDecl *FunctionTemplate,
12756 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12757 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12758 bool PartialOverloading, bool AggregateDeductionCandidate,
12759 bool PartialOrdering, QualType ObjectType,
12760 Expr::Classification ObjectClassification,
12761 bool ForOverloadSetAddressResolution,
12762 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12763
12764 /// Deduce template arguments when taking the address of a function
12765 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12766 /// a template.
12767 ///
12768 /// \param FunctionTemplate the function template for which we are performing
12769 /// template argument deduction.
12770 ///
12771 /// \param ExplicitTemplateArgs the explicitly-specified template
12772 /// arguments.
12773 ///
12774 /// \param ArgFunctionType the function type that will be used as the
12775 /// "argument" type (A) when performing template argument deduction from the
12776 /// function template's function type. This type may be NULL, if there is no
12777 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12778 ///
12779 /// \param Specialization if template argument deduction was successful,
12780 /// this will be set to the function template specialization produced by
12781 /// template argument deduction.
12782 ///
12783 /// \param Info the argument will be updated to provide additional information
12784 /// about template argument deduction.
12785 ///
12786 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12787 /// the address of a function template per [temp.deduct.funcaddr] and
12788 /// [over.over]. If \c false, we are looking up a function template
12789 /// specialization based on its signature, per [temp.deduct.decl].
12790 ///
12791 /// \returns the result of template argument deduction.
12792 TemplateDeductionResult DeduceTemplateArguments(
12793 FunctionTemplateDecl *FunctionTemplate,
12794 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12795 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12796 bool IsAddressOfFunction = false);
12797
12798 /// Deduce template arguments for a templated conversion
12799 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12800 /// conversion function template specialization.
12801 TemplateDeductionResult DeduceTemplateArguments(
12802 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12803 Expr::Classification ObjectClassification, QualType ToType,
12804 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12805
12806 /// Deduce template arguments for a function template when there is
12807 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12808 ///
12809 /// \param FunctionTemplate the function template for which we are performing
12810 /// template argument deduction.
12811 ///
12812 /// \param ExplicitTemplateArgs the explicitly-specified template
12813 /// arguments.
12814 ///
12815 /// \param Specialization if template argument deduction was successful,
12816 /// this will be set to the function template specialization produced by
12817 /// template argument deduction.
12818 ///
12819 /// \param Info the argument will be updated to provide additional information
12820 /// about template argument deduction.
12821 ///
12822 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12823 /// the address of a function template in a context where we do not have a
12824 /// target type, per [over.over]. If \c false, we are looking up a function
12825 /// template specialization based on its signature, which only happens when
12826 /// deducing a function parameter type from an argument that is a template-id
12827 /// naming a function template specialization.
12828 ///
12829 /// \returns the result of template argument deduction.
12830 TemplateDeductionResult
12831 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12832 TemplateArgumentListInfo *ExplicitTemplateArgs,
12833 FunctionDecl *&Specialization,
12834 sema::TemplateDeductionInfo &Info,
12835 bool IsAddressOfFunction = false);
12836
12837 /// Substitute Replacement for \p auto in \p TypeWithAuto
12838 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12839 /// Substitute Replacement for auto in TypeWithAuto
12840 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12841 QualType Replacement);
12842
12843 // Substitute auto in TypeWithAuto for a Dependent auto type
12844 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12845
12846 // Substitute auto in TypeWithAuto for a Dependent auto type
12847 TypeSourceInfo *
12848 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12849
12850 /// Completely replace the \c auto in \p TypeWithAuto by
12851 /// \p Replacement. This does not retain any \c auto type sugar.
12852 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12853 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12854 QualType Replacement);
12855
12856 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12857 ///
12858 /// Note that this is done even if the initializer is dependent. (This is
12859 /// necessary to support partial ordering of templates using 'auto'.)
12860 /// A dependent type will be produced when deducing from a dependent type.
12861 ///
12862 /// \param Type the type pattern using the auto type-specifier.
12863 /// \param Init the initializer for the variable whose type is to be deduced.
12864 /// \param Result if type deduction was successful, this will be set to the
12865 /// deduced type.
12866 /// \param Info the argument will be updated to provide additional information
12867 /// about template argument deduction.
12868 /// \param DependentDeduction Set if we should permit deduction in
12869 /// dependent cases. This is necessary for template partial ordering
12870 /// with 'auto' template parameters. The template parameter depth to be
12871 /// used should be specified in the 'Info' parameter.
12872 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12873 /// does not satisfy the type-constraint in the auto
12874 /// type.
12875 TemplateDeductionResult
12876 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12877 sema::TemplateDeductionInfo &Info,
12878 bool DependentDeduction = false,
12879 bool IgnoreConstraints = false,
12880 TemplateSpecCandidateSet *FailedTSC = nullptr);
12881 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12882 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12883 bool Diagnose = true);
12884
12885 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
12886 SourceLocation Loc);
12887
12888 /// Returns the more specialized class template partial specialization
12889 /// according to the rules of partial ordering of class template partial
12890 /// specializations (C++ [temp.class.order]).
12891 ///
12892 /// \param PS1 the first class template partial specialization
12893 ///
12894 /// \param PS2 the second class template partial specialization
12895 ///
12896 /// \returns the more specialized class template partial specialization. If
12897 /// neither partial specialization is more specialized, returns NULL.
12898 ClassTemplatePartialSpecializationDecl *
12899 getMoreSpecializedPartialSpecialization(
12900 ClassTemplatePartialSpecializationDecl *PS1,
12901 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12902
12903 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
12904 sema::TemplateDeductionInfo &Info);
12905
12906 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
12907 VarTemplatePartialSpecializationDecl *PS1,
12908 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12909
12910 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
12911 sema::TemplateDeductionInfo &Info);
12912
12913 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
12914 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12915 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12916 bool PartialOrdering, bool *StrictPackMatch);
12917
12918 /// Mark which template parameters are used in a given expression.
12919 ///
12920 /// \param E the expression from which template parameters will be deduced.
12921 ///
12922 /// \param Used a bit vector whose elements will be set to \c true
12923 /// to indicate when the corresponding template parameter will be
12924 /// deduced.
12925 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12926 unsigned Depth, llvm::SmallBitVector &Used);
12927
12928 /// Mark which template parameters are named in a given expression.
12929 ///
12930 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12931 /// are used but not directly named by an expression - i.e. it excludes
12932 /// any template parameter that denotes the type of a referenced NTTP.
12933 ///
12934 /// \param Used a bit vector whose elements will be set to \c true
12935 /// to indicate when the corresponding template parameter will be
12936 /// deduced.
12937 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
12938 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
12939
12940 /// Mark which template parameters can be deduced from a given
12941 /// template argument list.
12942 ///
12943 /// \param TemplateArgs the template argument list from which template
12944 /// parameters will be deduced.
12945 ///
12946 /// \param Used a bit vector whose elements will be set to \c true
12947 /// to indicate when the corresponding template parameter will be
12948 /// deduced.
12949 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12950 bool OnlyDeduced, unsigned Depth,
12951 llvm::SmallBitVector &Used);
12952
12953 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
12954 unsigned Depth, llvm::SmallBitVector &Used);
12955
12956 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
12957 unsigned Depth, llvm::SmallBitVector &Used);
12958
12959 void
12960 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
12961 llvm::SmallBitVector &Deduced) {
12962 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
12963 }
12964
12965 /// Marks all of the template parameters that will be deduced by a
12966 /// call to the given function template.
12967 static void
12968 MarkDeducedTemplateParameters(ASTContext &Ctx,
12969 const FunctionTemplateDecl *FunctionTemplate,
12970 llvm::SmallBitVector &Deduced);
12971
12972 /// Returns the more specialized function template according
12973 /// to the rules of function template partial ordering (C++
12974 /// [temp.func.order]).
12975 ///
12976 /// \param FT1 the first function template
12977 ///
12978 /// \param FT2 the second function template
12979 ///
12980 /// \param TPOC the context in which we are performing partial ordering of
12981 /// function templates.
12982 ///
12983 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
12984 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
12985 /// when calling a member function.
12986 ///
12987 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
12988 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
12989 /// template from a member function
12990 ///
12991 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
12992 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
12993 /// template from a member function
12994 ///
12995 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
12996 /// candidate with a reversed parameter order. In this case, the corresponding
12997 /// P/A pairs between FT1 and FT2 are reversed.
12998 ///
12999 /// \returns the more specialized function template. If neither
13000 /// template is more specialized, returns NULL.
13001 FunctionTemplateDecl *getMoreSpecializedTemplate(
13002 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13003 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13004 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13005 bool PartialOverloading = false);
13006
13007 /// Retrieve the most specialized of the given function template
13008 /// specializations.
13009 ///
13010 /// \param SpecBegin the start iterator of the function template
13011 /// specializations that we will be comparing.
13012 ///
13013 /// \param SpecEnd the end iterator of the function template
13014 /// specializations, paired with \p SpecBegin.
13015 ///
13016 /// \param Loc the location where the ambiguity or no-specializations
13017 /// diagnostic should occur.
13018 ///
13019 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13020 /// no matching candidates.
13021 ///
13022 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13023 /// occurs.
13024 ///
13025 /// \param CandidateDiag partial diagnostic used for each function template
13026 /// specialization that is a candidate in the ambiguous ordering. One
13027 /// parameter in this diagnostic should be unbound, which will correspond to
13028 /// the string describing the template arguments for the function template
13029 /// specialization.
13030 ///
13031 /// \returns the most specialized function template specialization, if
13032 /// found. Otherwise, returns SpecEnd.
13033 UnresolvedSetIterator
13034 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13035 TemplateSpecCandidateSet &FailedCandidates,
13036 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13037 const PartialDiagnostic &AmbigDiag,
13038 const PartialDiagnostic &CandidateDiag,
13039 bool Complain = true, QualType TargetType = QualType());
13040
13041 /// Returns the more constrained function according to the rules of
13042 /// partial ordering by constraints (C++ [temp.constr.order]).
13043 ///
13044 /// \param FD1 the first function
13045 ///
13046 /// \param FD2 the second function
13047 ///
13048 /// \returns the more constrained function. If neither function is
13049 /// more constrained, returns NULL.
13050 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13051 FunctionDecl *FD2);
13052
13053 ///@}
13054
13055 //
13056 //
13057 // -------------------------------------------------------------------------
13058 //
13059 //
13060
13061 /// \name C++ Template Deduction Guide
13062 /// Implementations are in SemaTemplateDeductionGuide.cpp
13063 ///@{
13064
13065 /// Declare implicit deduction guides for a class template if we've
13066 /// not already done so.
13067 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13068 SourceLocation Loc);
13069
13070 FunctionTemplateDecl *DeclareAggregateDeductionGuideFromInitList(
13071 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13072 SourceLocation Loc);
13073
13074 ///@}
13075
13076 //
13077 //
13078 // -------------------------------------------------------------------------
13079 //
13080 //
13081
13082 /// \name C++ Template Instantiation
13083 /// Implementations are in SemaTemplateInstantiate.cpp
13084 ///@{
13085
13086public:
13087 /// A helper class for building up ExtParameterInfos.
13088 class ExtParameterInfoBuilder {
13089 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13090 bool HasInteresting = false;
13091
13092 public:
13093 /// Set the ExtParameterInfo for the parameter at the given index,
13094 ///
13095 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13096 assert(Infos.size() <= index);
13097 Infos.resize(N: index);
13098 Infos.push_back(Elt: info);
13099
13100 if (!HasInteresting)
13101 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13102 }
13103
13104 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13105 /// ExtParameterInfo array we've built up.
13106 const FunctionProtoType::ExtParameterInfo *
13107 getPointerOrNull(unsigned numParams) {
13108 if (!HasInteresting)
13109 return nullptr;
13110 Infos.resize(N: numParams);
13111 return Infos.data();
13112 }
13113 };
13114
13115 /// The current instantiation scope used to store local
13116 /// variables.
13117 LocalInstantiationScope *CurrentInstantiationScope;
13118
13119 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13120 UnparsedDefaultArgInstantiationsMap;
13121
13122 /// A mapping from parameters with unparsed default arguments to the
13123 /// set of instantiations of each parameter.
13124 ///
13125 /// This mapping is a temporary data structure used when parsing
13126 /// nested class templates or nested classes of class templates,
13127 /// where we might end up instantiating an inner class before the
13128 /// default arguments of its methods have been parsed.
13129 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13130
13131 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13132
13133 struct RecursiveInstGuard {
13134 enum class Kind {
13135 Template,
13136 DefaultArgument,
13137 ExceptionSpec,
13138 };
13139
13140 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13141 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13142 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13143 if (!Created)
13144 Key = {};
13145 }
13146
13147 ~RecursiveInstGuard() {
13148 if (Key.getOpaqueValue()) {
13149 [[maybe_unused]] bool Erased =
13150 S.InstantiatingSpecializations.erase(V: Key);
13151 assert(Erased);
13152 }
13153 }
13154
13155 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13156 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13157
13158 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13159
13160 private:
13161 Sema &S;
13162 Sema::InstantiatingSpecializationsKey Key;
13163 };
13164
13165 /// A context in which code is being synthesized (where a source location
13166 /// alone is not sufficient to identify the context). This covers template
13167 /// instantiation and various forms of implicitly-generated functions.
13168 struct CodeSynthesisContext {
13169 /// The kind of template instantiation we are performing
13170 enum SynthesisKind {
13171 /// We are instantiating a template declaration. The entity is
13172 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13173 TemplateInstantiation,
13174
13175 /// We are instantiating a default argument for a template
13176 /// parameter. The Entity is the template parameter whose argument is
13177 /// being instantiated, the Template is the template, and the
13178 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13179 /// specified.
13180 DefaultTemplateArgumentInstantiation,
13181
13182 /// We are instantiating a default argument for a function.
13183 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13184 /// provides the template arguments as specified.
13185 DefaultFunctionArgumentInstantiation,
13186
13187 /// We are substituting explicit template arguments provided for
13188 /// a function template. The entity is a FunctionTemplateDecl.
13189 ExplicitTemplateArgumentSubstitution,
13190
13191 /// We are substituting template argument determined as part of
13192 /// template argument deduction for either a class template
13193 /// partial specialization or a function template. The
13194 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13195 /// a TemplateDecl.
13196 DeducedTemplateArgumentSubstitution,
13197
13198 /// We are substituting into a lambda expression.
13199 LambdaExpressionSubstitution,
13200
13201 /// We are substituting prior template arguments into a new
13202 /// template parameter. The template parameter itself is either a
13203 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13204 PriorTemplateArgumentSubstitution,
13205
13206 /// We are checking the validity of a default template argument that
13207 /// has been used when naming a template-id.
13208 DefaultTemplateArgumentChecking,
13209
13210 /// We are computing the exception specification for a defaulted special
13211 /// member function.
13212 ExceptionSpecEvaluation,
13213
13214 /// We are instantiating the exception specification for a function
13215 /// template which was deferred until it was needed.
13216 ExceptionSpecInstantiation,
13217
13218 /// We are instantiating a requirement of a requires expression.
13219 RequirementInstantiation,
13220
13221 /// We are checking the satisfaction of a nested requirement of a requires
13222 /// expression.
13223 NestedRequirementConstraintsCheck,
13224
13225 /// We are declaring an implicit special member function.
13226 DeclaringSpecialMember,
13227
13228 /// We are declaring an implicit 'operator==' for a defaulted
13229 /// 'operator<=>'.
13230 DeclaringImplicitEqualityComparison,
13231
13232 /// We are defining a synthesized function (such as a defaulted special
13233 /// member).
13234 DefiningSynthesizedFunction,
13235
13236 // We are checking the constraints associated with a constrained entity or
13237 // the constraint expression of a concept. This includes the checks that
13238 // atomic constraints have the type 'bool' and that they can be constant
13239 // evaluated.
13240 ConstraintsCheck,
13241
13242 // We are substituting template arguments into a constraint expression.
13243 ConstraintSubstitution,
13244
13245 // We are normalizing a constraint expression.
13246 ConstraintNormalization,
13247
13248 // Instantiating a Requires Expression parameter clause.
13249 RequirementParameterInstantiation,
13250
13251 // We are substituting into the parameter mapping of an atomic constraint
13252 // during normalization.
13253 ParameterMappingSubstitution,
13254
13255 /// We are rewriting a comparison operator in terms of an operator<=>.
13256 RewritingOperatorAsSpaceship,
13257
13258 /// We are initializing a structured binding.
13259 InitializingStructuredBinding,
13260
13261 /// We are marking a class as __dllexport.
13262 MarkingClassDllexported,
13263
13264 /// We are building an implied call from __builtin_dump_struct. The
13265 /// arguments are in CallArgs.
13266 BuildingBuiltinDumpStructCall,
13267
13268 /// Added for Template instantiation observation.
13269 /// Memoization means we are _not_ instantiating a template because
13270 /// it is already instantiated (but we entered a context where we
13271 /// would have had to if it was not already instantiated).
13272 Memoization,
13273
13274 /// We are building deduction guides for a class.
13275 BuildingDeductionGuides,
13276
13277 /// We are instantiating a type alias template declaration.
13278 TypeAliasTemplateInstantiation,
13279
13280 /// We are performing partial ordering for template template parameters.
13281 PartialOrderingTTP,
13282
13283 /// We are performing name lookup for a function template or variable
13284 /// template named 'sycl_kernel_launch'.
13285 SYCLKernelLaunchLookup,
13286
13287 /// We are performing overload resolution for a call to a function
13288 /// template or variable template named 'sycl_kernel_launch'.
13289 SYCLKernelLaunchOverloadResolution,
13290 } Kind;
13291
13292 /// Whether we're substituting into constraints.
13293 bool InConstraintSubstitution;
13294
13295 /// Whether we're substituting into the parameter mapping of a constraint.
13296 bool InParameterMappingSubstitution;
13297
13298 /// The point of instantiation or synthesis within the source code.
13299 SourceLocation PointOfInstantiation;
13300
13301 /// The entity that is being synthesized.
13302 Decl *Entity;
13303
13304 /// The template (or partial specialization) in which we are
13305 /// performing the instantiation, for substitutions of prior template
13306 /// arguments.
13307 NamedDecl *Template;
13308
13309 union {
13310 /// The list of template arguments we are substituting, if they
13311 /// are not part of the entity.
13312 const TemplateArgument *TemplateArgs;
13313
13314 /// The list of argument expressions in a synthesized call.
13315 const Expr *const *CallArgs;
13316 };
13317
13318 // FIXME: Wrap this union around more members, or perhaps store the
13319 // kind-specific members in the RAII object owning the context.
13320 union {
13321 /// The number of template arguments in TemplateArgs.
13322 unsigned NumTemplateArgs;
13323
13324 /// The number of expressions in CallArgs.
13325 unsigned NumCallArgs;
13326
13327 /// The special member being declared or defined.
13328 CXXSpecialMemberKind SpecialMember;
13329 };
13330
13331 ArrayRef<TemplateArgument> template_arguments() const {
13332 assert(Kind != DeclaringSpecialMember);
13333 return {TemplateArgs, NumTemplateArgs};
13334 }
13335
13336 /// The source range that covers the construct that cause
13337 /// the instantiation, e.g., the template-id that causes a class
13338 /// template instantiation.
13339 SourceRange InstantiationRange;
13340
13341 CodeSynthesisContext()
13342 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13343 InParameterMappingSubstitution(false), Entity(nullptr),
13344 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13345
13346 /// Determines whether this template is an actual instantiation
13347 /// that should be counted toward the maximum instantiation depth.
13348 bool isInstantiationRecord() const;
13349 };
13350
13351 /// A stack object to be created when performing template
13352 /// instantiation.
13353 ///
13354 /// Construction of an object of type \c InstantiatingTemplate
13355 /// pushes the current instantiation onto the stack of active
13356 /// instantiations. If the size of this stack exceeds the maximum
13357 /// number of recursive template instantiations, construction
13358 /// produces an error and evaluates true.
13359 ///
13360 /// Destruction of this object will pop the named instantiation off
13361 /// the stack.
13362 struct InstantiatingTemplate {
13363 /// Note that we are instantiating a class template,
13364 /// function template, variable template, alias template,
13365 /// or a member thereof.
13366 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13367 Decl *Entity,
13368 SourceRange InstantiationRange = SourceRange());
13369
13370 struct ExceptionSpecification {};
13371 /// Note that we are instantiating an exception specification
13372 /// of a function template.
13373 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13374 FunctionDecl *Entity, ExceptionSpecification,
13375 SourceRange InstantiationRange = SourceRange());
13376
13377 /// Note that we are instantiating a type alias template declaration.
13378 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13379 TypeAliasTemplateDecl *Entity,
13380 ArrayRef<TemplateArgument> TemplateArgs,
13381 SourceRange InstantiationRange = SourceRange());
13382
13383 /// Note that we are instantiating a default argument in a
13384 /// template-id.
13385 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13386 TemplateParameter Param, TemplateDecl *Template,
13387 ArrayRef<TemplateArgument> TemplateArgs,
13388 SourceRange InstantiationRange = SourceRange());
13389
13390 /// Note that we are substituting either explicitly-specified or
13391 /// deduced template arguments during function template argument deduction.
13392 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13393 FunctionTemplateDecl *FunctionTemplate,
13394 ArrayRef<TemplateArgument> TemplateArgs,
13395 CodeSynthesisContext::SynthesisKind Kind,
13396 SourceRange InstantiationRange = SourceRange());
13397
13398 /// Note that we are instantiating as part of template
13399 /// argument deduction for a class template declaration.
13400 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13401 TemplateDecl *Template,
13402 ArrayRef<TemplateArgument> TemplateArgs,
13403 SourceRange InstantiationRange = SourceRange());
13404
13405 /// Note that we are instantiating as part of template
13406 /// argument deduction for a class template partial
13407 /// specialization.
13408 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13409 ClassTemplatePartialSpecializationDecl *PartialSpec,
13410 ArrayRef<TemplateArgument> TemplateArgs,
13411 SourceRange InstantiationRange = SourceRange());
13412
13413 /// Note that we are instantiating as part of template
13414 /// argument deduction for a variable template partial
13415 /// specialization.
13416 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13417 VarTemplatePartialSpecializationDecl *PartialSpec,
13418 ArrayRef<TemplateArgument> TemplateArgs,
13419 SourceRange InstantiationRange = SourceRange());
13420
13421 /// Note that we are instantiating a default argument for a function
13422 /// parameter.
13423 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13424 ParmVarDecl *Param,
13425 ArrayRef<TemplateArgument> TemplateArgs,
13426 SourceRange InstantiationRange = SourceRange());
13427
13428 /// Note that we are substituting prior template arguments into a
13429 /// non-type parameter.
13430 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13431 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13432 ArrayRef<TemplateArgument> TemplateArgs,
13433 SourceRange InstantiationRange);
13434
13435 /// Note that we are substituting prior template arguments into a
13436 /// template template parameter.
13437 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13438 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13439 ArrayRef<TemplateArgument> TemplateArgs,
13440 SourceRange InstantiationRange);
13441
13442 /// Note that we are checking the default template argument
13443 /// against the template parameter for a given template-id.
13444 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13445 TemplateDecl *Template, NamedDecl *Param,
13446 ArrayRef<TemplateArgument> TemplateArgs,
13447 SourceRange InstantiationRange);
13448
13449 struct ConstraintsCheck {};
13450 /// \brief Note that we are checking the constraints associated with some
13451 /// constrained entity (a concept declaration or a template with associated
13452 /// constraints).
13453 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13454 ConstraintsCheck, NamedDecl *Template,
13455 ArrayRef<TemplateArgument> TemplateArgs,
13456 SourceRange InstantiationRange);
13457
13458 struct ConstraintSubstitution {};
13459 /// \brief Note that we are checking a constraint expression associated
13460 /// with a template declaration or as part of the satisfaction check of a
13461 /// concept.
13462 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13463 ConstraintSubstitution, NamedDecl *Template,
13464 SourceRange InstantiationRange);
13465
13466 struct ConstraintNormalization {};
13467 /// \brief Note that we are normalizing a constraint expression.
13468 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13469 ConstraintNormalization, NamedDecl *Template,
13470 SourceRange InstantiationRange);
13471
13472 struct ParameterMappingSubstitution {};
13473 /// \brief Note that we are subtituting into the parameter mapping of an
13474 /// atomic constraint during constraint normalization.
13475 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13476 ParameterMappingSubstitution, NamedDecl *Template,
13477 SourceRange InstantiationRange);
13478
13479 /// \brief Note that we are substituting template arguments into a part of
13480 /// a requirement of a requires expression.
13481 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13482 concepts::Requirement *Req,
13483 SourceRange InstantiationRange = SourceRange());
13484
13485 /// \brief Note that we are checking the satisfaction of the constraint
13486 /// expression inside of a nested requirement.
13487 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13488 concepts::NestedRequirement *Req, ConstraintsCheck,
13489 SourceRange InstantiationRange = SourceRange());
13490
13491 /// \brief Note that we are checking a requires clause.
13492 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13493 const RequiresExpr *E,
13494 SourceRange InstantiationRange);
13495
13496 struct BuildingDeductionGuidesTag {};
13497 /// \brief Note that we are building deduction guides.
13498 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13499 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13500 SourceRange InstantiationRange = SourceRange());
13501
13502 struct PartialOrderingTTP {};
13503 /// \brief Note that we are partial ordering template template parameters.
13504 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13505 PartialOrderingTTP, TemplateDecl *PArg,
13506 SourceRange InstantiationRange = SourceRange());
13507
13508 /// Note that we have finished instantiating this template.
13509 void Clear();
13510
13511 ~InstantiatingTemplate() { Clear(); }
13512
13513 /// Determines whether we have exceeded the maximum
13514 /// recursive template instantiations.
13515 bool isInvalid() const { return Invalid; }
13516
13517 private:
13518 Sema &SemaRef;
13519 bool Invalid;
13520
13521 InstantiatingTemplate(Sema &SemaRef,
13522 CodeSynthesisContext::SynthesisKind Kind,
13523 SourceLocation PointOfInstantiation,
13524 SourceRange InstantiationRange, Decl *Entity,
13525 NamedDecl *Template = nullptr,
13526 ArrayRef<TemplateArgument> TemplateArgs = {});
13527
13528 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13529
13530 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13531 };
13532
13533 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13534 const MultiLevelTemplateArgumentList &TemplateArgs,
13535 TemplateArgumentLoc &Output,
13536 SourceLocation Loc = {},
13537 const DeclarationName &Entity = {});
13538 bool
13539 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13540 const MultiLevelTemplateArgumentList &TemplateArgs,
13541 TemplateArgumentListInfo &Outputs);
13542
13543 /// Substitute concept template arguments in the constraint expression
13544 /// of a concept-id. This is used to implement [temp.constr.normal].
13545 ExprResult
13546 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13547 const Expr *ConstraintExpr,
13548 const MultiLevelTemplateArgumentList &MLTAL);
13549
13550 bool SubstTemplateArgumentsInParameterMapping(
13551 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13552 const MultiLevelTemplateArgumentList &TemplateArgs,
13553 TemplateArgumentListInfo &Out);
13554
13555 /// Retrieve the template argument list(s) that should be used to
13556 /// instantiate the definition of the given declaration.
13557 ///
13558 /// \param ND the declaration for which we are computing template
13559 /// instantiation arguments.
13560 ///
13561 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13562 /// the decl context where it will be created. In this case, the `Innermost`
13563 /// should likely be provided. If ND is non-null, this is ignored.
13564 ///
13565 /// \param Innermost if non-NULL, specifies a template argument list for the
13566 /// template declaration passed as ND.
13567 ///
13568 /// \param RelativeToPrimary true if we should get the template
13569 /// arguments relative to the primary template, even when we're
13570 /// dealing with a specialization. This is only relevant for function
13571 /// template specializations.
13572 ///
13573 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13574 /// instantiating the definition of the given declaration, \p ND. This is
13575 /// used to determine the proper set of template instantiation arguments for
13576 /// friend function template specializations.
13577 ///
13578 /// \param ForConstraintInstantiation when collecting arguments,
13579 /// ForConstraintInstantiation indicates we should continue looking when
13580 /// encountering a lambda generic call operator, and continue looking for
13581 /// arguments on an enclosing class template.
13582 ///
13583 /// \param SkipForSpecialization when specified, any template specializations
13584 /// in a traversal would be ignored.
13585 ///
13586 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13587 /// when encountering a specialized member function template, rather than
13588 /// returning immediately.
13589 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13590 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13591 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13592 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13593 bool ForConstraintInstantiation = false,
13594 bool SkipForSpecialization = false,
13595 bool ForDefaultArgumentSubstitution = false);
13596
13597 /// RAII object to handle the state changes required to synthesize
13598 /// a function body.
13599 class SynthesizedFunctionScope {
13600 Sema &S;
13601 Sema::ContextRAII SavedContext;
13602 bool PushedCodeSynthesisContext = false;
13603
13604 public:
13605 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13606 : S(S), SavedContext(S, DC) {
13607 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13608 S.PushFunctionScope();
13609 S.PushExpressionEvaluationContextForFunction(
13610 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13611 if (FD)
13612 FD->setWillHaveBody(true);
13613 else
13614 assert(isa<ObjCMethodDecl>(DC));
13615 }
13616
13617 void addContextNote(SourceLocation UseLoc) {
13618 assert(!PushedCodeSynthesisContext);
13619
13620 Sema::CodeSynthesisContext Ctx;
13621 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13622 Ctx.PointOfInstantiation = UseLoc;
13623 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13624 S.pushCodeSynthesisContext(Ctx);
13625
13626 PushedCodeSynthesisContext = true;
13627 }
13628
13629 ~SynthesizedFunctionScope() {
13630 if (PushedCodeSynthesisContext)
13631 S.popCodeSynthesisContext();
13632 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13633 FD->setWillHaveBody(false);
13634 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13635 }
13636 S.PopExpressionEvaluationContext();
13637 S.PopFunctionScopeInfo();
13638 }
13639
13640 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13641 SynthesizedFunctionScope &
13642 operator=(const SynthesizedFunctionScope &) = delete;
13643 };
13644
13645 /// RAII object to ensure that a code synthesis context is popped on scope
13646 /// exit.
13647 class ScopedCodeSynthesisContext {
13648 Sema &S;
13649
13650 public:
13651 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13652 : S(S) {
13653 S.pushCodeSynthesisContext(Ctx);
13654 }
13655
13656 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13657 };
13658
13659 /// List of active code synthesis contexts.
13660 ///
13661 /// This vector is treated as a stack. As synthesis of one entity requires
13662 /// synthesis of another, additional contexts are pushed onto the stack.
13663 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13664
13665 /// Specializations whose definitions are currently being instantiated.
13666 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13667
13668 /// Non-dependent types used in templates that have already been instantiated
13669 /// by some template instantiation.
13670 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13671
13672 /// Extra modules inspected when performing a lookup during a template
13673 /// instantiation. Computed lazily.
13674 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13675
13676 /// Cache of additional modules that should be used for name lookup
13677 /// within the current template instantiation. Computed lazily; use
13678 /// getLookupModules() to get a complete set.
13679 llvm::DenseSet<Module *> LookupModulesCache;
13680
13681 /// Map from the most recent declaration of a namespace to the most
13682 /// recent visible declaration of that namespace.
13683 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13684
13685 SFINAETrap *CurrentSFINAEContext = nullptr;
13686
13687 /// The number of \p CodeSynthesisContexts that are not template
13688 /// instantiations and, therefore, should not be counted as part of the
13689 /// instantiation depth.
13690 ///
13691 /// When the instantiation depth reaches the user-configurable limit
13692 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13693 // FIXME: Should we have a similar limit for other forms of synthesis?
13694 unsigned NonInstantiationEntries;
13695
13696 /// The depth of the context stack at the point when the most recent
13697 /// error or warning was produced.
13698 ///
13699 /// This value is used to suppress printing of redundant context stacks
13700 /// when there are multiple errors or warnings in the same instantiation.
13701 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13702 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13703
13704 /// The template instantiation callbacks to trace or track
13705 /// instantiations (objects can be chained).
13706 ///
13707 /// This callbacks is used to print, trace or track template
13708 /// instantiations as they are being constructed.
13709 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
13710 TemplateInstCallbacks;
13711
13712 /// The current index into pack expansion arguments that will be
13713 /// used for substitution of parameter packs.
13714 ///
13715 /// The pack expansion index will be none to indicate that parameter packs
13716 /// should be instantiated as themselves. Otherwise, the index specifies
13717 /// which argument within the parameter pack will be used for substitution.
13718 UnsignedOrNone ArgPackSubstIndex;
13719
13720 /// RAII object used to change the argument pack substitution index
13721 /// within a \c Sema object.
13722 ///
13723 /// See \c ArgPackSubstIndex for more information.
13724 class ArgPackSubstIndexRAII {
13725 Sema &Self;
13726 UnsignedOrNone OldSubstIndex;
13727
13728 public:
13729 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13730 : Self(Self),
13731 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13732
13733 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13734 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13735 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13736 };
13737
13738 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13739 void popCodeSynthesisContext();
13740
13741 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13742 if (!CodeSynthesisContexts.empty() &&
13743 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13744 PrintInstantiationStack(DiagFunc);
13745 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13746 }
13747 if (PragmaAttributeCurrentTargetDecl)
13748 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13749 }
13750 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13751 /// Prints the current instantiation stack through a series of
13752 /// notes.
13753 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13754 void PrintInstantiationStack() {
13755 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13756 }
13757
13758 /// Returns a pointer to the current SFINAE context, if any.
13759 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13760 return CurrentSFINAEContext;
13761 }
13762 [[nodiscard]] bool isSFINAEContext() const {
13763 return CurrentSFINAEContext != nullptr;
13764 }
13765
13766 /// Perform substitution on the type T with a given set of template
13767 /// arguments.
13768 ///
13769 /// This routine substitutes the given template arguments into the
13770 /// type T and produces the instantiated type.
13771 ///
13772 /// \param T the type into which the template arguments will be
13773 /// substituted. If this type is not dependent, it will be returned
13774 /// immediately.
13775 ///
13776 /// \param Args the template arguments that will be
13777 /// substituted for the top-level template parameters within T.
13778 ///
13779 /// \param Loc the location in the source code where this substitution
13780 /// is being performed. It will typically be the location of the
13781 /// declarator (if we're instantiating the type of some declaration)
13782 /// or the location of the type in the source code (if, e.g., we're
13783 /// instantiating the type of a cast expression).
13784 ///
13785 /// \param Entity the name of the entity associated with a declaration
13786 /// being instantiated (if any). May be empty to indicate that there
13787 /// is no such entity (if, e.g., this is a type that occurs as part of
13788 /// a cast expression) or that the entity has no name (e.g., an
13789 /// unnamed function parameter).
13790 ///
13791 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13792 /// acceptable as the top level type of the result.
13793 ///
13794 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13795 /// whenever substitution would perform a replacement with a null or
13796 /// non-existent template argument.
13797 ///
13798 /// \returns If the instantiation succeeds, the instantiated
13799 /// type. Otherwise, produces diagnostics and returns a NULL type.
13800 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13801 const MultiLevelTemplateArgumentList &TemplateArgs,
13802 SourceLocation Loc, DeclarationName Entity,
13803 bool AllowDeducedTST = false);
13804
13805 QualType SubstType(QualType T,
13806 const MultiLevelTemplateArgumentList &TemplateArgs,
13807 SourceLocation Loc, DeclarationName Entity,
13808 bool *IsIncompleteSubstitution = nullptr);
13809
13810 TypeSourceInfo *SubstType(TypeLoc TL,
13811 const MultiLevelTemplateArgumentList &TemplateArgs,
13812 SourceLocation Loc, DeclarationName Entity);
13813
13814 /// A form of SubstType intended specifically for instantiating the
13815 /// type of a FunctionDecl. Its purpose is solely to force the
13816 /// instantiation of default-argument expressions and to avoid
13817 /// instantiating an exception-specification.
13818 TypeSourceInfo *SubstFunctionDeclType(
13819 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13820 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13821 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13822 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13823 const MultiLevelTemplateArgumentList &Args);
13824 bool SubstExceptionSpec(SourceLocation Loc,
13825 FunctionProtoType::ExceptionSpecInfo &ESI,
13826 SmallVectorImpl<QualType> &ExceptionStorage,
13827 const MultiLevelTemplateArgumentList &Args);
13828 ParmVarDecl *
13829 SubstParmVarDecl(ParmVarDecl *D,
13830 const MultiLevelTemplateArgumentList &TemplateArgs,
13831 int indexAdjustment, UnsignedOrNone NumExpansions,
13832 bool ExpectParameterPack, bool EvaluateConstraints = true);
13833
13834 /// Substitute the given template arguments into the given set of
13835 /// parameters, producing the set of parameter types that would be generated
13836 /// from such a substitution.
13837 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13838 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13839 const MultiLevelTemplateArgumentList &TemplateArgs,
13840 SmallVectorImpl<QualType> &ParamTypes,
13841 SmallVectorImpl<ParmVarDecl *> *OutParams,
13842 ExtParameterInfoBuilder &ParamInfos);
13843
13844 /// Substitute the given template arguments into the default argument.
13845 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13846 const MultiLevelTemplateArgumentList &TemplateArgs,
13847 bool ForCallExpr = false);
13848 ExprResult SubstExpr(Expr *E,
13849 const MultiLevelTemplateArgumentList &TemplateArgs);
13850 /// Substitute an expression as if it is a address-of-operand, which makes it
13851 /// act like a CXXIdExpression rather than an attempt to call.
13852 ExprResult SubstCXXIdExpr(Expr *E,
13853 const MultiLevelTemplateArgumentList &TemplateArgs);
13854
13855 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
13856 // to disable constraint evaluation, then restore the state.
13857 template <typename InstTy> struct ConstraintEvalRAII {
13858 InstTy &TI;
13859 bool OldValue;
13860
13861 ConstraintEvalRAII(InstTy &TI)
13862 : TI(TI), OldValue(TI.getEvaluateConstraints()) {
13863 TI.setEvaluateConstraints(false);
13864 }
13865 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
13866 ConstraintEvalRAII(const ConstraintEvalRAII &) = delete;
13867 ConstraintEvalRAII &operator=(const ConstraintEvalRAII &) = delete;
13868 };
13869
13870 // Must be used instead of SubstExpr at 'constraint checking' time.
13871 ExprResult
13872 SubstConstraintExpr(Expr *E,
13873 const MultiLevelTemplateArgumentList &TemplateArgs);
13874 // Unlike the above, this does not evaluate constraints.
13875 ExprResult SubstConstraintExprWithoutSatisfaction(
13876 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13877
13878 /// Substitute the given template arguments into a list of
13879 /// expressions, expanding pack expansions if required.
13880 ///
13881 /// \param Exprs The list of expressions to substitute into.
13882 ///
13883 /// \param IsCall Whether this is some form of call, in which case
13884 /// default arguments will be dropped.
13885 ///
13886 /// \param TemplateArgs The set of template arguments to substitute.
13887 ///
13888 /// \param Outputs Will receive all of the substituted arguments.
13889 ///
13890 /// \returns true if an error occurred, false otherwise.
13891 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13892 const MultiLevelTemplateArgumentList &TemplateArgs,
13893 SmallVectorImpl<Expr *> &Outputs);
13894
13895 StmtResult SubstStmt(Stmt *S,
13896 const MultiLevelTemplateArgumentList &TemplateArgs);
13897
13898 ExprResult
13899 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
13900 bool CXXDirectInit);
13901
13902 /// Perform substitution on the base class specifiers of the
13903 /// given class template specialization.
13904 ///
13905 /// Produces a diagnostic and returns true on error, returns false and
13906 /// attaches the instantiated base classes to the class template
13907 /// specialization if successful.
13908 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13909 const MultiLevelTemplateArgumentList &TemplateArgs);
13910
13911 /// Instantiate the definition of a class from a given pattern.
13912 ///
13913 /// \param PointOfInstantiation The point of instantiation within the
13914 /// source code.
13915 ///
13916 /// \param Instantiation is the declaration whose definition is being
13917 /// instantiated. This will be either a class template specialization
13918 /// or a member class of a class template specialization.
13919 ///
13920 /// \param Pattern is the pattern from which the instantiation
13921 /// occurs. This will be either the declaration of a class template or
13922 /// the declaration of a member class of a class template.
13923 ///
13924 /// \param TemplateArgs The template arguments to be substituted into
13925 /// the pattern.
13926 ///
13927 /// \param TSK the kind of implicit or explicit instantiation to perform.
13928 ///
13929 /// \param Complain whether to complain if the class cannot be instantiated
13930 /// due to the lack of a definition.
13931 ///
13932 /// \returns true if an error occurred, false otherwise.
13933 bool InstantiateClass(SourceLocation PointOfInstantiation,
13934 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13935 const MultiLevelTemplateArgumentList &TemplateArgs,
13936 TemplateSpecializationKind TSK, bool Complain = true);
13937
13938private:
13939 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13940 CXXRecordDecl *Instantiation,
13941 CXXRecordDecl *Pattern,
13942 const MultiLevelTemplateArgumentList &TemplateArgs,
13943 TemplateSpecializationKind TSK, bool Complain);
13944
13945public:
13946 /// Instantiate the definition of an enum from a given pattern.
13947 ///
13948 /// \param PointOfInstantiation The point of instantiation within the
13949 /// source code.
13950 /// \param Instantiation is the declaration whose definition is being
13951 /// instantiated. This will be a member enumeration of a class
13952 /// temploid specialization, or a local enumeration within a
13953 /// function temploid specialization.
13954 /// \param Pattern The templated declaration from which the instantiation
13955 /// occurs.
13956 /// \param TemplateArgs The template arguments to be substituted into
13957 /// the pattern.
13958 /// \param TSK The kind of implicit or explicit instantiation to perform.
13959 ///
13960 /// \return \c true if an error occurred, \c false otherwise.
13961 bool InstantiateEnum(SourceLocation PointOfInstantiation,
13962 EnumDecl *Instantiation, EnumDecl *Pattern,
13963 const MultiLevelTemplateArgumentList &TemplateArgs,
13964 TemplateSpecializationKind TSK);
13965
13966 /// Instantiate the definition of a field from the given pattern.
13967 ///
13968 /// \param PointOfInstantiation The point of instantiation within the
13969 /// source code.
13970 /// \param Instantiation is the declaration whose definition is being
13971 /// instantiated. This will be a class of a class temploid
13972 /// specialization, or a local enumeration within a function temploid
13973 /// specialization.
13974 /// \param Pattern The templated declaration from which the instantiation
13975 /// occurs.
13976 /// \param TemplateArgs The template arguments to be substituted into
13977 /// the pattern.
13978 ///
13979 /// \return \c true if an error occurred, \c false otherwise.
13980 bool InstantiateInClassInitializer(
13981 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
13982 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
13983
13984 bool usesPartialOrExplicitSpecialization(
13985 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
13986
13987 bool InstantiateClassTemplateSpecialization(
13988 SourceLocation PointOfInstantiation,
13989 ClassTemplateSpecializationDecl *ClassTemplateSpec,
13990 TemplateSpecializationKind TSK, bool Complain,
13991 bool PrimaryStrictPackMatch);
13992
13993 /// Instantiates the definitions of all of the member
13994 /// of the given class, which is an instantiation of a class template
13995 /// or a member class of a template.
13996 void
13997 InstantiateClassMembers(SourceLocation PointOfInstantiation,
13998 CXXRecordDecl *Instantiation,
13999 const MultiLevelTemplateArgumentList &TemplateArgs,
14000 TemplateSpecializationKind TSK);
14001
14002 /// Instantiate the definitions of all of the members of the
14003 /// given class template specialization, which was named as part of an
14004 /// explicit instantiation.
14005 void InstantiateClassTemplateSpecializationMembers(
14006 SourceLocation PointOfInstantiation,
14007 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14008 TemplateSpecializationKind TSK);
14009
14010 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14011 NestedNameSpecifierLoc NNS,
14012 const MultiLevelTemplateArgumentList &TemplateArgs);
14013
14014 /// Do template substitution on declaration name info.
14015 DeclarationNameInfo
14016 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14017 const MultiLevelTemplateArgumentList &TemplateArgs);
14018 TemplateName
14019 SubstTemplateName(SourceLocation TemplateKWLoc,
14020 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14021 SourceLocation NameLoc,
14022 const MultiLevelTemplateArgumentList &TemplateArgs);
14023
14024 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14025 const MultiLevelTemplateArgumentList &TemplateArgs,
14026 bool EvaluateConstraint);
14027
14028 /// Determine whether we are currently performing template instantiation.
14029 bool inTemplateInstantiation() const {
14030 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14031 }
14032
14033 /// Determine whether we are currently performing constraint substitution.
14034 bool inConstraintSubstitution() const {
14035 return !CodeSynthesisContexts.empty() &&
14036 CodeSynthesisContexts.back().InConstraintSubstitution;
14037 }
14038
14039 bool inParameterMappingSubstitution() const {
14040 return !CodeSynthesisContexts.empty() &&
14041 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14042 !inConstraintSubstitution();
14043 }
14044
14045 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14046
14047 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14048 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14049 concepts::Requirement::SubstitutionDiagnostic *
14050 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14051
14052 ///@}
14053
14054 //
14055 //
14056 // -------------------------------------------------------------------------
14057 //
14058 //
14059
14060 /// \name C++ Template Declaration Instantiation
14061 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14062 ///@{
14063
14064public:
14065 /// An entity for which implicit template instantiation is required.
14066 ///
14067 /// The source location associated with the declaration is the first place in
14068 /// the source code where the declaration was "used". It is not necessarily
14069 /// the point of instantiation (which will be either before or after the
14070 /// namespace-scope declaration that triggered this implicit instantiation),
14071 /// However, it is the location that diagnostics should generally refer to,
14072 /// because users will need to know what code triggered the instantiation.
14073 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14074
14075 /// The queue of implicit template instantiations that are required
14076 /// but have not yet been performed.
14077 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14078
14079 /// Queue of implicit template instantiations that cannot be performed
14080 /// eagerly.
14081 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14082
14083 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14084 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14085 SavedPendingInstantiations;
14086
14087 /// The queue of implicit template instantiations that are required
14088 /// and must be performed within the current local scope.
14089 ///
14090 /// This queue is only used for member functions of local classes in
14091 /// templates, which must be instantiated in the same scope as their
14092 /// enclosing function, so that they can reference function-local
14093 /// types, static variables, enumerators, etc.
14094 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14095
14096 class LocalEagerInstantiationScope {
14097 public:
14098 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14099 : S(S), AtEndOfTU(AtEndOfTU) {
14100 SavedPendingLocalImplicitInstantiations.swap(
14101 x&: S.PendingLocalImplicitInstantiations);
14102 }
14103
14104 void perform() {
14105 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14106 /*AtEndOfTU=*/AtEndOfTU);
14107 }
14108
14109 ~LocalEagerInstantiationScope() {
14110 assert(S.PendingLocalImplicitInstantiations.empty() &&
14111 "there shouldn't be any pending local implicit instantiations");
14112 SavedPendingLocalImplicitInstantiations.swap(
14113 x&: S.PendingLocalImplicitInstantiations);
14114 }
14115
14116 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14117 LocalEagerInstantiationScope &
14118 operator=(const LocalEagerInstantiationScope &) = delete;
14119
14120 private:
14121 Sema &S;
14122 bool AtEndOfTU;
14123 std::deque<PendingImplicitInstantiation>
14124 SavedPendingLocalImplicitInstantiations;
14125 };
14126
14127 /// Records and restores the CurFPFeatures state on entry/exit of compound
14128 /// statements.
14129 class FPFeaturesStateRAII {
14130 public:
14131 FPFeaturesStateRAII(Sema &S);
14132 ~FPFeaturesStateRAII();
14133 FPOptionsOverride getOverrides() { return OldOverrides; }
14134
14135 private:
14136 Sema &S;
14137 FPOptions OldFPFeaturesState;
14138 FPOptionsOverride OldOverrides;
14139 LangOptions::FPEvalMethodKind OldEvalMethod;
14140 SourceLocation OldFPPragmaLocation;
14141 };
14142
14143 class GlobalEagerInstantiationScope {
14144 public:
14145 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14146 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14147 if (!Enabled)
14148 return;
14149
14150 S.SavedPendingInstantiations.emplace_back();
14151 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14152
14153 S.SavedVTableUses.emplace_back();
14154 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14155 }
14156
14157 void perform() {
14158 if (Enabled) {
14159 S.DefineUsedVTables();
14160 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14161 /*AtEndOfTU=*/AtEndOfTU);
14162 }
14163 }
14164
14165 ~GlobalEagerInstantiationScope() {
14166 if (!Enabled)
14167 return;
14168
14169 // Restore the set of pending vtables.
14170 assert(S.VTableUses.empty() &&
14171 "VTableUses should be empty before it is discarded.");
14172 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14173 S.SavedVTableUses.pop_back();
14174
14175 // Restore the set of pending implicit instantiations.
14176 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14177 AtEndOfTU) {
14178 assert(S.PendingInstantiations.empty() &&
14179 "PendingInstantiations should be empty before it is discarded.");
14180 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14181 S.SavedPendingInstantiations.pop_back();
14182 } else {
14183 // Template instantiations in the PCH may be delayed until the TU.
14184 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14185 S.PendingInstantiations.insert(
14186 position: S.PendingInstantiations.end(),
14187 first: S.SavedPendingInstantiations.back().begin(),
14188 last: S.SavedPendingInstantiations.back().end());
14189 S.SavedPendingInstantiations.pop_back();
14190 }
14191 }
14192
14193 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14194 delete;
14195 GlobalEagerInstantiationScope &
14196 operator=(const GlobalEagerInstantiationScope &) = delete;
14197
14198 private:
14199 Sema &S;
14200 bool Enabled;
14201 bool AtEndOfTU;
14202 };
14203
14204 ExplicitSpecifier instantiateExplicitSpecifier(
14205 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14206
14207 struct LateInstantiatedAttribute {
14208 const Attr *TmplAttr;
14209 LocalInstantiationScope *Scope;
14210 Decl *NewDecl;
14211
14212 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14213 Decl *D)
14214 : TmplAttr(A), Scope(S), NewDecl(D) {}
14215 };
14216 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14217
14218 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14219 const Decl *Pattern, Decl *Inst,
14220 LateInstantiatedAttrVec *LateAttrs = nullptr,
14221 LocalInstantiationScope *OuterMostScope = nullptr);
14222
14223 /// Update instantiation attributes after template was late parsed.
14224 ///
14225 /// Some attributes are evaluated based on the body of template. If it is
14226 /// late parsed, such attributes cannot be evaluated when declaration is
14227 /// instantiated. This function is used to update instantiation attributes
14228 /// when template definition is ready.
14229 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14230
14231 void
14232 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14233 const Decl *Pattern, Decl *Inst,
14234 LateInstantiatedAttrVec *LateAttrs = nullptr,
14235 LocalInstantiationScope *OuterMostScope = nullptr);
14236
14237 /// In the MS ABI, we need to instantiate default arguments of dllexported
14238 /// default constructors along with the constructor definition. This allows IR
14239 /// gen to emit a constructor closure which calls the default constructor with
14240 /// its default arguments.
14241 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
14242
14243 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14244 ParmVarDecl *Param);
14245 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14246 FunctionDecl *Function);
14247
14248 /// Instantiate (or find existing instantiation of) a function template with a
14249 /// given set of template arguments.
14250 ///
14251 /// Usually this should not be used, and template argument deduction should be
14252 /// used in its place.
14253 FunctionDecl *InstantiateFunctionDeclaration(
14254 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14255 SourceLocation Loc,
14256 CodeSynthesisContext::SynthesisKind CSC =
14257 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14258
14259 /// Instantiate the definition of the given function from its
14260 /// template.
14261 ///
14262 /// \param PointOfInstantiation the point at which the instantiation was
14263 /// required. Note that this is not precisely a "point of instantiation"
14264 /// for the function, but it's close.
14265 ///
14266 /// \param Function the already-instantiated declaration of a
14267 /// function template specialization or member function of a class template
14268 /// specialization.
14269 ///
14270 /// \param Recursive if true, recursively instantiates any functions that
14271 /// are required by this instantiation.
14272 ///
14273 /// \param DefinitionRequired if true, then we are performing an explicit
14274 /// instantiation where the body of the function is required. Complain if
14275 /// there is no such body.
14276 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14277 FunctionDecl *Function,
14278 bool Recursive = false,
14279 bool DefinitionRequired = false,
14280 bool AtEndOfTU = false);
14281 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14282 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14283 const TemplateArgumentList *PartialSpecArgs,
14284 SmallVectorImpl<TemplateArgument> &Converted,
14285 SourceLocation PointOfInstantiation,
14286 LateInstantiatedAttrVec *LateAttrs = nullptr,
14287 LocalInstantiationScope *StartingScope = nullptr);
14288
14289 /// Instantiates a variable template specialization by completing it
14290 /// with appropriate type information and initializer.
14291 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14292 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14293 const MultiLevelTemplateArgumentList &TemplateArgs);
14294
14295 /// BuildVariableInstantiation - Used after a new variable has been created.
14296 /// Sets basic variable data and decides whether to postpone the
14297 /// variable instantiation.
14298 void
14299 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14300 const MultiLevelTemplateArgumentList &TemplateArgs,
14301 LateInstantiatedAttrVec *LateAttrs,
14302 DeclContext *Owner,
14303 LocalInstantiationScope *StartingScope,
14304 bool InstantiatingVarTemplate = false,
14305 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14306
14307 /// Instantiate the initializer of a variable.
14308 void InstantiateVariableInitializer(
14309 VarDecl *Var, VarDecl *OldVar,
14310 const MultiLevelTemplateArgumentList &TemplateArgs);
14311
14312 /// Instantiate the definition of the given variable from its
14313 /// template.
14314 ///
14315 /// \param PointOfInstantiation the point at which the instantiation was
14316 /// required. Note that this is not precisely a "point of instantiation"
14317 /// for the variable, but it's close.
14318 ///
14319 /// \param Var the already-instantiated declaration of a templated variable.
14320 ///
14321 /// \param Recursive if true, recursively instantiates any functions that
14322 /// are required by this instantiation.
14323 ///
14324 /// \param DefinitionRequired if true, then we are performing an explicit
14325 /// instantiation where a definition of the variable is required. Complain
14326 /// if there is no such definition.
14327 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14328 VarDecl *Var, bool Recursive = false,
14329 bool DefinitionRequired = false,
14330 bool AtEndOfTU = false);
14331
14332 void InstantiateMemInitializers(
14333 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14334 const MultiLevelTemplateArgumentList &TemplateArgs);
14335
14336 /// Find the instantiation of the given declaration within the
14337 /// current instantiation.
14338 ///
14339 /// This routine is intended to be used when \p D is a declaration
14340 /// referenced from within a template, that needs to mapped into the
14341 /// corresponding declaration within an instantiation. For example,
14342 /// given:
14343 ///
14344 /// \code
14345 /// template<typename T>
14346 /// struct X {
14347 /// enum Kind {
14348 /// KnownValue = sizeof(T)
14349 /// };
14350 ///
14351 /// bool getKind() const { return KnownValue; }
14352 /// };
14353 ///
14354 /// template struct X<int>;
14355 /// \endcode
14356 ///
14357 /// In the instantiation of X<int>::getKind(), we need to map the \p
14358 /// EnumConstantDecl for \p KnownValue (which refers to
14359 /// X<T>::<Kind>::KnownValue) to its instantiation
14360 /// (X<int>::<Kind>::KnownValue).
14361 /// \p FindInstantiatedDecl performs this mapping from within the
14362 /// instantiation of X<int>.
14363 NamedDecl *
14364 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14365 const MultiLevelTemplateArgumentList &TemplateArgs,
14366 bool FindingInstantiatedContext = false);
14367
14368 /// Finds the instantiation of the given declaration context
14369 /// within the current instantiation.
14370 ///
14371 /// \returns NULL if there was an error
14372 DeclContext *
14373 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14374 const MultiLevelTemplateArgumentList &TemplateArgs);
14375
14376 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14377 const MultiLevelTemplateArgumentList &TemplateArgs);
14378
14379 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14380 /// an implicit 'operator=='.
14381 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14382 FunctionDecl *Spaceship);
14383
14384 /// Performs template instantiation for all implicit template
14385 /// instantiations we have seen until this point.
14386 void PerformPendingInstantiations(bool LocalOnly = false,
14387 bool AtEndOfTU = true);
14388
14389 TemplateParameterList *
14390 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14391 const MultiLevelTemplateArgumentList &TemplateArgs,
14392 bool EvaluateConstraints = true);
14393
14394 void PerformDependentDiagnostics(
14395 const DeclContext *Pattern,
14396 const MultiLevelTemplateArgumentList &TemplateArgs);
14397
14398private:
14399 /// Introduce the instantiated local variables into the local
14400 /// instantiation scope.
14401 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14402 const FunctionDecl *PatternDecl,
14403 LocalInstantiationScope &Scope);
14404 /// Introduce the instantiated function parameters into the local
14405 /// instantiation scope, and set the parameter names to those used
14406 /// in the template.
14407 bool addInstantiatedParametersToScope(
14408 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14409 LocalInstantiationScope &Scope,
14410 const MultiLevelTemplateArgumentList &TemplateArgs);
14411
14412 /// Introduce the instantiated captures of the lambda into the local
14413 /// instantiation scope.
14414 bool addInstantiatedCapturesToScope(
14415 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14416 LocalInstantiationScope &Scope,
14417 const MultiLevelTemplateArgumentList &TemplateArgs);
14418
14419 int ParsingClassDepth = 0;
14420
14421 class SavePendingParsedClassStateRAII {
14422 public:
14423 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14424
14425 ~SavePendingParsedClassStateRAII() {
14426 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14427 "there shouldn't be any pending delayed exception spec checks");
14428 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14429 "there shouldn't be any pending delayed exception spec checks");
14430 swapSavedState();
14431 }
14432
14433 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14434 delete;
14435 SavePendingParsedClassStateRAII &
14436 operator=(const SavePendingParsedClassStateRAII &) = delete;
14437
14438 private:
14439 Sema &S;
14440 decltype(DelayedOverridingExceptionSpecChecks)
14441 SavedOverridingExceptionSpecChecks;
14442 decltype(DelayedEquivalentExceptionSpecChecks)
14443 SavedEquivalentExceptionSpecChecks;
14444
14445 void swapSavedState() {
14446 SavedOverridingExceptionSpecChecks.swap(
14447 RHS&: S.DelayedOverridingExceptionSpecChecks);
14448 SavedEquivalentExceptionSpecChecks.swap(
14449 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14450 }
14451 };
14452
14453 ///@}
14454
14455 //
14456 //
14457 // -------------------------------------------------------------------------
14458 //
14459 //
14460
14461 /// \name C++ Variadic Templates
14462 /// Implementations are in SemaTemplateVariadic.cpp
14463 ///@{
14464
14465public:
14466 /// Determine whether an unexpanded parameter pack might be permitted in this
14467 /// location. Useful for error recovery.
14468 bool isUnexpandedParameterPackPermitted();
14469
14470 /// The context in which an unexpanded parameter pack is
14471 /// being diagnosed.
14472 ///
14473 /// Note that the values of this enumeration line up with the first
14474 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14475 enum UnexpandedParameterPackContext {
14476 /// An arbitrary expression.
14477 UPPC_Expression = 0,
14478
14479 /// The base type of a class type.
14480 UPPC_BaseType,
14481
14482 /// The type of an arbitrary declaration.
14483 UPPC_DeclarationType,
14484
14485 /// The type of a data member.
14486 UPPC_DataMemberType,
14487
14488 /// The size of a bit-field.
14489 UPPC_BitFieldWidth,
14490
14491 /// The expression in a static assertion.
14492 UPPC_StaticAssertExpression,
14493
14494 /// The fixed underlying type of an enumeration.
14495 UPPC_FixedUnderlyingType,
14496
14497 /// The enumerator value.
14498 UPPC_EnumeratorValue,
14499
14500 /// A using declaration.
14501 UPPC_UsingDeclaration,
14502
14503 /// A friend declaration.
14504 UPPC_FriendDeclaration,
14505
14506 /// A declaration qualifier.
14507 UPPC_DeclarationQualifier,
14508
14509 /// An initializer.
14510 UPPC_Initializer,
14511
14512 /// A default argument.
14513 UPPC_DefaultArgument,
14514
14515 /// The type of a non-type template parameter.
14516 UPPC_NonTypeTemplateParameterType,
14517
14518 /// The type of an exception.
14519 UPPC_ExceptionType,
14520
14521 /// Explicit specialization.
14522 UPPC_ExplicitSpecialization,
14523
14524 /// Partial specialization.
14525 UPPC_PartialSpecialization,
14526
14527 /// Microsoft __if_exists.
14528 UPPC_IfExists,
14529
14530 /// Microsoft __if_not_exists.
14531 UPPC_IfNotExists,
14532
14533 /// Lambda expression.
14534 UPPC_Lambda,
14535
14536 /// Block expression.
14537 UPPC_Block,
14538
14539 /// A type constraint.
14540 UPPC_TypeConstraint,
14541
14542 // A requirement in a requires-expression.
14543 UPPC_Requirement,
14544
14545 // A requires-clause.
14546 UPPC_RequiresClause,
14547 };
14548
14549 /// Diagnose unexpanded parameter packs.
14550 ///
14551 /// \param Loc The location at which we should emit the diagnostic.
14552 ///
14553 /// \param UPPC The context in which we are diagnosing unexpanded
14554 /// parameter packs.
14555 ///
14556 /// \param Unexpanded the set of unexpanded parameter packs.
14557 ///
14558 /// \returns true if an error occurred, false otherwise.
14559 bool DiagnoseUnexpandedParameterPacks(
14560 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14561 ArrayRef<UnexpandedParameterPack> Unexpanded);
14562
14563 /// If the given type contains an unexpanded parameter pack,
14564 /// diagnose the error.
14565 ///
14566 /// \param Loc The source location where a diagnostc should be emitted.
14567 ///
14568 /// \param T The type that is being checked for unexpanded parameter
14569 /// packs.
14570 ///
14571 /// \returns true if an error occurred, false otherwise.
14572 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14573 UnexpandedParameterPackContext UPPC);
14574
14575 /// If the given expression contains an unexpanded parameter
14576 /// pack, diagnose the error.
14577 ///
14578 /// \param E The expression that is being checked for unexpanded
14579 /// parameter packs.
14580 ///
14581 /// \returns true if an error occurred, false otherwise.
14582 bool DiagnoseUnexpandedParameterPack(
14583 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14584
14585 /// If the given requirees-expression contains an unexpanded reference to one
14586 /// of its own parameter packs, diagnose the error.
14587 ///
14588 /// \param RE The requiress-expression that is being checked for unexpanded
14589 /// parameter packs.
14590 ///
14591 /// \returns true if an error occurred, false otherwise.
14592 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14593
14594 /// If the given nested-name-specifier contains an unexpanded
14595 /// parameter pack, diagnose the error.
14596 ///
14597 /// \param SS The nested-name-specifier that is being checked for
14598 /// unexpanded parameter packs.
14599 ///
14600 /// \returns true if an error occurred, false otherwise.
14601 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14602 UnexpandedParameterPackContext UPPC);
14603
14604 /// If the given name contains an unexpanded parameter pack,
14605 /// diagnose the error.
14606 ///
14607 /// \param NameInfo The name (with source location information) that
14608 /// is being checked for unexpanded parameter packs.
14609 ///
14610 /// \returns true if an error occurred, false otherwise.
14611 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14612 UnexpandedParameterPackContext UPPC);
14613
14614 /// If the given template name contains an unexpanded parameter pack,
14615 /// diagnose the error.
14616 ///
14617 /// \param Loc The location of the template name.
14618 ///
14619 /// \param Template The template name that is being checked for unexpanded
14620 /// parameter packs.
14621 ///
14622 /// \returns true if an error occurred, false otherwise.
14623 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14624 TemplateName Template,
14625 UnexpandedParameterPackContext UPPC);
14626
14627 /// If the given template argument contains an unexpanded parameter
14628 /// pack, diagnose the error.
14629 ///
14630 /// \param Arg The template argument that is being checked for unexpanded
14631 /// parameter packs.
14632 ///
14633 /// \returns true if an error occurred, false otherwise.
14634 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14635 UnexpandedParameterPackContext UPPC);
14636
14637 /// Collect the set of unexpanded parameter packs within the given
14638 /// template argument.
14639 ///
14640 /// \param Arg The template argument that will be traversed to find
14641 /// unexpanded parameter packs.
14642 void collectUnexpandedParameterPacks(
14643 TemplateArgument Arg,
14644 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14645
14646 /// Collect the set of unexpanded parameter packs within the given
14647 /// template argument.
14648 ///
14649 /// \param Arg The template argument that will be traversed to find
14650 /// unexpanded parameter packs.
14651 void collectUnexpandedParameterPacks(
14652 TemplateArgumentLoc Arg,
14653 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14654
14655 /// Collect the set of unexpanded parameter packs within the given
14656 /// type.
14657 ///
14658 /// \param T The type that will be traversed to find
14659 /// unexpanded parameter packs.
14660 void collectUnexpandedParameterPacks(
14661 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14662
14663 /// Collect the set of unexpanded parameter packs within the given
14664 /// type.
14665 ///
14666 /// \param TL The type that will be traversed to find
14667 /// unexpanded parameter packs.
14668 void collectUnexpandedParameterPacks(
14669 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14670
14671 /// Collect the set of unexpanded parameter packs within the given
14672 /// nested-name-specifier.
14673 ///
14674 /// \param NNS The nested-name-specifier that will be traversed to find
14675 /// unexpanded parameter packs.
14676 void collectUnexpandedParameterPacks(
14677 NestedNameSpecifierLoc NNS,
14678 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14679
14680 /// Collect the set of unexpanded parameter packs within the given
14681 /// name.
14682 ///
14683 /// \param NameInfo The name that will be traversed to find
14684 /// unexpanded parameter packs.
14685 void collectUnexpandedParameterPacks(
14686 const DeclarationNameInfo &NameInfo,
14687 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14688
14689 /// Collect the set of unexpanded parameter packs within the given
14690 /// expression.
14691 static void collectUnexpandedParameterPacks(
14692 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14693
14694 /// Invoked when parsing a template argument.
14695 ///
14696 /// \param Arg the template argument, which may already be invalid.
14697 ///
14698 /// If it is followed by ellipsis, this function is called before
14699 /// `ActOnPackExpansion`.
14700 ParsedTemplateArgument
14701 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14702
14703 /// Invoked when parsing a template argument followed by an
14704 /// ellipsis, which creates a pack expansion.
14705 ///
14706 /// \param Arg The template argument preceding the ellipsis, which
14707 /// may already be invalid.
14708 ///
14709 /// \param EllipsisLoc The location of the ellipsis.
14710 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14711 SourceLocation EllipsisLoc);
14712
14713 /// Invoked when parsing a type followed by an ellipsis, which
14714 /// creates a pack expansion.
14715 ///
14716 /// \param Type The type preceding the ellipsis, which will become
14717 /// the pattern of the pack expansion.
14718 ///
14719 /// \param EllipsisLoc The location of the ellipsis.
14720 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14721
14722 /// Construct a pack expansion type from the pattern of the pack
14723 /// expansion.
14724 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14725 SourceLocation EllipsisLoc,
14726 UnsignedOrNone NumExpansions);
14727
14728 /// Construct a pack expansion type from the pattern of the pack
14729 /// expansion.
14730 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14731 SourceLocation EllipsisLoc,
14732 UnsignedOrNone NumExpansions);
14733
14734 /// Invoked when parsing an expression followed by an ellipsis, which
14735 /// creates a pack expansion.
14736 ///
14737 /// \param Pattern The expression preceding the ellipsis, which will become
14738 /// the pattern of the pack expansion.
14739 ///
14740 /// \param EllipsisLoc The location of the ellipsis.
14741 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14742
14743 /// Invoked when parsing an expression followed by an ellipsis, which
14744 /// creates a pack expansion.
14745 ///
14746 /// \param Pattern The expression preceding the ellipsis, which will become
14747 /// the pattern of the pack expansion.
14748 ///
14749 /// \param EllipsisLoc The location of the ellipsis.
14750 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14751 UnsignedOrNone NumExpansions);
14752
14753 /// Determine whether we could expand a pack expansion with the
14754 /// given set of parameter packs into separate arguments by repeatedly
14755 /// transforming the pattern.
14756 ///
14757 /// \param EllipsisLoc The location of the ellipsis that identifies the
14758 /// pack expansion.
14759 ///
14760 /// \param PatternRange The source range that covers the entire pattern of
14761 /// the pack expansion.
14762 ///
14763 /// \param Unexpanded The set of unexpanded parameter packs within the
14764 /// pattern.
14765 ///
14766 /// \param ShouldExpand Will be set to \c true if the transformer should
14767 /// expand the corresponding pack expansions into separate arguments. When
14768 /// set, \c NumExpansions must also be set.
14769 ///
14770 /// \param RetainExpansion Whether the caller should add an unexpanded
14771 /// pack expansion after all of the expanded arguments. This is used
14772 /// when extending explicitly-specified template argument packs per
14773 /// C++0x [temp.arg.explicit]p9.
14774 ///
14775 /// \param NumExpansions The number of separate arguments that will be in
14776 /// the expanded form of the corresponding pack expansion. This is both an
14777 /// input and an output parameter, which can be set by the caller if the
14778 /// number of expansions is known a priori (e.g., due to a prior substitution)
14779 /// and will be set by the callee when the number of expansions is known.
14780 /// The callee must set this value when \c ShouldExpand is \c true; it may
14781 /// set this value in other cases.
14782 ///
14783 /// \returns true if an error occurred (e.g., because the parameter packs
14784 /// are to be instantiated with arguments of different lengths), false
14785 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14786 /// must be set.
14787 bool CheckParameterPacksForExpansion(
14788 SourceLocation EllipsisLoc, SourceRange PatternRange,
14789 ArrayRef<UnexpandedParameterPack> Unexpanded,
14790 const MultiLevelTemplateArgumentList &TemplateArgs,
14791 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14792 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14793 bool Diagnose = true);
14794
14795 /// Determine the number of arguments in the given pack expansion
14796 /// type.
14797 ///
14798 /// This routine assumes that the number of arguments in the expansion is
14799 /// consistent across all of the unexpanded parameter packs in its pattern.
14800 ///
14801 /// Returns an empty Optional if the type can't be expanded.
14802 UnsignedOrNone getNumArgumentsInExpansion(
14803 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14804
14805 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14806 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14807 const MultiLevelTemplateArgumentList &TemplateArgs);
14808
14809 /// Determine whether the given declarator contains any unexpanded
14810 /// parameter packs.
14811 ///
14812 /// This routine is used by the parser to disambiguate function declarators
14813 /// with an ellipsis prior to the ')', e.g.,
14814 ///
14815 /// \code
14816 /// void f(T...);
14817 /// \endcode
14818 ///
14819 /// To determine whether we have an (unnamed) function parameter pack or
14820 /// a variadic function.
14821 ///
14822 /// \returns true if the declarator contains any unexpanded parameter packs,
14823 /// false otherwise.
14824 bool containsUnexpandedParameterPacks(Declarator &D);
14825
14826 /// Returns the pattern of the pack expansion for a template argument.
14827 ///
14828 /// \param OrigLoc The template argument to expand.
14829 ///
14830 /// \param Ellipsis Will be set to the location of the ellipsis.
14831 ///
14832 /// \param NumExpansions Will be set to the number of expansions that will
14833 /// be generated from this pack expansion, if known a priori.
14834 TemplateArgumentLoc
14835 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14836 SourceLocation &Ellipsis,
14837 UnsignedOrNone &NumExpansions) const;
14838
14839 /// Given a template argument that contains an unexpanded parameter pack, but
14840 /// which has already been substituted, attempt to determine the number of
14841 /// elements that will be produced once this argument is fully-expanded.
14842 ///
14843 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14844 /// avoid actually expanding the pack where possible.
14845 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14846
14847 /// Called when an expression computing the size of a parameter pack
14848 /// is parsed.
14849 ///
14850 /// \code
14851 /// template<typename ...Types> struct count {
14852 /// static const unsigned value = sizeof...(Types);
14853 /// };
14854 /// \endcode
14855 ///
14856 //
14857 /// \param OpLoc The location of the "sizeof" keyword.
14858 /// \param Name The name of the parameter pack whose size will be determined.
14859 /// \param NameLoc The source location of the name of the parameter pack.
14860 /// \param RParenLoc The location of the closing parentheses.
14861 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14862 IdentifierInfo &Name,
14863 SourceLocation NameLoc,
14864 SourceLocation RParenLoc);
14865
14866 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14867 SourceLocation EllipsisLoc,
14868 SourceLocation LSquareLoc, Expr *IndexExpr,
14869 SourceLocation RSquareLoc);
14870
14871 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14872 SourceLocation EllipsisLoc, Expr *IndexExpr,
14873 SourceLocation RSquareLoc,
14874 ArrayRef<Expr *> ExpandedExprs = {},
14875 bool FullySubstituted = false);
14876
14877 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14878 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14879 tok::TokenKind Operator,
14880 SourceLocation EllipsisLoc, Expr *RHS,
14881 SourceLocation RParenLoc);
14882 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14883 SourceLocation LParenLoc, Expr *LHS,
14884 BinaryOperatorKind Operator,
14885 SourceLocation EllipsisLoc, Expr *RHS,
14886 SourceLocation RParenLoc,
14887 UnsignedOrNone NumExpansions);
14888 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14889 BinaryOperatorKind Operator);
14890
14891 ///@}
14892
14893 //
14894 //
14895 // -------------------------------------------------------------------------
14896 //
14897 //
14898
14899 /// \name Constraints and Concepts
14900 /// Implementations are in SemaConcept.cpp
14901 ///@{
14902
14903public:
14904 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14905
14906 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14907 TypeSourceInfo *TSI);
14908
14909public:
14910 void PushSatisfactionStackEntry(const NamedDecl *D,
14911 const llvm::FoldingSetNodeID &ID) {
14912 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14913 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
14914 }
14915
14916 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14917
14918 bool SatisfactionStackContains(const NamedDecl *D,
14919 const llvm::FoldingSetNodeID &ID) const {
14920 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14921 return llvm::is_contained(Range: SatisfactionStack,
14922 Element: SatisfactionStackEntryTy{Can, ID});
14923 }
14924
14925 using SatisfactionStackEntryTy =
14926 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14927
14928 // Resets the current SatisfactionStack for cases where we are instantiating
14929 // constraints as a 'side effect' of normal instantiation in a way that is not
14930 // indicative of recursive definition.
14931 class SatisfactionStackResetRAII {
14932 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
14933 Sema &SemaRef;
14934
14935 public:
14936 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
14937 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14938 }
14939
14940 ~SatisfactionStackResetRAII() {
14941 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14942 }
14943
14944 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
14945 SatisfactionStackResetRAII &
14946 operator=(const SatisfactionStackResetRAII &) = delete;
14947 };
14948
14949 void SwapSatisfactionStack(
14950 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
14951 SatisfactionStack.swap(RHS&: NewSS);
14952 }
14953
14954 using ConstrainedDeclOrNestedRequirement =
14955 llvm::PointerUnion<const NamedDecl *,
14956 const concepts::NestedRequirement *>;
14957
14958 /// Check whether the given expression is a valid constraint expression.
14959 /// A diagnostic is emitted if it is not, false is returned, and
14960 /// PossibleNonPrimary will be set to true if the failure might be due to a
14961 /// non-primary expression being used as an atomic constraint.
14962 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
14963 bool *PossibleNonPrimary = nullptr,
14964 bool IsTrailingRequiresClause = false);
14965
14966 /// \brief Check whether the given list of constraint expressions are
14967 /// satisfied (as if in a 'conjunction') given template arguments.
14968 /// \param Template the template-like entity that triggered the constraints
14969 /// check (either a concept or a constrained entity).
14970 /// \param ConstraintExprs a list of constraint expressions, treated as if
14971 /// they were 'AND'ed together.
14972 /// \param TemplateArgLists the list of template arguments to substitute into
14973 /// the constraint expression.
14974 /// \param TemplateIDRange The source range of the template id that
14975 /// caused the constraints check.
14976 /// \param Satisfaction if true is returned, will contain details of the
14977 /// satisfaction, with enough information to diagnose an unsatisfied
14978 /// expression.
14979 /// \returns true if an error occurred and satisfaction could not be checked,
14980 /// false otherwise.
14981 bool CheckConstraintSatisfaction(
14982 ConstrainedDeclOrNestedRequirement Entity,
14983 ArrayRef<AssociatedConstraint> AssociatedConstraints,
14984 const MultiLevelTemplateArgumentList &TemplateArgLists,
14985 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
14986 const ConceptReference *TopLevelConceptId = nullptr,
14987 Expr **ConvertedExpr = nullptr);
14988
14989 /// Check whether the given function decl's trailing requires clause is
14990 /// satisfied, if any. Returns false and updates Satisfaction with the
14991 /// satisfaction verdict if successful, emits a diagnostic and returns true if
14992 /// an error occurred and satisfaction could not be determined.
14993 ///
14994 /// \returns true if an error occurred, false otherwise.
14995 bool CheckFunctionConstraints(const FunctionDecl *FD,
14996 ConstraintSatisfaction &Satisfaction,
14997 SourceLocation UsageLoc = SourceLocation(),
14998 bool ForOverloadResolution = false);
14999
15000 // Calculates whether two constraint expressions are equal irrespective of a
15001 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15002 // 'New', which are the "source" of the constraint, since this is necessary
15003 // for figuring out the relative 'depth' of the constraint. The depth of the
15004 // 'primary template' and the 'instantiated from' templates aren't necessarily
15005 // the same, such as a case when one is a 'friend' defined in a class.
15006 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15007 const Expr *OldConstr,
15008 const TemplateCompareNewDeclInfo &New,
15009 const Expr *NewConstr);
15010
15011 // Calculates whether the friend function depends on an enclosing template for
15012 // the purposes of [temp.friend] p9.
15013 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15014
15015 /// \brief Ensure that the given template arguments satisfy the constraints
15016 /// associated with the given template, emitting a diagnostic if they do not.
15017 ///
15018 /// \param Template The template to which the template arguments are being
15019 /// provided.
15020 ///
15021 /// \param TemplateArgs The converted, canonicalized template arguments.
15022 ///
15023 /// \param TemplateIDRange The source range of the template id that
15024 /// caused the constraints check.
15025 ///
15026 /// \returns true if the constrains are not satisfied or could not be checked
15027 /// for satisfaction, false if the constraints are satisfied.
15028 bool EnsureTemplateArgumentListConstraints(
15029 TemplateDecl *Template,
15030 const MultiLevelTemplateArgumentList &TemplateArgs,
15031 SourceRange TemplateIDRange);
15032
15033 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15034 FunctionDecl *Decl,
15035 ArrayRef<TemplateArgument> TemplateArgs,
15036 ConstraintSatisfaction &Satisfaction);
15037
15038 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15039 /// unsatisfied.
15040 /// \param First whether this is the first time an unsatisfied constraint is
15041 /// diagnosed for this error.
15042 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15043 SourceLocation Loc = {},
15044 bool First = true);
15045
15046 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15047 /// unsatisfied.
15048 void
15049 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15050 bool First = true);
15051
15052 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15053 ConstrainedDeclOrNestedRequirement Entity,
15054 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15055
15056 /// \brief Check whether the given declaration's associated constraints are
15057 /// at least as constrained than another declaration's according to the
15058 /// partial ordering of constraints.
15059 ///
15060 /// \param Result If no error occurred, receives the result of true if D1 is
15061 /// at least constrained than D2, and false otherwise.
15062 ///
15063 /// \returns true if an error occurred, false otherwise.
15064 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15065 MutableArrayRef<AssociatedConstraint> AC1,
15066 const NamedDecl *D2,
15067 MutableArrayRef<AssociatedConstraint> AC2,
15068 bool &Result);
15069
15070 /// If D1 was not at least as constrained as D2, but would've been if a pair
15071 /// of atomic constraints involved had been declared in a concept and not
15072 /// repeated in two separate places in code.
15073 /// \returns true if such a diagnostic was emitted, false otherwise.
15074 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15075 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15076 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15077
15078 /// Cache the satisfaction of an atomic constraint.
15079 /// The key is based on the unsubstituted expression and the parameter
15080 /// mapping. This lets us not substituting the mapping more than once,
15081 /// which is (very!) expensive.
15082 /// FIXME: this should be private.
15083 llvm::DenseMap<llvm::FoldingSetNodeID,
15084 UnsubstitutedConstraintSatisfactionCacheResult>
15085 UnsubstitutedConstraintSatisfactionCache;
15086
15087private:
15088 /// Caches pairs of template-like decls whose associated constraints were
15089 /// checked for subsumption and whether or not the first's constraints did in
15090 /// fact subsume the second's.
15091 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15092 SubsumptionCache;
15093 /// Caches the normalized associated constraints of declarations (concepts or
15094 /// constrained declarations). If an error occurred while normalizing the
15095 /// associated constraints of the template or concept, nullptr will be cached
15096 /// here.
15097 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15098 NormalizationCache;
15099
15100 /// Cache whether the associated constraint of a declaration
15101 /// is satisfied.
15102 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15103 SatisfactionCache;
15104
15105 // The current stack of constraint satisfactions, so we can exit-early.
15106 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15107
15108 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15109 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15110 /// use LambdaScopeForCallOperatorInstantiationRAII.
15111 bool
15112 SetupConstraintScope(FunctionDecl *FD,
15113 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15114 const MultiLevelTemplateArgumentList &MLTAL,
15115 LocalInstantiationScope &Scope);
15116
15117 /// Used during constraint checking, sets up the constraint template argument
15118 /// lists, and calls SetupConstraintScope to set up the
15119 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15120 std::optional<MultiLevelTemplateArgumentList>
15121 SetupConstraintCheckingTemplateArgumentsAndScope(
15122 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15123 LocalInstantiationScope &Scope);
15124
15125 ///@}
15126
15127 //
15128 //
15129 // -------------------------------------------------------------------------
15130 //
15131 //
15132
15133 /// \name Types
15134 /// Implementations are in SemaType.cpp
15135 ///@{
15136
15137public:
15138 /// A mapping that describes the nullability we've seen in each header file.
15139 FileNullabilityMap NullabilityMap;
15140
15141 static int getPrintable(int I) { return I; }
15142 static unsigned getPrintable(unsigned I) { return I; }
15143 static bool getPrintable(bool B) { return B; }
15144 static const char *getPrintable(const char *S) { return S; }
15145 static StringRef getPrintable(StringRef S) { return S; }
15146 static const std::string &getPrintable(const std::string &S) { return S; }
15147 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15148 return II;
15149 }
15150 static DeclarationName getPrintable(DeclarationName N) { return N; }
15151 static QualType getPrintable(QualType T) { return T; }
15152 static SourceRange getPrintable(SourceRange R) { return R; }
15153 static SourceRange getPrintable(SourceLocation L) { return L; }
15154 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15155 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15156
15157 enum class CompleteTypeKind {
15158 /// Apply the normal rules for complete types. In particular,
15159 /// treat all sizeless types as incomplete.
15160 Normal,
15161
15162 /// Relax the normal rules for complete types so that they include
15163 /// sizeless built-in types.
15164 AcceptSizeless,
15165
15166 // FIXME: Eventually we should flip the default to Normal and opt in
15167 // to AcceptSizeless rather than opt out of it.
15168 Default = AcceptSizeless
15169 };
15170
15171 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15172 const DeclSpec *DS = nullptr);
15173 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15174 const DeclSpec *DS = nullptr);
15175
15176 /// Build a pointer type.
15177 ///
15178 /// \param T The type to which we'll be building a pointer.
15179 ///
15180 /// \param Loc The location of the entity whose type involves this
15181 /// pointer type or, if there is no such entity, the location of the
15182 /// type that will have pointer type.
15183 ///
15184 /// \param Entity The name of the entity that involves the pointer
15185 /// type, if known.
15186 ///
15187 /// \returns A suitable pointer type, if there are no
15188 /// errors. Otherwise, returns a NULL type.
15189 QualType BuildPointerType(QualType T, SourceLocation Loc,
15190 DeclarationName Entity);
15191
15192 /// Build a reference type.
15193 ///
15194 /// \param T The type to which we'll be building a reference.
15195 ///
15196 /// \param Loc The location of the entity whose type involves this
15197 /// reference type or, if there is no such entity, the location of the
15198 /// type that will have reference type.
15199 ///
15200 /// \param Entity The name of the entity that involves the reference
15201 /// type, if known.
15202 ///
15203 /// \returns A suitable reference type, if there are no
15204 /// errors. Otherwise, returns a NULL type.
15205 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15206 DeclarationName Entity);
15207
15208 /// Build an array type.
15209 ///
15210 /// \param T The type of each element in the array.
15211 ///
15212 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15213 ///
15214 /// \param ArraySize Expression describing the size of the array.
15215 ///
15216 /// \param Brackets The range from the opening '[' to the closing ']'.
15217 ///
15218 /// \param Entity The name of the entity that involves the array
15219 /// type, if known.
15220 ///
15221 /// \returns A suitable array type, if there are no errors. Otherwise,
15222 /// returns a NULL type.
15223 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15224 unsigned Quals, SourceRange Brackets,
15225 DeclarationName Entity);
15226 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15227
15228 /// Build an ext-vector type.
15229 ///
15230 /// Run the required checks for the extended vector type.
15231 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15232 SourceLocation AttrLoc);
15233 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15234 SourceLocation AttrLoc);
15235
15236 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15237 Expr *CountExpr,
15238 bool CountInBytes,
15239 bool OrNull);
15240
15241 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15242 /// expression is uninstantiated. If instantiated it will apply the
15243 /// appropriate address space to the type. This function allows dependent
15244 /// template variables to be used in conjunction with the address_space
15245 /// attribute
15246 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15247 SourceLocation AttrLoc);
15248
15249 /// Same as above, but constructs the AddressSpace index if not provided.
15250 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15251 SourceLocation AttrLoc);
15252
15253 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15254
15255 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15256
15257 /// Build a function type.
15258 ///
15259 /// This routine checks the function type according to C++ rules and
15260 /// under the assumption that the result type and parameter types have
15261 /// just been instantiated from a template. It therefore duplicates
15262 /// some of the behavior of GetTypeForDeclarator, but in a much
15263 /// simpler form that is only suitable for this narrow use case.
15264 ///
15265 /// \param T The return type of the function.
15266 ///
15267 /// \param ParamTypes The parameter types of the function. This array
15268 /// will be modified to account for adjustments to the types of the
15269 /// function parameters.
15270 ///
15271 /// \param Loc The location of the entity whose type involves this
15272 /// function type or, if there is no such entity, the location of the
15273 /// type that will have function type.
15274 ///
15275 /// \param Entity The name of the entity that involves the function
15276 /// type, if known.
15277 ///
15278 /// \param EPI Extra information about the function type. Usually this will
15279 /// be taken from an existing function with the same prototype.
15280 ///
15281 /// \returns A suitable function type, if there are no errors. The
15282 /// unqualified type will always be a FunctionProtoType.
15283 /// Otherwise, returns a NULL type.
15284 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15285 SourceLocation Loc, DeclarationName Entity,
15286 const FunctionProtoType::ExtProtoInfo &EPI);
15287
15288 /// Build a member pointer type \c T Class::*.
15289 ///
15290 /// \param T the type to which the member pointer refers.
15291 /// \param Class the class type into which the member pointer points.
15292 /// \param Loc the location where this type begins
15293 /// \param Entity the name of the entity that will have this member pointer
15294 /// type
15295 ///
15296 /// \returns a member pointer type, if successful, or a NULL type if there was
15297 /// an error.
15298 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15299 CXXRecordDecl *Cls, SourceLocation Loc,
15300 DeclarationName Entity);
15301
15302 /// Build a block pointer type.
15303 ///
15304 /// \param T The type to which we'll be building a block pointer.
15305 ///
15306 /// \param Loc The source location, used for diagnostics.
15307 ///
15308 /// \param Entity The name of the entity that involves the block pointer
15309 /// type, if known.
15310 ///
15311 /// \returns A suitable block pointer type, if there are no
15312 /// errors. Otherwise, returns a NULL type.
15313 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15314 DeclarationName Entity);
15315
15316 /// Build a paren type including \p T.
15317 QualType BuildParenType(QualType T);
15318 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15319
15320 /// Build a Read-only Pipe type.
15321 ///
15322 /// \param T The type to which we'll be building a Pipe.
15323 ///
15324 /// \param Loc We do not use it for now.
15325 ///
15326 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15327 /// a NULL type.
15328 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15329
15330 /// Build a Write-only Pipe type.
15331 ///
15332 /// \param T The type to which we'll be building a Pipe.
15333 ///
15334 /// \param Loc We do not use it for now.
15335 ///
15336 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15337 /// a NULL type.
15338 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15339
15340 /// Build a bit-precise integer type.
15341 ///
15342 /// \param IsUnsigned Boolean representing the signedness of the type.
15343 ///
15344 /// \param BitWidth Size of this int type in bits, or an expression
15345 /// representing that.
15346 ///
15347 /// \param Loc Location of the keyword.
15348 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15349
15350 /// GetTypeForDeclarator - Convert the type for the specified
15351 /// declarator to Type instances.
15352 ///
15353 /// The result of this call will never be null, but the associated
15354 /// type may be a null type if there's an unrecoverable error.
15355 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15356 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15357
15358 /// Package the given type and TSI into a ParsedType.
15359 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15360 static QualType GetTypeFromParser(ParsedType Ty,
15361 TypeSourceInfo **TInfo = nullptr);
15362
15363 TypeResult ActOnTypeName(Declarator &D);
15364
15365 // Check whether the size of array element of type \p EltTy is a multiple of
15366 // its alignment and return false if it isn't.
15367 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15368
15369 void
15370 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15371 SourceLocation FallbackLoc,
15372 SourceLocation ConstQualLoc = SourceLocation(),
15373 SourceLocation VolatileQualLoc = SourceLocation(),
15374 SourceLocation RestrictQualLoc = SourceLocation(),
15375 SourceLocation AtomicQualLoc = SourceLocation(),
15376 SourceLocation UnalignedQualLoc = SourceLocation());
15377
15378 /// Retrieve the keyword associated
15379 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15380
15381 /// Adjust the calling convention of a method to be the ABI default if it
15382 /// wasn't specified explicitly. This handles method types formed from
15383 /// function type typedefs and typename template arguments.
15384 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15385 bool IsCtorOrDtor, SourceLocation Loc);
15386
15387 // Check if there is an explicit attribute, but only look through parens.
15388 // The intent is to look for an attribute on the current declarator, but not
15389 // one that came from a typedef.
15390 bool hasExplicitCallingConv(QualType T);
15391
15392 /// Check whether a nullability type specifier can be added to the given
15393 /// type through some means not written in source (e.g. API notes).
15394 ///
15395 /// \param Type The type to which the nullability specifier will be
15396 /// added. On success, this type will be updated appropriately.
15397 ///
15398 /// \param Nullability The nullability specifier to add.
15399 ///
15400 /// \param DiagLoc The location to use for diagnostics.
15401 ///
15402 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15403 /// array type (e.g., because it will decay to a pointer).
15404 ///
15405 /// \param OverrideExisting Whether to override an existing, locally-specified
15406 /// nullability specifier rather than complaining about the conflict.
15407 ///
15408 /// \returns true if nullability cannot be applied, false otherwise.
15409 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15410 NullabilityKind Nullability,
15411 SourceLocation DiagLoc,
15412 bool AllowArrayTypes,
15413 bool OverrideExisting);
15414
15415 /// Check whether the given variable declaration has a size that fits within
15416 /// the address space it is declared in. This issues a diagnostic if not.
15417 ///
15418 /// \param VD The variable declaration to check the size of.
15419 ///
15420 /// \param AS The address space to check the size of \p VD against.
15421 ///
15422 /// \returns true if the variable's size fits within the address space, false
15423 /// otherwise.
15424 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15425
15426 /// Get the type of expression E, triggering instantiation to complete the
15427 /// type if necessary -- that is, if the expression refers to a templated
15428 /// static data member of incomplete array type.
15429 ///
15430 /// May still return an incomplete type if instantiation was not possible or
15431 /// if the type is incomplete for a different reason. Use
15432 /// RequireCompleteExprType instead if a diagnostic is expected for an
15433 /// incomplete expression type.
15434 QualType getCompletedType(Expr *E);
15435
15436 void completeExprArrayBound(Expr *E);
15437
15438 /// Ensure that the type of the given expression is complete.
15439 ///
15440 /// This routine checks whether the expression \p E has a complete type. If
15441 /// the expression refers to an instantiable construct, that instantiation is
15442 /// performed as needed to complete its type. Furthermore
15443 /// Sema::RequireCompleteType is called for the expression's type (or in the
15444 /// case of a reference type, the referred-to type).
15445 ///
15446 /// \param E The expression whose type is required to be complete.
15447 /// \param Kind Selects which completeness rules should be applied.
15448 /// \param Diagnoser The object that will emit a diagnostic if the type is
15449 /// incomplete.
15450 ///
15451 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15452 /// otherwise.
15453 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15454 TypeDiagnoser &Diagnoser);
15455 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15456
15457 template <typename... Ts>
15458 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15459 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15460 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15461 }
15462
15463 // Returns the underlying type of a decltype with the given expression.
15464 QualType getDecltypeForExpr(Expr *E);
15465
15466 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15467 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15468 /// context, such as when building a type for decltype(auto).
15469 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15470
15471 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15472 SourceLocation Loc,
15473 SourceLocation EllipsisLoc);
15474 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15475 SourceLocation Loc, SourceLocation EllipsisLoc,
15476 bool FullySubstituted = false,
15477 ArrayRef<QualType> Expansions = {});
15478
15479 using UTTKind = UnaryTransformType::UTTKind;
15480 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15481 SourceLocation Loc);
15482 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15483 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15484 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15485 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15486 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15487 SourceLocation Loc);
15488 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15489 SourceLocation Loc);
15490 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15491 SourceLocation Loc);
15492
15493 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15494 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15495 }
15496
15497 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15498 SourceLocation Loc);
15499 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15500 SourceLocation Loc);
15501
15502 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15503
15504 /// Ensure that the type T is a literal type.
15505 ///
15506 /// This routine checks whether the type @p T is a literal type. If @p T is an
15507 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15508 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15509 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15510 /// it the type @p T), along with notes explaining why the type is not a
15511 /// literal type, and returns true.
15512 ///
15513 /// @param Loc The location in the source that the non-literal type
15514 /// diagnostic should refer to.
15515 ///
15516 /// @param T The type that this routine is examining for literalness.
15517 ///
15518 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15519 ///
15520 /// @returns @c true if @p T is not a literal type and a diagnostic was
15521 /// emitted, @c false otherwise.
15522 bool RequireLiteralType(SourceLocation Loc, QualType T,
15523 TypeDiagnoser &Diagnoser);
15524 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15525
15526 template <typename... Ts>
15527 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15528 const Ts &...Args) {
15529 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15530 return RequireLiteralType(Loc, T, Diagnoser);
15531 }
15532
15533 bool isCompleteType(SourceLocation Loc, QualType T,
15534 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15535 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15536 }
15537
15538 /// Ensure that the type T is a complete type.
15539 ///
15540 /// This routine checks whether the type @p T is complete in any
15541 /// context where a complete type is required. If @p T is a complete
15542 /// type, returns false. If @p T is a class template specialization,
15543 /// this routine then attempts to perform class template
15544 /// instantiation. If instantiation fails, or if @p T is incomplete
15545 /// and cannot be completed, issues the diagnostic @p diag (giving it
15546 /// the type @p T) and returns true.
15547 ///
15548 /// @param Loc The location in the source that the incomplete type
15549 /// diagnostic should refer to.
15550 ///
15551 /// @param T The type that this routine is examining for completeness.
15552 ///
15553 /// @param Kind Selects which completeness rules should be applied.
15554 ///
15555 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15556 /// @c false otherwise.
15557 bool RequireCompleteType(SourceLocation Loc, QualType T,
15558 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15559 bool RequireCompleteType(SourceLocation Loc, QualType T,
15560 CompleteTypeKind Kind, unsigned DiagID);
15561
15562 bool RequireCompleteType(SourceLocation Loc, QualType T,
15563 TypeDiagnoser &Diagnoser) {
15564 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15565 }
15566 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15567 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15568 }
15569
15570 template <typename... Ts>
15571 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15572 const Ts &...Args) {
15573 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15574 return RequireCompleteType(Loc, T, Diagnoser);
15575 }
15576
15577 /// Determine whether a declaration is visible to name lookup.
15578 bool isVisible(const NamedDecl *D) {
15579 return D->isUnconditionallyVisible() ||
15580 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15581 }
15582
15583 /// Determine whether a declaration is reachable.
15584 bool isReachable(const NamedDecl *D) {
15585 // All visible declarations are reachable.
15586 return D->isUnconditionallyVisible() ||
15587 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15588 }
15589
15590 /// Determine whether a declaration is acceptable (visible/reachable).
15591 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15592 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15593 }
15594
15595 /// Determine if \p D and \p Suggested have a structurally compatible
15596 /// layout as described in C11 6.2.7/1.
15597 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15598
15599 /// Determine if \p D has a visible definition. If not, suggest a declaration
15600 /// that should be made visible to expose the definition.
15601 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15602 bool OnlyNeedComplete = false);
15603 bool hasVisibleDefinition(const NamedDecl *D) {
15604 NamedDecl *Hidden;
15605 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15606 }
15607 /// Determine if \p D has a definition which allows we redefine it in current
15608 /// TU. \p Suggested is the definition that should be made visible to expose
15609 /// the definition.
15610 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15611 bool &Visible);
15612 bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible) {
15613 NamedDecl *Hidden;
15614 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), Suggested: &Hidden,
15615 Visible);
15616 }
15617
15618 /// Determine if \p D has a reachable definition. If not, suggest a
15619 /// declaration that should be made reachable to expose the definition.
15620 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15621 bool OnlyNeedComplete = false);
15622 bool hasReachableDefinition(NamedDecl *D) {
15623 NamedDecl *Hidden;
15624 return hasReachableDefinition(D, Suggested: &Hidden);
15625 }
15626
15627 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15628 AcceptableKind Kind,
15629 bool OnlyNeedComplete = false);
15630 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15631 NamedDecl *Hidden;
15632 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15633 }
15634
15635 /// Try to parse the conditional expression attached to an effect attribute
15636 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15637 /// optional on error.
15638 std::optional<FunctionEffectMode>
15639 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15640
15641 void ActOnCleanupAttr(Decl *D, const Attr *A);
15642 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15643
15644private:
15645 /// The implementation of RequireCompleteType
15646 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15647 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15648
15649 /// Nullability type specifiers.
15650 IdentifierInfo *Ident__Nonnull = nullptr;
15651 IdentifierInfo *Ident__Nullable = nullptr;
15652 IdentifierInfo *Ident__Nullable_result = nullptr;
15653 IdentifierInfo *Ident__Null_unspecified = nullptr;
15654
15655 ///@}
15656
15657 //
15658 //
15659 // -------------------------------------------------------------------------
15660 //
15661 //
15662
15663 /// \name FixIt Helpers
15664 /// Implementations are in SemaFixItUtils.cpp
15665 ///@{
15666
15667public:
15668 /// Get a string to suggest for zero-initialization of a type.
15669 std::string getFixItZeroInitializerForType(QualType T,
15670 SourceLocation Loc) const;
15671 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15672
15673 ///@}
15674
15675 //
15676 //
15677 // -------------------------------------------------------------------------
15678 //
15679 //
15680
15681 /// \name Function Effects
15682 /// Implementations are in SemaFunctionEffects.cpp
15683 ///@{
15684public:
15685 struct FunctionEffectDiff {
15686 enum class Kind { Added, Removed, ConditionMismatch };
15687
15688 FunctionEffect::Kind EffectKind;
15689 Kind DiffKind;
15690 std::optional<FunctionEffectWithCondition>
15691 Old; // Invalid when 'Kind' is 'Added'.
15692 std::optional<FunctionEffectWithCondition>
15693 New; // Invalid when 'Kind' is 'Removed'.
15694
15695 StringRef effectName() const {
15696 if (Old)
15697 return Old.value().Effect.name();
15698 return New.value().Effect.name();
15699 }
15700
15701 /// Describes the result of effects differing between a base class's virtual
15702 /// method and an overriding method in a subclass.
15703 enum class OverrideResult {
15704 NoAction,
15705 Warn,
15706 Merge // Merge missing effect from base to derived.
15707 };
15708
15709 /// Return true if adding or removing the effect as part of a type
15710 /// conversion should generate a diagnostic.
15711 bool shouldDiagnoseConversion(QualType SrcType,
15712 const FunctionEffectsRef &SrcFX,
15713 QualType DstType,
15714 const FunctionEffectsRef &DstFX) const;
15715
15716 /// Return true if adding or removing the effect in a redeclaration should
15717 /// generate a diagnostic.
15718 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15719 const FunctionEffectsRef &OldFX,
15720 const FunctionDecl &NewFunction,
15721 const FunctionEffectsRef &NewFX) const;
15722
15723 /// Return true if adding or removing the effect in a C++ virtual method
15724 /// override should generate a diagnostic.
15725 OverrideResult shouldDiagnoseMethodOverride(
15726 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15727 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15728 };
15729
15730 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15731 /// Caller should short-circuit by checking for equality first.
15732 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15733 const FunctionEffectsRef &New);
15734 };
15735
15736 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15737 /// FunctionEffectsRef to be verified.
15738 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15739
15740 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15741 /// are all null.
15742 FunctionEffectKindSet AllEffectsToVerify;
15743
15744public:
15745 /// Warn and return true if adding a function effect to a set would create a
15746 /// conflict.
15747 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15748 const FunctionEffectWithCondition &EC,
15749 SourceLocation NewAttrLoc);
15750
15751 // Report a failure to merge function effects between declarations due to a
15752 // conflict.
15753 void
15754 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15755 SourceLocation NewLoc,
15756 SourceLocation OldLoc);
15757
15758 /// Inline checks from the start of maybeAddDeclWithEffects, to
15759 /// minimize performance impact on code not using effects.
15760 template <class FuncOrBlockDecl>
15761 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15762 if (Context.hasAnyFunctionEffects())
15763 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15764 maybeAddDeclWithEffects(D, FX);
15765 }
15766
15767 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15768 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15769
15770 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15771 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15772
15773 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15774
15775 ///@}
15776};
15777
15778DeductionFailureInfo
15779MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15780 sema::TemplateDeductionInfo &Info);
15781
15782/// Contains a late templated function.
15783/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15784struct LateParsedTemplate {
15785 CachedTokens Toks;
15786 /// The template function declaration to be late parsed.
15787 Decl *D;
15788 /// Floating-point options in the point of definition.
15789 FPOptions FPO;
15790};
15791
15792template <>
15793void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15794 PragmaMsStackAction Action,
15795 llvm::StringRef StackSlotLabel,
15796 AlignPackInfo Value);
15797
15798} // end namespace clang
15799
15800#endif
15801