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 PackIndex ///< Index of a pack indexing expression or specifier.
852};
853
854/// Enums for the diagnostics of target, target_version and target_clones.
855namespace DiagAttrParams {
856enum DiagType { Unsupported, Duplicate, Unknown };
857enum Specifier { None, CPU, Tune };
858enum AttrName { Target, TargetClones, TargetVersion };
859} // end namespace DiagAttrParams
860
861void inferNoReturnAttr(Sema &S, Decl *D);
862
863#ifdef __GNUC__
864#pragma GCC diagnostic push
865#pragma GCC diagnostic ignored "-Wattributes"
866#endif
867/// Sema - This implements semantic analysis and AST building for C.
868/// \nosubgrouping
869class Sema final : public SemaBase {
870#ifdef __GNUC__
871#pragma GCC diagnostic pop
872#endif
873 // Table of Contents
874 // -----------------
875 // 1. Semantic Analysis (Sema.cpp)
876 // 2. API Notes (SemaAPINotes.cpp)
877 // 3. C++ Access Control (SemaAccess.cpp)
878 // 4. Attributes (SemaAttr.cpp)
879 // 5. Availability Attribute Handling (SemaAvailability.cpp)
880 // 6. Bounds Safety (SemaBoundsSafety.cpp)
881 // 7. Casts (SemaCast.cpp)
882 // 8. Extra Semantic Checking (SemaChecking.cpp)
883 // 9. C++ Coroutines (SemaCoroutine.cpp)
884 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp)
885 // 11. Declarations (SemaDecl.cpp)
886 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp)
887 // 13. C++ Declarations (SemaDeclCXX.cpp)
888 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp)
889 // 15. Expressions (SemaExpr.cpp)
890 // 16. C++ Expressions (SemaExprCXX.cpp)
891 // 17. Member Access Expressions (SemaExprMember.cpp)
892 // 18. Initializers (SemaInit.cpp)
893 // 19. C++ Lambda Expressions (SemaLambda.cpp)
894 // 20. Name Lookup (SemaLookup.cpp)
895 // 21. Modules (SemaModule.cpp)
896 // 22. C++ Overloading (SemaOverload.cpp)
897 // 23. Statements (SemaStmt.cpp)
898 // 24. `inline asm` Statement (SemaStmtAsm.cpp)
899 // 25. Statement Attribute Handling (SemaStmtAttr.cpp)
900 // 26. C++ Templates (SemaTemplate.cpp)
901 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp)
902 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp)
903 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp)
904 // 30. C++ Template Declaration Instantiation
905 // (SemaTemplateInstantiateDecl.cpp)
906 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp)
907 // 32. Constraints and Concepts (SemaConcept.cpp)
908 // 33. Types (SemaType.cpp)
909 // 34. FixIt Helpers (SemaFixItUtils.cpp)
910 // 35. Function Effects (SemaFunctionEffects.cpp)
911
912 /// \name Semantic Analysis
913 /// Implementations are in Sema.cpp
914 ///@{
915
916public:
917 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
918 TranslationUnitKind TUKind = TU_Complete,
919 CodeCompleteConsumer *CompletionConsumer = nullptr);
920 ~Sema();
921
922 /// Perform initialization that occurs after the parser has been
923 /// initialized but before it parses anything.
924 void Initialize();
925
926 /// This virtual key function only exists to limit the emission of debug info
927 /// describing the Sema class. GCC and Clang only emit debug info for a class
928 /// with a vtable when the vtable is emitted. Sema is final and not
929 /// polymorphic, but the debug info size savings are so significant that it is
930 /// worth adding a vtable just to take advantage of this optimization.
931 LLVM_DECLARE_VIRTUAL_ANCHOR_FUNCTION();
932
933 const LangOptions &getLangOpts() const { return LangOpts; }
934 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
935 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
936
937 DiagnosticsEngine &getDiagnostics() const { return Diags; }
938 SourceManager &getSourceManager() const { return SourceMgr; }
939 Preprocessor &getPreprocessor() const { return PP; }
940 ASTContext &getASTContext() const { return Context; }
941 ASTConsumer &getASTConsumer() const { return Consumer; }
942 ASTMutationListener *getASTMutationListener() const;
943 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
944
945 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
946 StringRef Platform);
947 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
948
949 /// Registers an external source. If an external source already exists,
950 /// creates a multiplex external source and appends to it.
951 ///
952 ///\param[in] E - A non-null external sema source.
953 ///
954 void addExternalSource(IntrusiveRefCntPtr<ExternalSemaSource> E);
955
956 /// Print out statistics about the semantic analysis.
957 void PrintStats() const;
958
959 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
960 /// guaranteed). Produces a warning if we're low on stack space and allocates
961 /// more in that case. Use this in code that may recurse deeply (for example,
962 /// in template instantiation) to avoid stack overflow.
963 void runWithSufficientStackSpace(SourceLocation Loc,
964 llvm::function_ref<void()> Fn);
965
966 /// Returns default addr space for method qualifiers.
967 LangAS getDefaultCXXMethodAddrSpace() const;
968
969 /// Load weak undeclared identifiers from the external source.
970 void LoadExternalWeakUndeclaredIdentifiers();
971
972 /// Load #pragma redefine_extname'd undeclared identifiers from the external
973 /// source.
974 void LoadExternalExtnameUndeclaredIdentifiers();
975
976 /// Determine if VD, which must be a variable or function, is an external
977 /// symbol that nonetheless can't be referenced from outside this translation
978 /// unit because its type has no linkage and it's not extern "C".
979 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
980
981 /// Determines whether the given source location is in the main file
982 /// and we're in a context where we should warn about unused entities.
983 bool isMainFileLoc(SourceLocation Loc) const;
984
985 /// Obtain a sorted list of functions that are undefined but ODR-used.
986 void getUndefinedButUsed(
987 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined);
988
989 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
990 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
991 /// Retrieves list of suspicious delete-expressions that will be checked at
992 /// the end of translation unit.
993 const llvm::MapVector<FieldDecl *, DeleteLocs> &
994 getMismatchingDeleteExpressions() const;
995
996 /// Cause the built diagnostic to be emitted on the DiagosticsEngine.
997 /// This is closely coupled to the SemaDiagnosticBuilder class and
998 /// should not be used elsewhere.
999 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB);
1000
1001 void addImplicitTypedef(StringRef Name, QualType T);
1002
1003 /// Whether uncompilable error has occurred. This includes error happens
1004 /// in deferred diagnostics.
1005 bool hasUncompilableErrorOccurred() const;
1006
1007 /// Looks through the macro-expansion chain for the given
1008 /// location, looking for a macro expansion with the given name.
1009 /// If one is found, returns true and sets the location to that
1010 /// expansion loc.
1011 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1012
1013 /// Calls \c Lexer::getLocForEndOfToken()
1014 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1015
1016 /// Calls \c Lexer::findNextToken() to find the next token, and if the
1017 /// locations of both ends of the token can be resolved it return that
1018 /// range; Otherwise it returns an invalid SourceRange.
1019 SourceRange getRangeForNextToken(
1020 SourceLocation Loc, bool IncludeMacros, bool IncludeComments,
1021 std::optional<tok::TokenKind> ExpectedToken = std::nullopt);
1022
1023 /// Retrieve the module loader associated with the preprocessor.
1024 ModuleLoader &getModuleLoader() const;
1025
1026 /// Invent a new identifier for parameters of abbreviated templates.
1027 IdentifierInfo *
1028 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName,
1029 unsigned Index);
1030
1031 void emitAndClearUnusedLocalTypedefWarnings();
1032
1033 // Emit all deferred diagnostics.
1034 void emitDeferredDiags();
1035
1036 /// This is called before the very first declaration in the translation unit
1037 /// is parsed. Note that the ASTContext may have already injected some
1038 /// declarations.
1039 void ActOnStartOfTranslationUnit();
1040 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1041 /// translation unit when EOF is reached and all but the top-level scope is
1042 /// popped.
1043 void ActOnEndOfTranslationUnit();
1044 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1045
1046 /// Determines the active Scope associated with the given declaration
1047 /// context.
1048 ///
1049 /// This routine maps a declaration context to the active Scope object that
1050 /// represents that declaration context in the parser. It is typically used
1051 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1052 /// declarations) that injects a name for name-lookup purposes and, therefore,
1053 /// must update the Scope.
1054 ///
1055 /// \returns The scope corresponding to the given declaraion context, or NULL
1056 /// if no such scope is open.
1057 Scope *getScopeForContext(DeclContext *Ctx);
1058
1059 void PushFunctionScope();
1060 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1061 sema::LambdaScopeInfo *PushLambdaScope();
1062
1063 /// This is used to inform Sema what the current TemplateParameterDepth
1064 /// is during Parsing. Currently it is used to pass on the depth
1065 /// when parsing generic lambda 'auto' parameters.
1066 void RecordParsingTemplateParameterDepth(unsigned Depth);
1067
1068 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1069 RecordDecl *RD, CapturedRegionKind K,
1070 unsigned OpenMPCaptureLevel = 0);
1071
1072 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1073 /// time after they've been popped.
1074 class PoppedFunctionScopeDeleter {
1075 Sema *Self;
1076
1077 public:
1078 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1079 void operator()(sema::FunctionScopeInfo *Scope) const;
1080 };
1081
1082 using PoppedFunctionScopePtr =
1083 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1084
1085 /// Pop a function (or block or lambda or captured region) scope from the
1086 /// stack.
1087 ///
1088 /// \param WP The warning policy to use for CFG-based warnings, or null if
1089 /// such warnings should not be produced.
1090 /// \param D The declaration corresponding to this function scope, if
1091 /// producing CFG-based warnings.
1092 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1093 PoppedFunctionScopePtr
1094 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1095 Decl *D = nullptr, QualType BlockType = QualType());
1096
1097 sema::FunctionScopeInfo *getEnclosingFunction() const;
1098
1099 void setFunctionHasBranchIntoScope();
1100 void setFunctionHasBranchProtectedScope();
1101 void setFunctionHasIndirectGoto();
1102 void setFunctionHasMustTail();
1103
1104 void PushCompoundScope(bool IsStmtExpr);
1105 void PopCompoundScope();
1106
1107 /// Determine whether any errors occurred within this function/method/
1108 /// block.
1109 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1110
1111 /// Retrieve the current block, if any.
1112 sema::BlockScopeInfo *getCurBlock();
1113
1114 /// Get the innermost lambda or block enclosing the current location, if any.
1115 /// This looks through intervening non-lambda, non-block scopes such as local
1116 /// functions.
1117 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const;
1118
1119 /// Retrieve the current lambda scope info, if any.
1120 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1121 /// lambda scope info ignoring all inner capturing scopes that are not
1122 /// lambda scopes.
1123 sema::LambdaScopeInfo *
1124 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1125
1126 /// Retrieve the current generic lambda info, if any.
1127 sema::LambdaScopeInfo *getCurGenericLambda();
1128
1129 /// Retrieve the current captured region, if any.
1130 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1131
1132 void ActOnComment(SourceRange Comment);
1133
1134 /// Retrieve the parser's current scope.
1135 ///
1136 /// This routine must only be used when it is certain that semantic analysis
1137 /// and the parser are in precisely the same context, which is not the case
1138 /// when, e.g., we are performing any kind of template instantiation.
1139 /// Therefore, the only safe places to use this scope are in the parser
1140 /// itself and in routines directly invoked from the parser and *never* from
1141 /// template substitution or instantiation.
1142 Scope *getCurScope() const { return CurScope; }
1143
1144 IdentifierInfo *getSuperIdentifier() const;
1145
1146 DeclContext *getCurLexicalContext() const {
1147 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
1148 }
1149
1150 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
1151 const FunctionDecl *FD = nullptr);
1152 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
1153 const PartialDiagnostic &PD,
1154 const FunctionDecl *FD = nullptr) {
1155 return targetDiag(Loc, DiagID: PD.getDiagID(), FD) << PD;
1156 }
1157
1158 /// Check if the type is allowed to be used for the current target.
1159 void checkTypeSupport(QualType Ty, SourceLocation Loc,
1160 ValueDecl *D = nullptr);
1161
1162 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
1163 /// cast. If there is already an implicit cast, merge into the existing one.
1164 /// If isLvalue, the result of the cast is an lvalue.
1165 ExprResult ImpCastExprToType(
1166 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue,
1167 const CXXCastPath *BasePath = nullptr,
1168 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
1169
1170 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
1171 /// to the conversion from scalar type ScalarTy to the Boolean type.
1172 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
1173
1174 /// If \p AllowLambda is true, treat lambda as function.
1175 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
1176
1177 /// Returns a pointer to the innermost enclosing function, or nullptr if the
1178 /// current context is not inside a function. If \p AllowLambda is true,
1179 /// this can return the call operator of an enclosing lambda, otherwise
1180 /// lambdas are skipped when looking for an enclosing function.
1181 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
1182
1183 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
1184 /// the method decl for the method being parsed. If we're currently
1185 /// in a 'block', this returns the containing context.
1186 ObjCMethodDecl *getCurMethodDecl();
1187
1188 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
1189 /// or C function we're in, otherwise return null. If we're currently
1190 /// in a 'block', this returns the containing context.
1191 NamedDecl *getCurFunctionOrMethodDecl() const;
1192
1193 /// Warn if we're implicitly casting from a _Nullable pointer type to a
1194 /// _Nonnull one.
1195 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
1196 SourceLocation Loc);
1197
1198 /// Warn when implicitly casting 0 to nullptr.
1199 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
1200
1201 /// Warn when implicitly changing function effects.
1202 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,
1203 SourceLocation Loc);
1204
1205 /// makeUnavailableInSystemHeader - There is an error in the current
1206 /// context. If we're still in a system header, and we can plausibly
1207 /// make the relevant declaration unavailable instead of erroring, do
1208 /// so and return true.
1209 bool makeUnavailableInSystemHeader(SourceLocation loc,
1210 UnavailableAttr::ImplicitReason reason);
1211
1212 /// Retrieve a suitable printing policy for diagnostics.
1213 PrintingPolicy getPrintingPolicy() const {
1214 return getPrintingPolicy(Ctx: Context, PP);
1215 }
1216
1217 /// Retrieve a suitable printing policy for diagnostics.
1218 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1219 const Preprocessor &PP);
1220
1221 /// Scope actions.
1222 void ActOnTranslationUnitScope(Scope *S);
1223
1224 /// Determine whether \param D is function like (function or function
1225 /// template) for parsing.
1226 bool isDeclaratorFunctionLike(Declarator &D);
1227
1228 /// The maximum alignment, same as in llvm::Value. We duplicate them here
1229 /// because that allows us not to duplicate the constants in clang code,
1230 /// which we must to since we can't directly use the llvm constants.
1231 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
1232 ///
1233 /// This is the greatest alignment value supported by load, store, and alloca
1234 /// instructions, and global values.
1235 static const unsigned MaxAlignmentExponent = 32;
1236 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
1237
1238 /// Flag indicating whether or not to collect detailed statistics.
1239 bool CollectStats;
1240
1241 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
1242
1243 /// Stack containing information about each of the nested
1244 /// function, block, and method scopes that are currently active.
1245 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
1246
1247 /// The index of the first FunctionScope that corresponds to the current
1248 /// context.
1249 unsigned FunctionScopesStart = 0;
1250
1251 /// Track the number of currently active capturing scopes.
1252 unsigned CapturingFunctionScopes = 0;
1253
1254 llvm::BumpPtrAllocator BumpAlloc;
1255
1256 /// The kind of translation unit we are processing.
1257 ///
1258 /// When we're processing a complete translation unit, Sema will perform
1259 /// end-of-translation-unit semantic tasks (such as creating
1260 /// initializers for tentative definitions in C) once parsing has
1261 /// completed. Modules and precompiled headers perform different kinds of
1262 /// checks.
1263 const TranslationUnitKind TUKind;
1264
1265 /// Translation Unit Scope - useful to Objective-C actions that need
1266 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1267 /// For example, user-defined classes, built-in "id" type, etc.
1268 Scope *TUScope;
1269
1270 void incrementMSManglingNumber() const {
1271 return CurScope->incrementMSManglingNumber();
1272 }
1273
1274 /// Try to recover by turning the given expression into a
1275 /// call. Returns true if recovery was attempted or an error was
1276 /// emitted; this may also leave the ExprResult invalid.
1277 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1278 bool ForceComplain = false,
1279 bool (*IsPlausibleResult)(QualType) = nullptr);
1280
1281 // Adds implicit lifetime bound attribute for implicit this to its
1282 // TypeSourceInfo.
1283 void addLifetimeBoundToImplicitThis(CXXMethodDecl *MD);
1284
1285 /// Figure out if an expression could be turned into a call.
1286 ///
1287 /// Use this when trying to recover from an error where the programmer may
1288 /// have written just the name of a function instead of actually calling it.
1289 ///
1290 /// \param E - The expression to examine.
1291 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1292 /// with no arguments, this parameter is set to the type returned by such a
1293 /// call; otherwise, it is set to an empty QualType.
1294 /// \param OverloadSet - If the expression is an overloaded function
1295 /// name, this parameter is populated with the decls of the various
1296 /// overloads.
1297 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1298 UnresolvedSetImpl &NonTemplateOverloads);
1299
1300 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
1301 typedef OpaquePtr<TemplateName> TemplateTy;
1302 typedef OpaquePtr<QualType> TypeTy;
1303
1304 OpenCLOptions OpenCLFeatures;
1305 FPOptions CurFPFeatures;
1306
1307 const LangOptions &LangOpts;
1308 Preprocessor &PP;
1309 ASTContext &Context;
1310 ASTConsumer &Consumer;
1311 DiagnosticsEngine &Diags;
1312 SourceManager &SourceMgr;
1313 api_notes::APINotesManager APINotes;
1314
1315 /// A RAII object to enter scope of a compound statement.
1316 class CompoundScopeRAII {
1317 public:
1318 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
1319 S.ActOnStartOfCompoundStmt(IsStmtExpr);
1320 }
1321
1322 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); }
1323 CompoundScopeRAII(const CompoundScopeRAII &) = delete;
1324 CompoundScopeRAII &operator=(const CompoundScopeRAII &) = delete;
1325
1326 private:
1327 Sema &S;
1328 };
1329
1330 /// An RAII helper that pops function a function scope on exit.
1331 struct FunctionScopeRAII {
1332 Sema &S;
1333 bool Active;
1334 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
1335 ~FunctionScopeRAII() {
1336 if (Active)
1337 S.PopFunctionScopeInfo();
1338 }
1339 void disable() { Active = false; }
1340 };
1341
1342 sema::FunctionScopeInfo *getCurFunction() const {
1343 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1344 }
1345
1346 /// Worker object for performing CFG-based warnings.
1347 sema::AnalysisBasedWarnings AnalysisWarnings;
1348 threadSafety::BeforeSet *ThreadSafetyDeclCache;
1349
1350 /// Callback to the parser to parse templated functions when needed.
1351 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
1352 LateTemplateParserCB *LateTemplateParser;
1353 void *OpaqueParser;
1354
1355 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) {
1356 LateTemplateParser = LTP;
1357 OpaqueParser = P;
1358 }
1359
1360 /// Callback to the parser to parse a type expressed as a string.
1361 std::function<TypeResult(StringRef, StringRef, SourceLocation)>
1362 ParseTypeFromStringCallback;
1363
1364 /// VAListTagName - The declaration name corresponding to __va_list_tag.
1365 /// This is used as part of a hack to omit that class from ADL results.
1366 DeclarationName VAListTagName;
1367
1368 /// Is the last error level diagnostic immediate. This is used to determined
1369 /// whether the next info diagnostic should be immediate.
1370 bool IsLastErrorImmediate = true;
1371
1372 /// Track if we're currently analyzing overflow behavior types in assignment
1373 /// context.
1374 bool InOverflowBehaviorAssignmentContext = false;
1375
1376 class DelayedDiagnostics;
1377
1378 class DelayedDiagnosticsState {
1379 sema::DelayedDiagnosticPool *SavedPool = nullptr;
1380 friend class Sema::DelayedDiagnostics;
1381 };
1382 typedef DelayedDiagnosticsState ParsingDeclState;
1383 typedef DelayedDiagnosticsState ProcessingContextState;
1384
1385 /// A class which encapsulates the logic for delaying diagnostics
1386 /// during parsing and other processing.
1387 class DelayedDiagnostics {
1388 /// The current pool of diagnostics into which delayed
1389 /// diagnostics should go.
1390 sema::DelayedDiagnosticPool *CurPool = nullptr;
1391
1392 public:
1393 DelayedDiagnostics() = default;
1394
1395 /// Adds a delayed diagnostic.
1396 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
1397
1398 /// Determines whether diagnostics should be delayed.
1399 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
1400
1401 /// Returns the current delayed-diagnostics pool.
1402 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; }
1403
1404 /// Enter a new scope. Access and deprecation diagnostics will be
1405 /// collected in this pool.
1406 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
1407 DelayedDiagnosticsState state;
1408 state.SavedPool = CurPool;
1409 CurPool = &pool;
1410 return state;
1411 }
1412
1413 /// Leave a delayed-diagnostic state that was previously pushed.
1414 /// Do not emit any of the diagnostics. This is performed as part
1415 /// of the bookkeeping of popping a pool "properly".
1416 void popWithoutEmitting(DelayedDiagnosticsState state) {
1417 CurPool = state.SavedPool;
1418 }
1419
1420 /// Enter a new scope where access and deprecation diagnostics are
1421 /// not delayed.
1422 DelayedDiagnosticsState pushUndelayed() {
1423 DelayedDiagnosticsState state;
1424 state.SavedPool = CurPool;
1425 CurPool = nullptr;
1426 return state;
1427 }
1428
1429 /// Undo a previous pushUndelayed().
1430 void popUndelayed(DelayedDiagnosticsState state) {
1431 assert(CurPool == nullptr);
1432 CurPool = state.SavedPool;
1433 }
1434 } DelayedDiagnostics;
1435
1436 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
1437 return DelayedDiagnostics.push(pool);
1438 }
1439
1440 /// Diagnostics that are emitted only if we discover that the given function
1441 /// must be codegen'ed. Because handling these correctly adds overhead to
1442 /// compilation, this is currently only used for offload languages like CUDA,
1443 /// OpenMP, and SYCL.
1444 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags;
1445
1446 /// CurContext - This is the current declaration context of parsing.
1447 DeclContext *CurContext;
1448
1449 SemaAMDGPU &AMDGPU() {
1450 assert(AMDGPUPtr);
1451 return *AMDGPUPtr;
1452 }
1453
1454 SemaARM &ARM() {
1455 assert(ARMPtr);
1456 return *ARMPtr;
1457 }
1458
1459 SemaAVR &AVR() {
1460 assert(AVRPtr);
1461 return *AVRPtr;
1462 }
1463
1464 SemaBPF &BPF() {
1465 assert(BPFPtr);
1466 return *BPFPtr;
1467 }
1468
1469 SemaCodeCompletion &CodeCompletion() {
1470 assert(CodeCompletionPtr);
1471 return *CodeCompletionPtr;
1472 }
1473
1474 SemaCUDA &CUDA() {
1475 assert(CUDAPtr);
1476 return *CUDAPtr;
1477 }
1478
1479 SemaDirectX &DirectX() {
1480 assert(DirectXPtr);
1481 return *DirectXPtr;
1482 }
1483
1484 SemaHLSL &HLSL() {
1485 assert(HLSLPtr);
1486 return *HLSLPtr;
1487 }
1488
1489 SemaHexagon &Hexagon() {
1490 assert(HexagonPtr);
1491 return *HexagonPtr;
1492 }
1493
1494 SemaLoongArch &LoongArch() {
1495 assert(LoongArchPtr);
1496 return *LoongArchPtr;
1497 }
1498
1499 SemaM68k &M68k() {
1500 assert(M68kPtr);
1501 return *M68kPtr;
1502 }
1503
1504 SemaMIPS &MIPS() {
1505 assert(MIPSPtr);
1506 return *MIPSPtr;
1507 }
1508
1509 SemaMSP430 &MSP430() {
1510 assert(MSP430Ptr);
1511 return *MSP430Ptr;
1512 }
1513
1514 SemaNVPTX &NVPTX() {
1515 assert(NVPTXPtr);
1516 return *NVPTXPtr;
1517 }
1518
1519 SemaObjC &ObjC() {
1520 assert(ObjCPtr);
1521 return *ObjCPtr;
1522 }
1523
1524 SemaOpenACC &OpenACC() {
1525 assert(OpenACCPtr);
1526 return *OpenACCPtr;
1527 }
1528
1529 SemaOpenCL &OpenCL() {
1530 assert(OpenCLPtr);
1531 return *OpenCLPtr;
1532 }
1533
1534 SemaOpenMP &OpenMP() {
1535 assert(OpenMPPtr && "SemaOpenMP is dead");
1536 return *OpenMPPtr;
1537 }
1538
1539 SemaPPC &PPC() {
1540 assert(PPCPtr);
1541 return *PPCPtr;
1542 }
1543
1544 SemaPseudoObject &PseudoObject() {
1545 assert(PseudoObjectPtr);
1546 return *PseudoObjectPtr;
1547 }
1548
1549 SemaRISCV &RISCV() {
1550 assert(RISCVPtr);
1551 return *RISCVPtr;
1552 }
1553
1554 SemaSPIRV &SPIRV() {
1555 assert(SPIRVPtr);
1556 return *SPIRVPtr;
1557 }
1558
1559 SemaSYCL &SYCL() {
1560 assert(SYCLPtr);
1561 return *SYCLPtr;
1562 }
1563
1564 SemaSwift &Swift() {
1565 assert(SwiftPtr);
1566 return *SwiftPtr;
1567 }
1568
1569 SemaSystemZ &SystemZ() {
1570 assert(SystemZPtr);
1571 return *SystemZPtr;
1572 }
1573
1574 SemaWasm &Wasm() {
1575 assert(WasmPtr);
1576 return *WasmPtr;
1577 }
1578
1579 SemaX86 &X86() {
1580 assert(X86Ptr);
1581 return *X86Ptr;
1582 }
1583
1584 /// Source of additional semantic information.
1585 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
1586
1587protected:
1588 friend class Parser;
1589 friend class InitializationSequence;
1590 friend class ASTReader;
1591 friend class ASTDeclReader;
1592 friend class ASTWriter;
1593
1594private:
1595 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1596 bool WarnedDarwinSDKInfoMissing = false;
1597
1598 StackExhaustionHandler StackHandler;
1599
1600 Sema(const Sema &) = delete;
1601 void operator=(const Sema &) = delete;
1602
1603 /// The handler for the FileChanged preprocessor events.
1604 ///
1605 /// Used for diagnostics that implement custom semantic analysis for #include
1606 /// directives, like -Wpragma-pack.
1607 sema::SemaPPCallbacks *SemaPPCallbackHandler;
1608
1609 /// The parser's current scope.
1610 ///
1611 /// The parser maintains this state here.
1612 Scope *CurScope;
1613
1614 mutable IdentifierInfo *Ident_super;
1615
1616 std::unique_ptr<SemaAMDGPU> AMDGPUPtr;
1617 std::unique_ptr<SemaARM> ARMPtr;
1618 std::unique_ptr<SemaAVR> AVRPtr;
1619 std::unique_ptr<SemaBPF> BPFPtr;
1620 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr;
1621 std::unique_ptr<SemaCUDA> CUDAPtr;
1622 std::unique_ptr<SemaDirectX> DirectXPtr;
1623 std::unique_ptr<SemaHLSL> HLSLPtr;
1624 std::unique_ptr<SemaHexagon> HexagonPtr;
1625 std::unique_ptr<SemaLoongArch> LoongArchPtr;
1626 std::unique_ptr<SemaM68k> M68kPtr;
1627 std::unique_ptr<SemaMIPS> MIPSPtr;
1628 std::unique_ptr<SemaMSP430> MSP430Ptr;
1629 std::unique_ptr<SemaNVPTX> NVPTXPtr;
1630 std::unique_ptr<SemaObjC> ObjCPtr;
1631 std::unique_ptr<SemaOpenACC> OpenACCPtr;
1632 std::unique_ptr<SemaOpenCL> OpenCLPtr;
1633 std::unique_ptr<SemaOpenMP> OpenMPPtr;
1634 std::unique_ptr<SemaPPC> PPCPtr;
1635 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr;
1636 std::unique_ptr<SemaRISCV> RISCVPtr;
1637 std::unique_ptr<SemaSPIRV> SPIRVPtr;
1638 std::unique_ptr<SemaSYCL> SYCLPtr;
1639 std::unique_ptr<SemaSwift> SwiftPtr;
1640 std::unique_ptr<SemaSystemZ> SystemZPtr;
1641 std::unique_ptr<SemaWasm> WasmPtr;
1642 std::unique_ptr<SemaX86> X86Ptr;
1643
1644 ///@}
1645
1646 //
1647 //
1648 // -------------------------------------------------------------------------
1649 //
1650 //
1651
1652 /// \name API Notes
1653 /// Implementations are in SemaAPINotes.cpp
1654 ///@{
1655
1656public:
1657 /// Map any API notes provided for this declaration to attributes on the
1658 /// declaration.
1659 ///
1660 /// Triggered by declaration-attribute processing.
1661 void ProcessAPINotes(Decl *D);
1662 /// Apply the 'Nullability:' annotation to the specified declaration
1663 void ApplyNullability(Decl *D, NullabilityKind Nullability);
1664 /// Apply the 'Type:' annotation to the specified declaration
1665 void ApplyAPINotesType(Decl *D, StringRef TypeString);
1666
1667 /// Whether APINotes should be gathered for all applicable Swift language
1668 /// versions, without being applied. Leaving clients of the current module
1669 /// to select and apply the correct version.
1670 bool captureSwiftVersionIndependentAPINotes() {
1671 return APINotes.captureVersionIndependentSwift();
1672 }
1673 ///@}
1674
1675 //
1676 //
1677 // -------------------------------------------------------------------------
1678 //
1679 //
1680
1681 /// \name C++ Access Control
1682 /// Implementations are in SemaAccess.cpp
1683 ///@{
1684
1685public:
1686 enum AccessResult {
1687 AR_accessible,
1688 AR_inaccessible,
1689 AR_dependent,
1690 AR_delayed
1691 };
1692
1693 /// SetMemberAccessSpecifier - Set the access specifier of a member.
1694 /// Returns true on error (when the previous member decl access specifier
1695 /// is different from the new member decl access specifier).
1696 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
1697 NamedDecl *PrevMemberDecl,
1698 AccessSpecifier LexicalAS);
1699
1700 /// Perform access-control checking on a previously-unresolved member
1701 /// access which has now been resolved to a member.
1702 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1703 DeclAccessPair FoundDecl);
1704 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1705 DeclAccessPair FoundDecl);
1706
1707 /// Checks access to an overloaded operator new or delete.
1708 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
1709 SourceRange PlacementRange,
1710 CXXRecordDecl *NamingClass,
1711 DeclAccessPair FoundDecl,
1712 bool Diagnose = true);
1713
1714 /// Checks access to a constructor.
1715 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1716 DeclAccessPair FoundDecl,
1717 const InitializedEntity &Entity,
1718 bool IsCopyBindingRefToTemp = false);
1719
1720 /// Checks access to a constructor.
1721 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D,
1722 DeclAccessPair FoundDecl,
1723 const InitializedEntity &Entity,
1724 const PartialDiagnostic &PDiag);
1725 AccessResult CheckDestructorAccess(SourceLocation Loc,
1726 CXXDestructorDecl *Dtor,
1727 const PartialDiagnostic &PDiag,
1728 QualType objectType = QualType());
1729
1730 /// Checks access to the target of a friend declaration.
1731 AccessResult CheckFriendAccess(NamedDecl *D);
1732
1733 /// Checks access to a member.
1734 AccessResult CheckMemberAccess(SourceLocation UseLoc,
1735 CXXRecordDecl *NamingClass,
1736 DeclAccessPair Found);
1737
1738 /// Checks implicit access to a member in a structured binding.
1739 AccessResult
1740 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1741 CXXRecordDecl *DecomposedClass,
1742 DeclAccessPair Field);
1743 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1744 const SourceRange &,
1745 DeclAccessPair FoundDecl);
1746
1747 /// Checks access to an overloaded member operator, including
1748 /// conversion operators.
1749 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1750 Expr *ArgExpr,
1751 DeclAccessPair FoundDecl);
1752 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
1753 ArrayRef<Expr *> ArgExprs,
1754 DeclAccessPair FoundDecl);
1755 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
1756 DeclAccessPair FoundDecl);
1757
1758 /// Checks access for a hierarchy conversion.
1759 ///
1760 /// \param ForceCheck true if this check should be performed even if access
1761 /// control is disabled; some things rely on this for semantics
1762 /// \param ForceUnprivileged true if this check should proceed as if the
1763 /// context had no special privileges
1764 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base,
1765 QualType Derived, const CXXBasePath &Path,
1766 unsigned DiagID, bool ForceCheck = false,
1767 bool ForceUnprivileged = false);
1768
1769 AccessResult CheckBaseClassAccess(
1770 SourceLocation AccessLoc, CXXRecordDecl *Base, CXXRecordDecl *Derived,
1771 const CXXBasePath &Path, unsigned DiagID,
1772 llvm::function_ref<void(PartialDiagnostic &PD)> SetupPDiag,
1773 bool ForceCheck = false, bool ForceUnprivileged = false);
1774
1775 /// Checks access to all the declarations in the given result set.
1776 void CheckLookupAccess(const LookupResult &R);
1777
1778 /// Checks access to Target from the given class. The check will take access
1779 /// specifiers into account, but no member access expressions and such.
1780 ///
1781 /// \param Target the declaration to check if it can be accessed
1782 /// \param NamingClass the class in which the lookup was started.
1783 /// \param BaseType type of the left side of member access expression.
1784 /// \p BaseType and \p NamingClass are used for C++ access control.
1785 /// Depending on the lookup case, they should be set to the following:
1786 /// - lhs.target (member access without a qualifier):
1787 /// \p BaseType and \p NamingClass are both the type of 'lhs'.
1788 /// - lhs.X::target (member access with a qualifier):
1789 /// BaseType is the type of 'lhs', NamingClass is 'X'
1790 /// - X::target (qualified lookup without member access):
1791 /// BaseType is null, NamingClass is 'X'.
1792 /// - target (unqualified lookup).
1793 /// BaseType is null, NamingClass is the parent class of 'target'.
1794 /// \return true if the Target is accessible from the Class, false otherwise.
1795 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
1796 QualType BaseType);
1797
1798 /// Is the given member accessible for the purposes of deciding whether to
1799 /// define a special member function as deleted?
1800 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1801 DeclAccessPair Found, QualType ObjectType,
1802 SourceLocation Loc,
1803 const PartialDiagnostic &Diag);
1804 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1805 DeclAccessPair Found,
1806 QualType ObjectType) {
1807 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
1808 Loc: SourceLocation(), Diag: PDiag());
1809 }
1810
1811 void HandleDependentAccessCheck(
1812 const DependentDiagnostic &DD,
1813 const MultiLevelTemplateArgumentList &TemplateArgs);
1814 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
1815
1816 ///@}
1817
1818 //
1819 //
1820 // -------------------------------------------------------------------------
1821 //
1822 //
1823
1824 /// \name Attributes
1825 /// Implementations are in SemaAttr.cpp
1826 ///@{
1827
1828public:
1829 /// Controls member pointer representation format under the MS ABI.
1830 LangOptions::PragmaMSPointersToMembersKind
1831 MSPointerToMemberRepresentationMethod;
1832
1833 bool MSStructPragmaOn; // True when \#pragma ms_struct on
1834
1835 /// Source location for newly created implicit MSInheritanceAttrs
1836 SourceLocation ImplicitMSInheritanceAttrLoc;
1837
1838 struct PragmaClangSection {
1839 std::string SectionName;
1840 bool Valid = false;
1841 SourceLocation PragmaLocation;
1842 };
1843
1844 PragmaClangSection PragmaClangBSSSection;
1845 PragmaClangSection PragmaClangDataSection;
1846 PragmaClangSection PragmaClangRodataSection;
1847 PragmaClangSection PragmaClangRelroSection;
1848 PragmaClangSection PragmaClangTextSection;
1849
1850 enum PragmaMsStackAction {
1851 PSK_Reset = 0x0, // #pragma ()
1852 PSK_Set = 0x1, // #pragma (value)
1853 PSK_Push = 0x2, // #pragma (push[, id])
1854 PSK_Pop = 0x4, // #pragma (pop[, id])
1855 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
1856 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
1857 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
1858 };
1859
1860 struct PragmaPackInfo {
1861 PragmaMsStackAction Action;
1862 StringRef SlotLabel;
1863 Token Alignment;
1864 };
1865
1866 // #pragma pack and align.
1867 class AlignPackInfo {
1868 public:
1869 // `Native` represents default align mode, which may vary based on the
1870 // platform.
1871 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
1872
1873 // #pragma pack info constructor
1874 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
1875 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
1876 assert(Num == PackNumber && "The pack number has been truncated.");
1877 }
1878
1879 // #pragma align info constructor
1880 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
1881 : PackAttr(false), AlignMode(M),
1882 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
1883
1884 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
1885
1886 AlignPackInfo() : AlignPackInfo(Native, false) {}
1887
1888 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
1889 // integer encoding for it. This should only be passed to
1890 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
1891 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
1892 std::uint32_t Encoding{};
1893 if (Info.IsXLStack())
1894 Encoding |= IsXLMask;
1895
1896 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
1897
1898 if (Info.IsPackAttr())
1899 Encoding |= PackAttrMask;
1900
1901 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
1902
1903 return Encoding;
1904 }
1905
1906 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
1907 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
1908 AlignPackInfo::Mode M =
1909 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
1910 int PackNumber = (Encoding & PackNumMask) >> 4;
1911
1912 if (Encoding & PackAttrMask)
1913 return AlignPackInfo(M, PackNumber, IsXL);
1914
1915 return AlignPackInfo(M, IsXL);
1916 }
1917
1918 bool IsPackAttr() const { return PackAttr; }
1919
1920 bool IsAlignAttr() const { return !PackAttr; }
1921
1922 Mode getAlignMode() const { return AlignMode; }
1923
1924 unsigned getPackNumber() const { return PackNumber; }
1925
1926 bool IsPackSet() const {
1927 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
1928 // attriute on a decl.
1929 return PackNumber != UninitPackVal && PackNumber != 0;
1930 }
1931
1932 bool IsXLStack() const { return XLStack; }
1933
1934 bool operator==(const AlignPackInfo &Info) const {
1935 return std::tie(args: AlignMode, args: PackNumber, args: PackAttr, args: XLStack) ==
1936 std::tie(args: Info.AlignMode, args: Info.PackNumber, args: Info.PackAttr,
1937 args: Info.XLStack);
1938 }
1939
1940 bool operator!=(const AlignPackInfo &Info) const {
1941 return !(*this == Info);
1942 }
1943
1944 private:
1945 /// \brief True if this is a pragma pack attribute,
1946 /// not a pragma align attribute.
1947 bool PackAttr;
1948
1949 /// \brief The alignment mode that is in effect.
1950 Mode AlignMode;
1951
1952 /// \brief The pack number of the stack.
1953 unsigned char PackNumber;
1954
1955 /// \brief True if it is a XL #pragma align/pack stack.
1956 bool XLStack;
1957
1958 /// \brief Uninitialized pack value.
1959 static constexpr unsigned char UninitPackVal = -1;
1960
1961 // Masks to encode and decode an AlignPackInfo.
1962 static constexpr uint32_t IsXLMask{0x0000'0001};
1963 static constexpr uint32_t AlignModeMask{0x0000'0006};
1964 static constexpr uint32_t PackAttrMask{0x00000'0008};
1965 static constexpr uint32_t PackNumMask{0x0000'01F0};
1966 };
1967
1968 template <typename ValueType> struct PragmaStack {
1969 struct Slot {
1970 llvm::StringRef StackSlotLabel;
1971 ValueType Value;
1972 SourceLocation PragmaLocation;
1973 SourceLocation PragmaPushLocation;
1974 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
1975 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
1976 : StackSlotLabel(StackSlotLabel), Value(Value),
1977 PragmaLocation(PragmaLocation),
1978 PragmaPushLocation(PragmaPushLocation) {}
1979 };
1980
1981 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
1982 llvm::StringRef StackSlotLabel, ValueType Value) {
1983 if (Action == PSK_Reset) {
1984 CurrentValue = DefaultValue;
1985 CurrentPragmaLocation = PragmaLocation;
1986 return;
1987 }
1988 if (Action & PSK_Push)
1989 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
1990 PragmaLocation);
1991 else if (Action & PSK_Pop) {
1992 if (!StackSlotLabel.empty()) {
1993 // If we've got a label, try to find it and jump there.
1994 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
1995 return x.StackSlotLabel == StackSlotLabel;
1996 });
1997 // If we found the label so pop from there.
1998 if (I != Stack.rend()) {
1999 CurrentValue = I->Value;
2000 CurrentPragmaLocation = I->PragmaLocation;
2001 Stack.erase(std::prev(I.base()), Stack.end());
2002 }
2003 } else if (!Stack.empty()) {
2004 // We do not have a label, just pop the last entry.
2005 CurrentValue = Stack.back().Value;
2006 CurrentPragmaLocation = Stack.back().PragmaLocation;
2007 Stack.pop_back();
2008 }
2009 }
2010 if (Action & PSK_Set) {
2011 CurrentValue = Value;
2012 CurrentPragmaLocation = PragmaLocation;
2013 }
2014 }
2015
2016 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
2017 // method body to restore the stacks on exit, so it works like this:
2018 //
2019 // struct S {
2020 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
2021 // void Method {}
2022 // #pragma <name>(pop, InternalPragmaSlot)
2023 // };
2024 //
2025 // It works even with #pragma vtordisp, although MSVC doesn't support
2026 // #pragma vtordisp(push [, id], n)
2027 // syntax.
2028 //
2029 // Push / pop a named sentinel slot.
2030 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
2031 assert((Action == PSK_Push || Action == PSK_Pop) &&
2032 "Can only push / pop #pragma stack sentinels!");
2033 Act(PragmaLocation: CurrentPragmaLocation, Action, StackSlotLabel: Label, Value: CurrentValue);
2034 }
2035
2036 // Constructors.
2037 explicit PragmaStack(const ValueType &Default)
2038 : DefaultValue(Default), CurrentValue(Default) {}
2039
2040 bool hasValue() const { return CurrentValue != DefaultValue; }
2041
2042 SmallVector<Slot, 2> Stack;
2043 ValueType DefaultValue; // Value used for PSK_Reset action.
2044 ValueType CurrentValue;
2045 SourceLocation CurrentPragmaLocation;
2046 };
2047 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
2048 // we shouldn't do so if they're in a module).
2049
2050 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
2051 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
2052 ///
2053 /// 0: Suppress all vtordisps
2054 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
2055 /// structors
2056 /// 2: Always insert vtordisps to support RTTI on partially constructed
2057 /// objects
2058 PragmaStack<MSVtorDispMode> VtorDispStack;
2059 PragmaStack<AlignPackInfo> AlignPackStack;
2060 // The current #pragma align/pack values and locations at each #include.
2061 struct AlignPackIncludeState {
2062 AlignPackInfo CurrentValue;
2063 SourceLocation CurrentPragmaLocation;
2064 bool HasNonDefaultValue, ShouldWarnOnInclude;
2065 };
2066 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
2067 // Segment #pragmas.
2068 PragmaStack<StringLiteral *> DataSegStack;
2069 PragmaStack<StringLiteral *> BSSSegStack;
2070 PragmaStack<StringLiteral *> ConstSegStack;
2071 PragmaStack<StringLiteral *> CodeSegStack;
2072
2073 // #pragma strict_gs_check.
2074 PragmaStack<bool> StrictGuardStackCheckStack;
2075
2076 // This stack tracks the current state of Sema.CurFPFeatures.
2077 PragmaStack<FPOptionsOverride> FpPragmaStack;
2078 FPOptionsOverride CurFPFeatureOverrides() {
2079 FPOptionsOverride result;
2080 if (!FpPragmaStack.hasValue()) {
2081 result = FPOptionsOverride();
2082 } else {
2083 result = FpPragmaStack.CurrentValue;
2084 }
2085 return result;
2086 }
2087
2088 enum PragmaSectionKind {
2089 PSK_DataSeg,
2090 PSK_BSSSeg,
2091 PSK_ConstSeg,
2092 PSK_CodeSeg,
2093 };
2094
2095 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
2096 // Actions should be performed only if we enter / exit a C++ method body.
2097 class PragmaStackSentinelRAII {
2098 public:
2099 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
2100 ~PragmaStackSentinelRAII();
2101 PragmaStackSentinelRAII(const PragmaStackSentinelRAII &) = delete;
2102 PragmaStackSentinelRAII &
2103 operator=(const PragmaStackSentinelRAII &) = delete;
2104
2105 private:
2106 Sema &S;
2107 StringRef SlotLabel;
2108 bool ShouldAct;
2109 };
2110
2111 /// Last section used with #pragma init_seg.
2112 StringLiteral *CurInitSeg;
2113 SourceLocation CurInitSegLoc;
2114
2115 /// Sections used with #pragma alloc_text.
2116 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
2117
2118 /// VisContext - Manages the stack for \#pragma GCC visibility.
2119 void *VisContext; // Really a "PragmaVisStack*"
2120
2121 /// This an attribute introduced by \#pragma clang attribute.
2122 struct PragmaAttributeEntry {
2123 SourceLocation Loc;
2124 ParsedAttr *Attribute;
2125 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
2126 bool IsUsed;
2127 };
2128
2129 /// A push'd group of PragmaAttributeEntries.
2130 struct PragmaAttributeGroup {
2131 /// The location of the push attribute.
2132 SourceLocation Loc;
2133 /// The namespace of this push group.
2134 const IdentifierInfo *Namespace;
2135 SmallVector<PragmaAttributeEntry, 2> Entries;
2136 };
2137
2138 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
2139
2140 /// The declaration that is currently receiving an attribute from the
2141 /// #pragma attribute stack.
2142 const Decl *PragmaAttributeCurrentTargetDecl;
2143
2144 /// This represents the last location of a "#pragma clang optimize off"
2145 /// directive if such a directive has not been closed by an "on" yet. If
2146 /// optimizations are currently "on", this is set to an invalid location.
2147 SourceLocation OptimizeOffPragmaLocation;
2148
2149 /// Get the location for the currently active "\#pragma clang optimize
2150 /// off". If this location is invalid, then the state of the pragma is "on".
2151 SourceLocation getOptimizeOffPragmaLocation() const {
2152 return OptimizeOffPragmaLocation;
2153 }
2154
2155 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
2156 /// whether the optimizations in the list passed to the pragma should be
2157 /// turned off or on. This boolean is true by default because command line
2158 /// options are honored when `#pragma optimize("", on)`.
2159 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
2160 bool MSPragmaOptimizeIsOn = true;
2161
2162 /// Set of no-builtin functions listed by \#pragma function.
2163 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
2164
2165 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
2166 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
2167 void AddAlignmentAttributesForRecord(RecordDecl *RD);
2168
2169 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
2170 void AddMsStructLayoutForRecord(RecordDecl *RD);
2171
2172 /// Add gsl::Pointer attribute to std::container::iterator
2173 /// \param ND The declaration that introduces the name
2174 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
2175 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
2176
2177 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
2178 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
2179
2180 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods.
2181 void inferLifetimeBoundAttribute(FunctionDecl *FD);
2182
2183 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods.
2184 void inferLifetimeCaptureByAttribute(FunctionDecl *FD);
2185
2186 /// Add [[gsl::Pointer]] attributes for std:: types.
2187 void inferGslPointerAttribute(TypedefNameDecl *TD);
2188
2189 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
2190 StringRef ParamName);
2191 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
2192 // can be the name of a function parameter, we need to parse the function
2193 // declaration and rest of the parameters before processesing 'X'. Therefore
2194 // do this lazily instead of processing while parsing the annotation itself.
2195 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD);
2196
2197 /// Add _Nullable attributes for std:: types.
2198 void inferNullableClassAttribute(CXXRecordDecl *CRD);
2199
2200 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
2201 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
2202 PragmaClangSectionAction Action,
2203 PragmaClangSectionKind SecKind,
2204 StringRef SecName);
2205
2206 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
2207 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
2208 SourceLocation PragmaLoc);
2209
2210 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
2211 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
2212 StringRef SlotLabel, Expr *Alignment);
2213
2214 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs
2215 /// (unless they are value dependent or type dependent). Returns false
2216 /// and emits a diagnostic if one or more of the arguments could not be
2217 /// folded into a constant.
2218 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI,
2219 MutableArrayRef<Expr *> Args);
2220
2221 enum class PragmaAlignPackDiagnoseKind {
2222 NonDefaultStateAtInclude,
2223 ChangedStateAtExit
2224 };
2225
2226 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
2227 SourceLocation IncludeLoc);
2228 void DiagnoseUnterminatedPragmaAlignPack();
2229
2230 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
2231 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
2232
2233 /// ActOnPragmaMSComment - Called on well formed
2234 /// \#pragma comment(kind, "arg").
2235 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
2236 StringRef Arg);
2237
2238 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
2239 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
2240 StringRef Value);
2241
2242 /// Are precise floating point semantics currently enabled?
2243 bool isPreciseFPEnabled() {
2244 return !CurFPFeatures.getAllowFPReassociate() &&
2245 !CurFPFeatures.getNoSignedZero() &&
2246 !CurFPFeatures.getAllowReciprocal() &&
2247 !CurFPFeatures.getAllowApproxFunc();
2248 }
2249
2250 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
2251 LangOptions::FPEvalMethodKind Value);
2252
2253 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
2254 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
2255 PragmaFloatControlKind Value);
2256
2257 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
2258 /// pointers_to_members(representation method[, general purpose
2259 /// representation]).
2260 void ActOnPragmaMSPointersToMembers(
2261 LangOptions::PragmaMSPointersToMembersKind Kind,
2262 SourceLocation PragmaLoc);
2263
2264 /// Called on well formed \#pragma vtordisp().
2265 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
2266 SourceLocation PragmaLoc, MSVtorDispMode Value);
2267
2268 bool UnifySection(StringRef SectionName, int SectionFlags,
2269 NamedDecl *TheDecl);
2270 bool UnifySection(StringRef SectionName, int SectionFlags,
2271 SourceLocation PragmaSectionLocation);
2272
2273 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
2274 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
2275 PragmaMsStackAction Action,
2276 llvm::StringRef StackSlotLabel,
2277 StringLiteral *SegmentName, llvm::StringRef PragmaName);
2278
2279 /// Called on well formed \#pragma section().
2280 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags,
2281 StringLiteral *SegmentName);
2282
2283 /// Called on well-formed \#pragma init_seg().
2284 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
2285 StringLiteral *SegmentName);
2286
2287 /// Called on well-formed \#pragma alloc_text().
2288 void ActOnPragmaMSAllocText(
2289 SourceLocation PragmaLocation, StringRef Section,
2290 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>>
2291 &Functions);
2292
2293 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma
2294 /// strict_gs_check.
2295 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation,
2296 PragmaMsStackAction Action,
2297 bool Value);
2298
2299 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
2300 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope,
2301 SourceLocation PragmaLoc);
2302
2303 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
2304 SourceLocation PragmaLoc,
2305 attr::ParsedSubjectMatchRuleSet Rules);
2306 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
2307 const IdentifierInfo *Namespace);
2308
2309 /// Called on well-formed '\#pragma clang attribute pop'.
2310 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
2311 const IdentifierInfo *Namespace);
2312
2313 /// Adds the attributes that have been specified using the
2314 /// '\#pragma clang attribute push' directives to the given declaration.
2315 void AddPragmaAttributes(Scope *S, Decl *D);
2316
2317 using InstantiationContextDiagFuncRef =
2318 llvm::function_ref<void(SourceLocation, PartialDiagnostic)>;
2319 auto getDefaultDiagFunc() {
2320 return [this](SourceLocation Loc, PartialDiagnostic PD) {
2321 // This bypasses a lot of the filters in the diag engine, as it's
2322 // to be used to attach notes to diagnostics which have already
2323 // been filtered through.
2324 DiagnosticBuilder Builder(Diags.Report(Loc, DiagID: PD.getDiagID()));
2325 PD.Emit(DB: Builder);
2326 };
2327 }
2328
2329 void PrintPragmaAttributeInstantiationPoint(
2330 InstantiationContextDiagFuncRef DiagFunc);
2331 void PrintPragmaAttributeInstantiationPoint() {
2332 PrintPragmaAttributeInstantiationPoint(DiagFunc: getDefaultDiagFunc());
2333 }
2334
2335 void DiagnoseUnterminatedPragmaAttribute();
2336
2337 /// Called on well formed \#pragma clang optimize.
2338 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
2339
2340 /// #pragma optimize("[optimization-list]", on | off).
2341 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn);
2342
2343 /// Call on well formed \#pragma function.
2344 void
2345 ActOnPragmaMSFunction(SourceLocation Loc,
2346 const llvm::SmallVectorImpl<StringRef> &NoBuiltins);
2347
2348 NamedDecl *lookupExternCFunctionOrVariable(IdentifierInfo *IdentId,
2349 SourceLocation NameLoc,
2350 Scope *curScope);
2351
2352 /// Information from a C++ #pragma export, for a symbol that we
2353 /// haven't seen the declaration for yet.
2354 struct PendingPragmaInfo {
2355 SourceLocation NameLoc;
2356 bool Used;
2357 };
2358
2359 llvm::DenseMap<IdentifierInfo *, PendingPragmaInfo> PendingExportedNames;
2360
2361 /// ActonPragmaExport - called on well-formed '\#pragma export'.
2362 void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
2363 Scope *curScope);
2364
2365 /// Only called on function definitions; if there is a pragma in scope
2366 /// with the effect of a range-based optnone, consider marking the function
2367 /// with attribute optnone.
2368 void AddRangeBasedOptnone(FunctionDecl *FD);
2369
2370 /// Only called on function definitions; if there is a `#pragma alloc_text`
2371 /// that decides which code section the function should be in, add
2372 /// attribute section to the function.
2373 void AddSectionMSAllocText(FunctionDecl *FD);
2374
2375 /// Adds the 'optnone' attribute to the function declaration if there
2376 /// are no conflicts; Loc represents the location causing the 'optnone'
2377 /// attribute to be added (usually because of a pragma).
2378 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
2379
2380 /// Only called on function definitions; if there is a MSVC #pragma optimize
2381 /// in scope, consider changing the function's attributes based on the
2382 /// optimization list passed to the pragma.
2383 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD);
2384
2385 /// Only called on function definitions; if there is a pragma in scope
2386 /// with the effect of a range-based no_builtin, consider marking the function
2387 /// with attribute no_builtin.
2388 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD);
2389
2390 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
2391 /// add an appropriate visibility attribute.
2392 void AddPushedVisibilityAttribute(Decl *RD);
2393
2394 /// FreeVisContext - Deallocate and null out VisContext.
2395 void FreeVisContext();
2396
2397 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
2398 void ActOnPragmaVisibility(const IdentifierInfo *VisType,
2399 SourceLocation PragmaLoc);
2400
2401 /// ActOnPragmaFPContract - Called on well formed
2402 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
2403 /// \#pragma clang fp contract
2404 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
2405
2406 /// Called on well formed
2407 /// \#pragma clang fp reassociate
2408 /// or
2409 /// \#pragma clang fp reciprocal
2410 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind,
2411 bool IsEnabled);
2412
2413 /// ActOnPragmaFenvAccess - Called on well formed
2414 /// \#pragma STDC FENV_ACCESS
2415 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
2416
2417 /// ActOnPragmaCXLimitedRange - Called on well formed
2418 /// \#pragma STDC CX_LIMITED_RANGE
2419 void ActOnPragmaCXLimitedRange(SourceLocation Loc,
2420 LangOptions::ComplexRangeKind Range);
2421
2422 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
2423 void ActOnPragmaFPExceptions(SourceLocation Loc,
2424 LangOptions::FPExceptionModeKind);
2425
2426 /// Called to set constant rounding mode for floating point operations.
2427 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode);
2428
2429 /// Called to set exception behavior for floating point operations.
2430 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
2431
2432 /// PushNamespaceVisibilityAttr - Note that we've entered a
2433 /// namespace with a visibility attribute.
2434 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
2435 SourceLocation Loc);
2436
2437 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
2438 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
2439 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
2440
2441 /// Handles semantic checking for features that are common to all attributes,
2442 /// such as checking whether a parameter was properly specified, or the
2443 /// correct number of arguments were passed, etc. Returns true if the
2444 /// attribute has been diagnosed.
2445 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
2446 bool SkipArgCountCheck = false);
2447 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
2448 bool SkipArgCountCheck = false);
2449
2450 ///@}
2451
2452 //
2453 //
2454 // -------------------------------------------------------------------------
2455 //
2456 //
2457
2458 /// \name Availability Attribute Handling
2459 /// Implementations are in SemaAvailability.cpp
2460 ///@{
2461
2462public:
2463 /// Issue any -Wunguarded-availability warnings in \c FD
2464 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
2465
2466 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
2467
2468 /// Retrieve the current function, if any, that should be analyzed for
2469 /// potential availability violations.
2470 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2471
2472 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
2473 const ObjCInterfaceDecl *UnknownObjCClass,
2474 bool ObjCPropertyAccess,
2475 bool AvoidPartialAvailabilityChecks,
2476 ObjCInterfaceDecl *ClassReceiver);
2477
2478 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs);
2479
2480 std::pair<AvailabilityResult, const NamedDecl *>
2481 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message,
2482 ObjCInterfaceDecl *ClassReceiver);
2483 ///@}
2484
2485 //
2486 //
2487 // -------------------------------------------------------------------------
2488 //
2489 //
2490
2491 /// \name Bounds Safety
2492 /// Implementations are in SemaBoundsSafety.cpp
2493 ///@{
2494public:
2495 /// Check if applying the specified attribute variant from the "counted by"
2496 /// family of attributes to FieldDecl \p FD is semantically valid. If
2497 /// semantically invalid diagnostics will be emitted explaining the problems.
2498 ///
2499 /// \param FD The FieldDecl to apply the attribute to
2500 /// \param E The count expression on the attribute
2501 /// \param CountInBytes If true the attribute is from the "sized_by" family of
2502 /// attributes. If the false the attribute is from
2503 /// "counted_by" family of attributes.
2504 /// \param OrNull If true the attribute is from the "_or_null" suffixed family
2505 /// of attributes. If false the attribute does not have the
2506 /// suffix.
2507 ///
2508 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g.
2509 /// \p CountInBytes and \p OrNull both being true indicates the
2510 /// `counted_by_or_null` attribute.
2511 ///
2512 /// \returns false iff semantically valid.
2513 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes,
2514 bool OrNull);
2515
2516 /// Perform Bounds Safety Semantic checks for assigning to a `__counted_by` or
2517 /// `__counted_by_or_null` pointer type \param LHSTy.
2518 ///
2519 /// \param LHSTy The type being assigned to. Checks will only be performed if
2520 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2521 /// \param RHSExpr The expression being assigned from.
2522 /// \param Action The type assignment being performed
2523 /// \param Loc The SourceLocation to use for error diagnostics
2524 /// \param Assignee The ValueDecl being assigned. This is used to compute
2525 /// the name of the assignee. If the assignee isn't known this can
2526 /// be set to nullptr.
2527 /// \param ShowFullyQualifiedAssigneeName If set to true when using \p
2528 /// Assignee to compute the name of the assignee use the fully
2529 /// qualified name, otherwise use the unqualified name.
2530 ///
2531 /// \returns True iff no diagnostic where emitted, false otherwise.
2532 bool BoundsSafetyCheckAssignmentToCountAttrPtr(
2533 QualType LHSTy, Expr *RHSExpr, AssignmentAction Action,
2534 SourceLocation Loc, const ValueDecl *Assignee,
2535 bool ShowFullyQualifiedAssigneeName);
2536
2537 /// Perform Bounds Safety Semantic checks for initializing a Bounds Safety
2538 /// pointer.
2539 ///
2540 /// \param Entity The entity being initialized
2541 /// \param Kind The kind of initialization being performed
2542 /// \param Action The type assignment being performed
2543 /// \param LHSTy The type being assigned to. Checks will only be performed if
2544 /// the type is a `counted_by` or `counted_by_or_null ` pointer.
2545 /// \param RHSExpr The expression being used for initialization.
2546 ///
2547 /// \returns True iff no diagnostic where emitted, false otherwise.
2548 bool BoundsSafetyCheckInitialization(const InitializedEntity &Entity,
2549 const InitializationKind &Kind,
2550 AssignmentAction Action,
2551 QualType LHSType, Expr *RHSExpr);
2552
2553 /// Perform Bounds Safety semantic checks for uses of invalid uses counted_by
2554 /// or counted_by_or_null pointers in \param E.
2555 ///
2556 /// \param E the expression to check
2557 ///
2558 /// \returns True iff no diagnostic where emitted, false otherwise.
2559 bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E);
2560 ///@}
2561
2562 //
2563 //
2564 // -------------------------------------------------------------------------
2565 //
2566 //
2567
2568 /// \name Casts
2569 /// Implementations are in SemaCast.cpp
2570 ///@{
2571
2572public:
2573 static bool isCast(CheckedConversionKind CCK) {
2574 return CCK == CheckedConversionKind::CStyleCast ||
2575 CCK == CheckedConversionKind::FunctionalCast ||
2576 CCK == CheckedConversionKind::OtherCast;
2577 }
2578
2579 /// ActOnCXXNamedCast - Parse
2580 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
2581 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2582 SourceLocation LAngleBracketLoc, Declarator &D,
2583 SourceLocation RAngleBracketLoc,
2584 SourceLocation LParenLoc, Expr *E,
2585 SourceLocation RParenLoc);
2586
2587 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
2588 TypeSourceInfo *Ty, Expr *E,
2589 SourceRange AngleBrackets, SourceRange Parens);
2590
2591 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
2592 ExprResult Operand,
2593 SourceLocation RParenLoc);
2594
2595 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
2596 Expr *Operand, SourceLocation RParenLoc);
2597
2598 // Checks that reinterpret casts don't have undefined behavior.
2599 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2600 bool IsDereference, SourceRange Range);
2601
2602 // Checks that the vector type should be initialized from a scalar
2603 // by splatting the value rather than populating a single element.
2604 // This is the case for AltiVecVector types as well as with
2605 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
2606 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
2607
2608 // Checks if the -faltivec-src-compat=gcc option is specified.
2609 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
2610 // treated the same way as they are when trying to initialize
2611 // these vectors on gcc (an error is emitted).
2612 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2613 QualType SrcTy);
2614
2615 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
2616 SourceLocation RParenLoc, Expr *Op);
2617
2618 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
2619 SourceLocation LParenLoc,
2620 Expr *CastExpr,
2621 SourceLocation RParenLoc);
2622
2623 ///@}
2624
2625 //
2626 //
2627 // -------------------------------------------------------------------------
2628 //
2629 //
2630
2631 /// \name Extra Semantic Checking
2632 /// Implementations are in SemaChecking.cpp
2633 ///@{
2634
2635public:
2636 /// Used to change context to isConstantEvaluated without pushing a heavy
2637 /// ExpressionEvaluationContextRecord object.
2638 bool isConstantEvaluatedOverride = false;
2639
2640 bool isConstantEvaluatedContext() const {
2641 return currentEvaluationContext().isConstantEvaluated() ||
2642 isConstantEvaluatedOverride;
2643 }
2644
2645 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
2646 unsigned ByteNo) const;
2647
2648 enum FormatArgumentPassingKind {
2649 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments)
2650 FAPK_Variadic, // values to format are passed as variadic arguments
2651 FAPK_VAList, // values to format are passed in a va_list
2652 FAPK_Elsewhere, // values to format are not passed to this function
2653 };
2654
2655 // Used to grab the relevant information from a FormatAttr and a
2656 // FunctionDeclaration.
2657 struct FormatStringInfo {
2658 unsigned FormatIdx;
2659 unsigned FirstDataArg;
2660 FormatArgumentPassingKind ArgPassingKind;
2661 };
2662
2663 /// Given a function and its FormatAttr or FormatMatchesAttr info, attempts to
2664 /// populate the FormatStringInfo parameter with the attribute's correct
2665 /// format_idx and firstDataArg. Returns true when the format fits the
2666 /// function and the FormatStringInfo has been populated.
2667 static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx,
2668 unsigned FirstArg, FormatStringInfo *FSI);
2669 static bool getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
2670 bool HasImplicitThisParam, bool IsVariadic,
2671 FormatStringInfo *FSI);
2672
2673 // Used by C++ template instantiation.
2674 ExprResult BuiltinShuffleVector(CallExpr *TheCall);
2675
2676 /// ConvertVectorExpr - Handle __builtin_convertvector
2677 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2678 SourceLocation BuiltinLoc,
2679 SourceLocation RParenLoc);
2680
2681 static StringRef GetFormatStringTypeName(FormatStringType FST);
2682 static FormatStringType GetFormatStringType(StringRef FormatFlavor);
2683 static FormatStringType GetFormatStringType(const FormatAttr *Format);
2684 static FormatStringType GetFormatStringType(const FormatMatchesAttr *Format);
2685
2686 bool FormatStringHasSArg(const StringLiteral *FExpr);
2687
2688 /// Check for comparisons of floating-point values using == and !=. Issue a
2689 /// warning if the comparison is not likely to do what the programmer
2690 /// intended.
2691 void CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
2692 const Expr *RHS, BinaryOperatorKind Opcode);
2693
2694 /// Register a magic integral constant to be used as a type tag.
2695 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
2696 uint64_t MagicValue, QualType Type,
2697 bool LayoutCompatible, bool MustBeNull);
2698
2699 struct TypeTagData {
2700 TypeTagData() {}
2701
2702 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull)
2703 : Type(Type), LayoutCompatible(LayoutCompatible),
2704 MustBeNull(MustBeNull) {}
2705
2706 QualType Type;
2707
2708 /// If true, \c Type should be compared with other expression's types for
2709 /// layout-compatibility.
2710 LLVM_PREFERRED_TYPE(bool)
2711 unsigned LayoutCompatible : 1;
2712 LLVM_PREFERRED_TYPE(bool)
2713 unsigned MustBeNull : 1;
2714 };
2715
2716 /// A pair of ArgumentKind identifier and magic value. This uniquely
2717 /// identifies the magic value.
2718 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
2719
2720 /// Diagnoses the current set of gathered accesses. This happens at the end of
2721 /// each expression evaluation context. Diagnostics are emitted only for
2722 /// accesses gathered in the current evaluation context.
2723 void DiagnoseMisalignedMembers();
2724
2725 /// This function checks if the expression is in the sef of potentially
2726 /// misaligned members and it is converted to some pointer type T with lower
2727 /// or equal alignment requirements. If so it removes it. This is used when
2728 /// we do not want to diagnose such misaligned access (e.g. in conversions to
2729 /// void*).
2730 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
2731
2732 /// Returns true if `From` is a function or pointer to a function with the
2733 /// `cfi_unchecked_callee` attribute but `To` is a function or pointer to
2734 /// function without this attribute.
2735 bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const;
2736
2737 /// This function calls Action when it determines that E designates a
2738 /// misaligned member due to the packed attribute. This is used to emit
2739 /// local diagnostics like in reference binding.
2740 void RefersToMemberWithReducedAlignment(
2741 Expr *E,
2742 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
2743 Action);
2744
2745 enum class AtomicArgumentOrder { API, AST };
2746 ExprResult
2747 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
2748 SourceLocation RParenLoc, MultiExprArg Args,
2749 AtomicExpr::AtomicOp Op,
2750 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
2751
2752 /// Check to see if a given expression could have '.c_str()' called on it.
2753 bool hasCStrMethod(const Expr *E);
2754
2755 /// Diagnose pointers that are always non-null.
2756 /// \param E the expression containing the pointer
2757 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
2758 /// compared to a null pointer
2759 /// \param IsEqual True when the comparison is equal to a null pointer
2760 /// \param Range Extra SourceRange to highlight in the diagnostic
2761 void DiagnoseAlwaysNonNullPointer(Expr *E,
2762 Expr::NullPointerConstantKind NullType,
2763 bool IsEqual, SourceRange Range);
2764
2765 /// CheckParmsForFunctionDef - Check that the parameters of the given
2766 /// function are appropriate for the definition of a function. This
2767 /// takes care of any checks that cannot be performed on the
2768 /// declaration itself, e.g., that the types of each of the function
2769 /// parameters are complete.
2770 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2771 bool CheckParameterNames);
2772
2773 /// CheckCastAlign - Implements -Wcast-align, which warns when a
2774 /// pointer cast increases the alignment requirements.
2775 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2776
2777 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
2778 /// to weak/__unsafe_unretained type.
2779 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
2780
2781 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
2782 /// to weak/__unsafe_unretained expression.
2783 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
2784
2785 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
2786 /// statement as a \p Body, and it is located on the same line.
2787 ///
2788 /// This helps prevent bugs due to typos, such as:
2789 /// if (condition);
2790 /// do_stuff();
2791 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body,
2792 unsigned DiagID);
2793
2794 /// Warn if a for/while loop statement \p S, which is followed by
2795 /// \p PossibleBody, has a suspicious null statement as a body.
2796 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody);
2797
2798 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
2799 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
2800 SourceLocation OpLoc);
2801
2802 bool IsLayoutCompatible(QualType T1, QualType T2) const;
2803 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
2804 const TypeSourceInfo *Derived);
2805
2806 /// CheckFunctionCall - Check a direct function call for various correctness
2807 /// and safety properties not strictly enforced by the C type system.
2808 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2809 const FunctionProtoType *Proto);
2810
2811 enum class EltwiseBuiltinArgTyRestriction {
2812 None,
2813 FloatTy,
2814 IntegerTy,
2815 SignedIntOrFloatTy,
2816 };
2817
2818 /// \param FPOnly restricts the arguments to floating-point types.
2819 std::optional<QualType>
2820 BuiltinVectorMath(CallExpr *TheCall,
2821 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2822 EltwiseBuiltinArgTyRestriction::None);
2823 bool BuiltinVectorToScalarMath(CallExpr *TheCall);
2824
2825 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction,
2826 const Expr *ThisArg, ArrayRef<const Expr *> Args);
2827
2828 /// Handles the checks for format strings, non-POD arguments to vararg
2829 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if
2830 /// attributes and AArch64 SME attributes.
2831 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2832 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2833 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
2834 VariadicCallType CallType);
2835
2836 /// Verify that two format strings (as understood by attribute(format) and
2837 /// attribute(format_matches) are compatible. If they are incompatible,
2838 /// diagnostics are emitted with the assumption that \c
2839 /// AuthoritativeFormatString is correct and
2840 /// \c TestedFormatString is wrong. If \c FunctionCallArg is provided,
2841 /// diagnostics will point to it and a note will refer to \c
2842 /// TestedFormatString or \c AuthoritativeFormatString as appropriate.
2843 bool
2844 CheckFormatStringsCompatible(FormatStringType FST,
2845 const StringLiteral *AuthoritativeFormatString,
2846 const StringLiteral *TestedFormatString,
2847 const Expr *FunctionCallArg = nullptr);
2848
2849 /// Verify that one format string (as understood by attribute(format)) is
2850 /// self-consistent; for instance, that it doesn't have multiple positional
2851 /// arguments referring to the same argument in incompatible ways. Diagnose
2852 /// if it isn't.
2853 bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str);
2854
2855 /// \brief Enforce the bounds of a TCB
2856 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
2857 /// directly calls other functions in the same TCB as marked by the
2858 /// enforce_tcb and enforce_tcb_leaf attributes.
2859 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
2860 const NamedDecl *Callee);
2861
2862 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc);
2863
2864 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2865 /// TheCall is a constant expression.
2866 bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
2867 llvm::APSInt &Result);
2868
2869 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2870 /// TheCall is a constant expression in the range [Low, High].
2871 bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
2872 int High, bool RangeIsError = true);
2873
2874 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
2875 /// TheCall is a constant expression is a multiple of Num..
2876 bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
2877 unsigned Multiple);
2878
2879 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
2880 /// constant expression representing a power of 2.
2881 bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum);
2882
2883 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
2884 /// a constant expression representing an arbitrary byte value shifted left by
2885 /// a multiple of 8 bits.
2886 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
2887 unsigned ArgBits);
2888
2889 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
2890 /// TheCall is a constant expression representing either a shifted byte value,
2891 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
2892 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
2893 /// Arm MVE intrinsics.
2894 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum,
2895 unsigned ArgBits);
2896
2897 /// Checks that a call expression's argument count is at least the desired
2898 /// number. This is useful when doing custom type-checking on a variadic
2899 /// function. Returns true on error.
2900 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount);
2901
2902 /// Checks that a call expression's argument count is at most the desired
2903 /// number. This is useful when doing custom type-checking on a variadic
2904 /// function. Returns true on error.
2905 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount);
2906
2907 /// Checks that a call expression's argument count is in the desired range.
2908 /// This is useful when doing custom type-checking on a variadic function.
2909 /// Returns true on error.
2910 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
2911 unsigned MaxArgCount);
2912
2913 /// Checks that a call expression's argument count is the desired number.
2914 /// This is useful when doing custom type-checking. Returns true on error.
2915 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount);
2916
2917 /// Returns true if the argument consists of one contiguous run of 1s with any
2918 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB,
2919 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
2920 /// since all 1s are not contiguous.
2921 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
2922
2923 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
2924 bool *ICContext = nullptr,
2925 bool IsListInit = false);
2926
2927 /// Check for overflow behavior type related implicit conversion diagnostics.
2928 /// Returns true if OBT-related diagnostic was issued, false otherwise.
2929 bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
2930 SourceLocation CC);
2931
2932 bool
2933 BuiltinElementwiseTernaryMath(CallExpr *TheCall,
2934 EltwiseBuiltinArgTyRestriction ArgTyRestr =
2935 EltwiseBuiltinArgTyRestriction::FloatTy);
2936 bool PrepareBuiltinElementwiseMathOneArgCall(
2937 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr =
2938 EltwiseBuiltinArgTyRestriction::None);
2939
2940private:
2941 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
2942 const ArraySubscriptExpr *ASE = nullptr,
2943 bool AllowOnePastEnd = true, bool IndexNegated = false);
2944 void CheckArrayAccess(const Expr *E);
2945
2946 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2947 const FunctionProtoType *Proto);
2948
2949 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2950 /// such as function pointers returned from functions.
2951 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
2952
2953 /// CheckConstructorCall - Check a constructor call for correctness and safety
2954 /// properties not enforced by the C type system.
2955 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
2956 ArrayRef<const Expr *> Args,
2957 const FunctionProtoType *Proto, SourceLocation Loc);
2958
2959 /// Warn if a pointer or reference argument passed to a function points to an
2960 /// object that is less aligned than the parameter. This can happen when
2961 /// creating a typedef with a lower alignment than the original type and then
2962 /// calling functions defined in terms of the original type.
2963 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
2964 StringRef ParamName, QualType ArgTy, QualType ParamTy);
2965
2966 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
2967
2968 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2969 CallExpr *TheCall);
2970
2971 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2972 CallExpr *TheCall);
2973
2974 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
2975
2976 /// Check the arguments to '__builtin_va_start', '__builtin_ms_va_start',
2977 /// or '__builtin_c23_va_start' for validity. Emit an error and return true
2978 /// on failure; return false on success.
2979 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
2980 bool BuiltinVAStartARMMicrosoft(CallExpr *Call);
2981
2982 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2983 /// friends. This is declared to take (...), so we have to check everything.
2984 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID);
2985
2986 /// BuiltinSemaBuiltinFPClassification - Handle functions like
2987 /// __builtin_isnan and friends. This is declared to take (...), so we have
2988 /// to check everything.
2989 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
2990 unsigned BuiltinID);
2991
2992 /// Perform semantic analysis for a call to __builtin_complex.
2993 bool BuiltinComplex(CallExpr *TheCall);
2994 bool BuiltinOSLogFormat(CallExpr *TheCall);
2995
2996 /// BuiltinPrefetch - Handle __builtin_prefetch.
2997 /// This is declared to take (const void*, ...) and can take two
2998 /// optional constant int args.
2999 bool BuiltinPrefetch(CallExpr *TheCall);
3000
3001 /// Handle __builtin_alloca_with_align. This is declared
3002 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
3003 /// than 8.
3004 bool BuiltinAllocaWithAlign(CallExpr *TheCall);
3005
3006 /// BuiltinArithmeticFence - Handle __arithmetic_fence.
3007 bool BuiltinArithmeticFence(CallExpr *TheCall);
3008
3009 /// BuiltinAssume - Handle __assume (MS Extension).
3010 /// __assume does not evaluate its arguments, and should warn if its argument
3011 /// has side effects.
3012 bool BuiltinAssume(CallExpr *TheCall);
3013
3014 /// Handle __builtin_assume_aligned. This is declared
3015 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3016 bool BuiltinAssumeAligned(CallExpr *TheCall);
3017
3018 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3019 /// This checks that the target supports __builtin_longjmp and
3020 /// that val is a constant 1.
3021 bool BuiltinLongjmp(CallExpr *TheCall);
3022
3023 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3024 /// This checks that the target supports __builtin_setjmp.
3025 bool BuiltinSetjmp(CallExpr *TheCall);
3026
3027 /// We have a call to a function like __sync_fetch_and_add, which is an
3028 /// overloaded function based on the pointer type of its first argument.
3029 /// The main BuildCallExpr routines have already promoted the types of
3030 /// arguments because all of these calls are prototyped as void(...).
3031 ///
3032 /// This function goes through and does final semantic checking for these
3033 /// builtins, as well as generating any warnings.
3034 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult);
3035
3036 /// BuiltinNontemporalOverloaded - We have a call to
3037 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3038 /// overloaded function based on the pointer type of its last argument.
3039 ///
3040 /// This function goes through and does final semantic checking for these
3041 /// builtins.
3042 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult);
3043 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult,
3044 AtomicExpr::AtomicOp Op);
3045
3046 /// \param FPOnly restricts the arguments to floating-point types.
3047 bool BuiltinElementwiseMath(CallExpr *TheCall,
3048 EltwiseBuiltinArgTyRestriction ArgTyRestr =
3049 EltwiseBuiltinArgTyRestriction::None);
3050 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
3051
3052 bool BuiltinNonDeterministicValue(CallExpr *TheCall);
3053
3054 bool CheckInvalidBuiltinCountedByRef(const Expr *E,
3055 BuiltinCountedByRefKind K);
3056 bool BuiltinCountedByRef(CallExpr *TheCall);
3057
3058 // Matrix builtin handling.
3059 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult);
3060 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
3061 ExprResult CallResult);
3062 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
3063 ExprResult CallResult);
3064
3065 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3066 /// functions) for correct use of format strings.
3067 /// Returns true if a format string has been fully checked.
3068 bool CheckFormatArguments(const FormatAttr *Format,
3069 ArrayRef<const Expr *> Args, bool IsCXXMember,
3070 VariadicCallType CallType, SourceLocation Loc,
3071 SourceRange Range,
3072 llvm::SmallBitVector &CheckedVarArgs);
3073 bool CheckFormatString(const FormatMatchesAttr *Format,
3074 ArrayRef<const Expr *> Args, bool IsCXXMember,
3075 VariadicCallType CallType, SourceLocation Loc,
3076 SourceRange Range,
3077 llvm::SmallBitVector &CheckedVarArgs);
3078 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
3079 FormatArgumentPassingKind FAPK,
3080 StringLiteral *ReferenceFormatString,
3081 unsigned format_idx, unsigned firstDataArg,
3082 FormatStringType Type, VariadicCallType CallType,
3083 SourceLocation Loc, SourceRange range,
3084 llvm::SmallBitVector &CheckedVarArgs);
3085
3086 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl);
3087
3088 /// Warn when using the wrong abs() function.
3089 void CheckAbsoluteValueFunction(const CallExpr *Call,
3090 const FunctionDecl *FDecl);
3091
3092 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
3093
3094 /// Check for dangerous or invalid arguments to memset().
3095 ///
3096 /// This issues warnings on known problematic, dangerous or unspecified
3097 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3098 /// function calls.
3099 ///
3100 /// \param Call The call expression to diagnose.
3101 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId,
3102 IdentifierInfo *FnName);
3103
3104 bool CheckSizeofMemaccessArgument(const Expr *SizeOfArg, const Expr *Dest,
3105 IdentifierInfo *FnName);
3106 // Warn if the user has made the 'size' argument to strlcpy or strlcat
3107 // be the size of the source, instead of the destination.
3108 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName);
3109
3110 // Warn on anti-patterns as the 'size' argument to strncat.
3111 // The correct size argument should look like following:
3112 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3113 void CheckStrncatArguments(const CallExpr *Call,
3114 const IdentifierInfo *FnName);
3115
3116 /// Alerts the user that they are attempting to free a non-malloc'd object.
3117 void CheckFreeArguments(const CallExpr *E);
3118
3119 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
3120 SourceLocation ReturnLoc, bool isObjCMethod = false,
3121 const AttrVec *Attrs = nullptr,
3122 const FunctionDecl *FD = nullptr);
3123
3124 /// Diagnoses "dangerous" implicit conversions within the given
3125 /// expression (which is a full expression). Implements -Wconversion
3126 /// and -Wsign-compare.
3127 ///
3128 /// \param CC the "context" location of the implicit conversion, i.e.
3129 /// the most location of the syntactic entity requiring the implicit
3130 /// conversion
3131 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
3132
3133 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
3134 /// Input argument E is a logical expression.
3135 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
3136
3137 /// Diagnose when expression is an integer constant expression and its
3138 /// evaluation results in integer overflow
3139 void CheckForIntOverflow(const Expr *E);
3140 void CheckUnsequencedOperations(const Expr *E);
3141
3142 /// Perform semantic checks on a completed expression. This will either
3143 /// be a full-expression or a default argument expression.
3144 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
3145 bool IsConstexpr = false);
3146
3147 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
3148 Expr *Init);
3149
3150 /// A map from magic value to type information.
3151 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
3152 TypeTagForDatatypeMagicValues;
3153
3154 /// Peform checks on a call of a function with argument_with_type_tag
3155 /// or pointer_with_type_tag attributes.
3156 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
3157 const ArrayRef<const Expr *> ExprArgs,
3158 SourceLocation CallSiteLoc);
3159
3160 /// Check if we are taking the address of a packed field
3161 /// as this may be a problem if the pointer value is dereferenced.
3162 void CheckAddressOfPackedMember(Expr *rhs);
3163
3164 /// Helper class that collects misaligned member designations and
3165 /// their location info for delayed diagnostics.
3166 struct MisalignedMember {
3167 Expr *E;
3168 RecordDecl *RD;
3169 ValueDecl *MD;
3170 CharUnits Alignment;
3171
3172 MisalignedMember() : E(), RD(), MD() {}
3173 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
3174 CharUnits Alignment)
3175 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
3176 explicit MisalignedMember(Expr *E)
3177 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
3178
3179 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
3180 };
3181
3182 /// Adds an expression to the set of gathered misaligned members.
3183 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
3184 CharUnits Alignment);
3185 ///@}
3186
3187 //
3188 //
3189 // -------------------------------------------------------------------------
3190 //
3191 //
3192
3193 /// \name C++ Coroutines
3194 /// Implementations are in SemaCoroutine.cpp
3195 ///@{
3196
3197public:
3198 /// The C++ "std::coroutine_traits" template, which is defined in
3199 /// \<coroutine_traits>
3200 ClassTemplateDecl *StdCoroutineTraitsCache;
3201
3202 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
3203 StringRef Keyword);
3204 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3205 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
3206 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
3207
3208 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc);
3209 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
3210 UnresolvedLookupExpr *Lookup);
3211 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3212 Expr *Awaiter, bool IsImplicit = false);
3213 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand,
3214 UnresolvedLookupExpr *Lookup);
3215 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
3216 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
3217 bool IsImplicit = false);
3218 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
3219 bool buildCoroutineParameterMoves(SourceLocation Loc);
3220 VarDecl *buildCoroutinePromise(SourceLocation Loc);
3221 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
3222
3223 // As a clang extension, enforces that a non-coroutine function must be marked
3224 // with [[clang::coro_wrapper]] if it returns a type marked with
3225 // [[clang::coro_return_type]].
3226 // Expects that FD is not a coroutine.
3227 void CheckCoroutineWrapper(FunctionDecl *FD);
3228 /// Lookup 'coroutine_traits' in std namespace and std::experimental
3229 /// namespace. The namespace found is recorded in Namespace.
3230 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
3231 SourceLocation FuncLoc);
3232 /// Check that the expression co_await promise.final_suspend() shall not be
3233 /// potentially-throwing.
3234 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
3235
3236 ///@}
3237
3238 //
3239 //
3240 // -------------------------------------------------------------------------
3241 //
3242 //
3243
3244 /// \name C++ Scope Specifiers
3245 /// Implementations are in SemaCXXScopeSpec.cpp
3246 ///@{
3247
3248public:
3249 // Marks SS invalid if it represents an incomplete type.
3250 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
3251 // Complete an enum decl, maybe without a scope spec.
3252 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
3253 CXXScopeSpec *SS = nullptr);
3254
3255 /// Compute the DeclContext that is associated with the given type.
3256 ///
3257 /// \param T the type for which we are attempting to find a DeclContext.
3258 ///
3259 /// \returns the declaration context represented by the type T,
3260 /// or NULL if the declaration context cannot be computed (e.g., because it is
3261 /// dependent and not the current instantiation).
3262 DeclContext *computeDeclContext(QualType T);
3263
3264 /// Compute the DeclContext that is associated with the given
3265 /// scope specifier.
3266 ///
3267 /// \param SS the C++ scope specifier as it appears in the source
3268 ///
3269 /// \param EnteringContext when true, we will be entering the context of
3270 /// this scope specifier, so we can retrieve the declaration context of a
3271 /// class template or class template partial specialization even if it is
3272 /// not the current instantiation.
3273 ///
3274 /// \returns the declaration context represented by the scope specifier @p SS,
3275 /// or NULL if the declaration context cannot be computed (e.g., because it is
3276 /// dependent and not the current instantiation).
3277 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
3278 bool EnteringContext = false);
3279 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
3280
3281 /// If the given nested name specifier refers to the current
3282 /// instantiation, return the declaration that corresponds to that
3283 /// current instantiation (C++0x [temp.dep.type]p1).
3284 ///
3285 /// \param NNS a dependent nested name specifier.
3286 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier NNS);
3287
3288 /// The parser has parsed a global nested-name-specifier '::'.
3289 ///
3290 /// \param CCLoc The location of the '::'.
3291 ///
3292 /// \param SS The nested-name-specifier, which will be updated in-place
3293 /// to reflect the parsed nested-name-specifier.
3294 ///
3295 /// \returns true if an error occurred, false otherwise.
3296 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
3297
3298 /// The parser has parsed a '__super' nested-name-specifier.
3299 ///
3300 /// \param SuperLoc The location of the '__super' keyword.
3301 ///
3302 /// \param ColonColonLoc The location of the '::'.
3303 ///
3304 /// \param SS The nested-name-specifier, which will be updated in-place
3305 /// to reflect the parsed nested-name-specifier.
3306 ///
3307 /// \returns true if an error occurred, false otherwise.
3308 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
3309 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
3310
3311 /// Determines whether the given declaration is an valid acceptable
3312 /// result for name lookup of a nested-name-specifier.
3313 /// \param SD Declaration checked for nested-name-specifier.
3314 /// \param IsExtension If not null and the declaration is accepted as an
3315 /// extension, the pointed variable is assigned true.
3316 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
3317 bool *CanCorrect = nullptr);
3318
3319 /// If the given nested-name-specifier begins with a bare identifier
3320 /// (e.g., Base::), perform name lookup for that identifier as a
3321 /// nested-name-specifier within the given scope, and return the result of
3322 /// that name lookup.
3323 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier NNS);
3324
3325 /// Keeps information about an identifier in a nested-name-spec.
3326 ///
3327 struct NestedNameSpecInfo {
3328 /// The type of the object, if we're parsing nested-name-specifier in
3329 /// a member access expression.
3330 ParsedType ObjectType;
3331
3332 /// The identifier preceding the '::'.
3333 IdentifierInfo *Identifier;
3334
3335 /// The location of the identifier.
3336 SourceLocation IdentifierLoc;
3337
3338 /// The location of the '::'.
3339 SourceLocation CCLoc;
3340
3341 /// Creates info object for the most typical case.
3342 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3343 SourceLocation ColonColonLoc,
3344 ParsedType ObjectType = ParsedType())
3345 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
3346 CCLoc(ColonColonLoc) {}
3347
3348 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
3349 SourceLocation ColonColonLoc, QualType ObjectType)
3350 : ObjectType(ParsedType::make(P: ObjectType)), Identifier(II),
3351 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {}
3352 };
3353
3354 /// Build a new nested-name-specifier for "identifier::", as described
3355 /// by ActOnCXXNestedNameSpecifier.
3356 ///
3357 /// \param S Scope in which the nested-name-specifier occurs.
3358 /// \param IdInfo Parser information about an identifier in the
3359 /// nested-name-spec.
3360 /// \param EnteringContext If true, enter the context specified by the
3361 /// nested-name-specifier.
3362 /// \param SS Optional nested name specifier preceding the identifier.
3363 /// \param ScopeLookupResult Provides the result of name lookup within the
3364 /// scope of the nested-name-specifier that was computed at template
3365 /// definition time.
3366 /// \param ErrorRecoveryLookup Specifies if the method is called to improve
3367 /// error recovery and what kind of recovery is performed.
3368 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
3369 /// are allowed. The bool value pointed by this parameter is set to
3370 /// 'true' if the identifier is treated as if it was followed by ':',
3371 /// not '::'.
3372 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3373 ///
3374 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
3375 /// that it contains an extra parameter \p ScopeLookupResult, which provides
3376 /// the result of name lookup within the scope of the nested-name-specifier
3377 /// that was computed at template definition time.
3378 ///
3379 /// If ErrorRecoveryLookup is true, then this call is used to improve error
3380 /// recovery. This means that it should not emit diagnostics, it should
3381 /// just return true on failure. It also means it should only return a valid
3382 /// scope if it *knows* that the result is correct. It should not return in a
3383 /// dependent context, for example. Nor will it extend \p SS with the scope
3384 /// specifier.
3385 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3386 bool EnteringContext, CXXScopeSpec &SS,
3387 NamedDecl *ScopeLookupResult,
3388 bool ErrorRecoveryLookup,
3389 bool *IsCorrectedToColon = nullptr,
3390 bool OnlyNamespace = false);
3391
3392 /// The parser has parsed a nested-name-specifier 'identifier::'.
3393 ///
3394 /// \param S The scope in which this nested-name-specifier occurs.
3395 ///
3396 /// \param IdInfo Parser information about an identifier in the
3397 /// nested-name-spec.
3398 ///
3399 /// \param EnteringContext Whether we're entering the context nominated by
3400 /// this nested-name-specifier.
3401 ///
3402 /// \param SS The nested-name-specifier, which is both an input
3403 /// parameter (the nested-name-specifier before this type) and an
3404 /// output parameter (containing the full nested-name-specifier,
3405 /// including this new type).
3406 ///
3407 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
3408 /// are allowed. The bool value pointed by this parameter is set to 'true'
3409 /// if the identifier is treated as if it was followed by ':', not '::'.
3410 ///
3411 /// \param OnlyNamespace If true, only considers namespaces in lookup.
3412 ///
3413 /// \returns true if an error occurred, false otherwise.
3414 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
3415 bool EnteringContext, CXXScopeSpec &SS,
3416 bool *IsCorrectedToColon = nullptr,
3417 bool OnlyNamespace = false);
3418
3419 /// The parser has parsed a nested-name-specifier
3420 /// 'template[opt] template-name < template-args >::'.
3421 ///
3422 /// \param S The scope in which this nested-name-specifier occurs.
3423 ///
3424 /// \param SS The nested-name-specifier, which is both an input
3425 /// parameter (the nested-name-specifier before this type) and an
3426 /// output parameter (containing the full nested-name-specifier,
3427 /// including this new type).
3428 ///
3429 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
3430 /// \param TemplateName the template name.
3431 /// \param TemplateNameLoc The location of the template name.
3432 /// \param LAngleLoc The location of the opening angle bracket ('<').
3433 /// \param TemplateArgs The template arguments.
3434 /// \param RAngleLoc The location of the closing angle bracket ('>').
3435 /// \param CCLoc The location of the '::'.
3436 ///
3437 /// \param EnteringContext Whether we're entering the context of the
3438 /// nested-name-specifier.
3439 ///
3440 ///
3441 /// \returns true if an error occurred, false otherwise.
3442 bool ActOnCXXNestedNameSpecifier(
3443 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3444 TemplateTy TemplateName, SourceLocation TemplateNameLoc,
3445 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
3446 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext);
3447
3448 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS,
3449 SourceLocation ColonColonLoc);
3450
3451 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS,
3452 const DeclSpec &DS,
3453 SourceLocation ColonColonLoc,
3454 QualType Type);
3455
3456 /// IsInvalidUnlessNestedName - This method is used for error recovery
3457 /// purposes to determine whether the specified identifier is only valid as
3458 /// a nested name specifier, for example a namespace name. It is
3459 /// conservatively correct to always return false from this method.
3460 ///
3461 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
3462 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
3463 NestedNameSpecInfo &IdInfo,
3464 bool EnteringContext);
3465
3466 /// Given a C++ nested-name-specifier, produce an annotation value
3467 /// that the parser can use later to reconstruct the given
3468 /// nested-name-specifier.
3469 ///
3470 /// \param SS A nested-name-specifier.
3471 ///
3472 /// \returns A pointer containing all of the information in the
3473 /// nested-name-specifier \p SS.
3474 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
3475
3476 /// Given an annotation pointer for a nested-name-specifier, restore
3477 /// the nested-name-specifier structure.
3478 ///
3479 /// \param Annotation The annotation pointer, produced by
3480 /// \c SaveNestedNameSpecifierAnnotation().
3481 ///
3482 /// \param AnnotationRange The source range corresponding to the annotation.
3483 ///
3484 /// \param SS The nested-name-specifier that will be updated with the contents
3485 /// of the annotation pointer.
3486 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
3487 SourceRange AnnotationRange,
3488 CXXScopeSpec &SS);
3489
3490 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3491
3492 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
3493 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
3494 /// After this method is called, according to [C++ 3.4.3p3], names should be
3495 /// looked up in the declarator-id's scope, until the declarator is parsed and
3496 /// ActOnCXXExitDeclaratorScope is called.
3497 /// The 'SS' should be a non-empty valid CXXScopeSpec.
3498 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
3499
3500 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
3501 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
3502 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
3503 /// Used to indicate that names should revert to being looked up in the
3504 /// defining scope.
3505 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
3506
3507 ///@}
3508
3509 //
3510 //
3511 // -------------------------------------------------------------------------
3512 //
3513 //
3514
3515 /// \name Declarations
3516 /// Implementations are in SemaDecl.cpp
3517 ///@{
3518
3519public:
3520 IdentifierResolver IdResolver;
3521
3522 /// The index of the first InventedParameterInfo that refers to the current
3523 /// context.
3524 unsigned InventedParameterInfosStart = 0;
3525
3526 /// A RAII object to temporarily push a declaration context.
3527 class ContextRAII {
3528 private:
3529 Sema &S;
3530 DeclContext *SavedContext;
3531 ProcessingContextState SavedContextState;
3532 QualType SavedCXXThisTypeOverride;
3533 unsigned SavedFunctionScopesStart;
3534 unsigned SavedInventedParameterInfosStart;
3535
3536 public:
3537 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
3538 : S(S), SavedContext(S.CurContext),
3539 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
3540 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
3541 SavedFunctionScopesStart(S.FunctionScopesStart),
3542 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) {
3543 assert(ContextToPush && "pushing null context");
3544 S.CurContext = ContextToPush;
3545 if (NewThisContext)
3546 S.CXXThisTypeOverride = QualType();
3547 // Any saved FunctionScopes do not refer to this context.
3548 S.FunctionScopesStart = S.FunctionScopes.size();
3549 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
3550 }
3551
3552 void pop() {
3553 if (!SavedContext)
3554 return;
3555 S.CurContext = SavedContext;
3556 S.DelayedDiagnostics.popUndelayed(state: SavedContextState);
3557 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
3558 S.FunctionScopesStart = SavedFunctionScopesStart;
3559 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
3560 SavedContext = nullptr;
3561 }
3562
3563 ~ContextRAII() { pop(); }
3564 ContextRAII(const ContextRAII &) = delete;
3565 ContextRAII &operator=(const ContextRAII &) = delete;
3566 };
3567
3568 void DiagnoseInvalidJumps(Stmt *Body);
3569
3570 /// The function definitions which were renamed as part of typo-correction
3571 /// to match their respective declarations. We want to keep track of them
3572 /// to ensure that we don't emit a "redefinition" error if we encounter a
3573 /// correctly named definition after the renamed definition.
3574 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
3575
3576 /// A cache of the flags available in enumerations with the flag_bits
3577 /// attribute.
3578 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache;
3579
3580 /// A cache of enumerator values for enums checked by -Wassign-enum.
3581 llvm::DenseMap<const EnumDecl *, llvm::SmallVector<llvm::APSInt>>
3582 AssignEnumCache;
3583
3584 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
3585 /// declared. Rare. May alias another identifier, declared or undeclared.
3586 ///
3587 /// For aliases, the target identifier is used as a key for eventual
3588 /// processing when the target is declared. For the single-identifier form,
3589 /// the sole identifier is used as the key. Each entry is a `SetVector`
3590 /// (ordered by parse order) of aliases (identified by the alias name) in case
3591 /// of multiple aliases to the same undeclared identifier.
3592 llvm::MapVector<
3593 IdentifierInfo *,
3594 llvm::SetVector<
3595 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
3596 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
3597 WeakUndeclaredIdentifiers;
3598
3599 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
3600 /// \#pragma redefine_extname before declared. Used in Solaris system headers
3601 /// to define functions that occur in multiple standards to call the version
3602 /// in the currently selected standard.
3603 llvm::MapVector<IdentifierInfo *, AsmLabelAttr *>
3604 ExtnameUndeclaredIdentifiers;
3605
3606 /// Set containing all typedefs that are likely unused.
3607 llvm::SmallSetVector<const TypedefNameDecl *, 4>
3608 UnusedLocalTypedefNameCandidates;
3609
3610 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
3611 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
3612 UnusedFileScopedDeclsType;
3613
3614 /// The set of file scoped decls seen so far that have not been used
3615 /// and must warn if not used. Only contains the first declaration.
3616 UnusedFileScopedDeclsType UnusedFileScopedDecls;
3617
3618 typedef LazyVector<VarDecl *, ExternalSemaSource,
3619 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
3620 TentativeDefinitionsType;
3621
3622 /// All the tentative definitions encountered in the TU.
3623 TentativeDefinitionsType TentativeDefinitions;
3624
3625 /// All the external declarations encoutered and used in the TU.
3626 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;
3627
3628 /// Generally null except when we temporarily switch decl contexts,
3629 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
3630 DeclContext *OriginalLexicalContext;
3631
3632 /// Is the module scope we are in a C++ Header Unit?
3633 bool currentModuleIsHeaderUnit() const {
3634 return ModuleScopes.empty() ? false
3635 : ModuleScopes.back().Module->isHeaderUnit();
3636 }
3637
3638 /// Get the module owning an entity.
3639 Module *getOwningModule(const Decl *Entity) {
3640 return Entity->getOwningModule();
3641 }
3642
3643 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
3644
3645 enum class DiagCtorKind { None, Implicit, Typename };
3646 /// Returns the TypeDeclType for the given type declaration,
3647 /// as ASTContext::getTypeDeclType would, but
3648 /// performs the required semantic checks for name lookup of said entity.
3649 void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD,
3650 SourceLocation NameLoc);
3651
3652 /// If the identifier refers to a type name within this scope,
3653 /// return the declaration of that type.
3654 ///
3655 /// This routine performs ordinary name lookup of the identifier II
3656 /// within the given scope, with optional C++ scope specifier SS, to
3657 /// determine whether the name refers to a type. If so, returns an
3658 /// opaque pointer (actually a QualType) corresponding to that
3659 /// type. Otherwise, returns NULL.
3660 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
3661 Scope *S, CXXScopeSpec *SS = nullptr,
3662 bool isClassName = false, bool HasTrailingDot = false,
3663 ParsedType ObjectType = nullptr,
3664 bool IsCtorOrDtorName = false,
3665 bool WantNontrivialTypeSourceInfo = false,
3666 bool IsClassTemplateDeductionContext = true,
3667 ImplicitTypenameContext AllowImplicitTypename =
3668 ImplicitTypenameContext::No,
3669 IdentifierInfo **CorrectedII = nullptr);
3670
3671 /// isTagName() - This method is called *for error recovery purposes only*
3672 /// to determine if the specified name is a valid tag name ("struct foo"). If
3673 /// so, this returns the TST for the tag corresponding to it (TST_enum,
3674 /// TST_union, TST_struct, TST_interface, TST_class). This is used to
3675 /// diagnose cases in C where the user forgot to specify the tag.
3676 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
3677
3678 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
3679 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
3680 /// then downgrade the missing typename error to a warning.
3681 /// This is needed for MSVC compatibility; Example:
3682 /// @code
3683 /// template<class T> class A {
3684 /// public:
3685 /// typedef int TYPE;
3686 /// };
3687 /// template<class T> class B : public A<T> {
3688 /// public:
3689 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
3690 /// };
3691 /// @endcode
3692 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
3693 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc,
3694 Scope *S, CXXScopeSpec *SS,
3695 ParsedType &SuggestedType,
3696 bool IsTemplateName = false);
3697
3698 /// Attempt to behave like MSVC in situations where lookup of an unqualified
3699 /// type name has failed in a dependent context. In these situations, we
3700 /// automatically form a DependentTypeName that will retry lookup in a related
3701 /// scope during instantiation.
3702 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
3703 SourceLocation NameLoc,
3704 bool IsTemplateTypeArg);
3705
3706 class NameClassification {
3707 NameClassificationKind Kind;
3708 union {
3709 ExprResult Expr;
3710 NamedDecl *NonTypeDecl;
3711 TemplateName Template;
3712 ParsedType Type;
3713 };
3714
3715 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
3716
3717 public:
3718 NameClassification(ParsedType Type)
3719 : Kind(NameClassificationKind::Type), Type(Type) {}
3720
3721 NameClassification(const IdentifierInfo *Keyword)
3722 : Kind(NameClassificationKind::Keyword) {}
3723
3724 static NameClassification Error() {
3725 return NameClassification(NameClassificationKind::Error);
3726 }
3727
3728 static NameClassification Unknown() {
3729 return NameClassification(NameClassificationKind::Unknown);
3730 }
3731
3732 static NameClassification OverloadSet(ExprResult E) {
3733 NameClassification Result(NameClassificationKind::OverloadSet);
3734 Result.Expr = E;
3735 return Result;
3736 }
3737
3738 static NameClassification NonType(NamedDecl *D) {
3739 NameClassification Result(NameClassificationKind::NonType);
3740 Result.NonTypeDecl = D;
3741 return Result;
3742 }
3743
3744 static NameClassification UndeclaredNonType() {
3745 return NameClassification(NameClassificationKind::UndeclaredNonType);
3746 }
3747
3748 static NameClassification DependentNonType() {
3749 return NameClassification(NameClassificationKind::DependentNonType);
3750 }
3751
3752 static NameClassification TypeTemplate(TemplateName Name) {
3753 NameClassification Result(NameClassificationKind::TypeTemplate);
3754 Result.Template = Name;
3755 return Result;
3756 }
3757
3758 static NameClassification VarTemplate(TemplateName Name) {
3759 NameClassification Result(NameClassificationKind::VarTemplate);
3760 Result.Template = Name;
3761 return Result;
3762 }
3763
3764 static NameClassification FunctionTemplate(TemplateName Name) {
3765 NameClassification Result(NameClassificationKind::FunctionTemplate);
3766 Result.Template = Name;
3767 return Result;
3768 }
3769
3770 static NameClassification Concept(TemplateName Name) {
3771 NameClassification Result(NameClassificationKind::Concept);
3772 Result.Template = Name;
3773 return Result;
3774 }
3775
3776 static NameClassification UndeclaredTemplate(TemplateName Name) {
3777 NameClassification Result(NameClassificationKind::UndeclaredTemplate);
3778 Result.Template = Name;
3779 return Result;
3780 }
3781
3782 NameClassificationKind getKind() const { return Kind; }
3783
3784 ExprResult getExpression() const {
3785 assert(Kind == NameClassificationKind::OverloadSet);
3786 return Expr;
3787 }
3788
3789 ParsedType getType() const {
3790 assert(Kind == NameClassificationKind::Type);
3791 return Type;
3792 }
3793
3794 NamedDecl *getNonTypeDecl() const {
3795 assert(Kind == NameClassificationKind::NonType);
3796 return NonTypeDecl;
3797 }
3798
3799 TemplateName getTemplateName() const {
3800 assert(Kind == NameClassificationKind::TypeTemplate ||
3801 Kind == NameClassificationKind::FunctionTemplate ||
3802 Kind == NameClassificationKind::VarTemplate ||
3803 Kind == NameClassificationKind::Concept ||
3804 Kind == NameClassificationKind::UndeclaredTemplate);
3805 return Template;
3806 }
3807
3808 TemplateNameKind getTemplateNameKind() const {
3809 switch (Kind) {
3810 case NameClassificationKind::TypeTemplate:
3811 return TNK_Type_template;
3812 case NameClassificationKind::FunctionTemplate:
3813 return TNK_Function_template;
3814 case NameClassificationKind::VarTemplate:
3815 return TNK_Var_template;
3816 case NameClassificationKind::Concept:
3817 return TNK_Concept_template;
3818 case NameClassificationKind::UndeclaredTemplate:
3819 return TNK_Undeclared_template;
3820 default:
3821 llvm_unreachable("unsupported name classification.");
3822 }
3823 }
3824 };
3825
3826 /// Perform name lookup on the given name, classifying it based on
3827 /// the results of name lookup and the following token.
3828 ///
3829 /// This routine is used by the parser to resolve identifiers and help direct
3830 /// parsing. When the identifier cannot be found, this routine will attempt
3831 /// to correct the typo and classify based on the resulting name.
3832 ///
3833 /// \param S The scope in which we're performing name lookup.
3834 ///
3835 /// \param SS The nested-name-specifier that precedes the name.
3836 ///
3837 /// \param Name The identifier. If typo correction finds an alternative name,
3838 /// this pointer parameter will be updated accordingly.
3839 ///
3840 /// \param NameLoc The location of the identifier.
3841 ///
3842 /// \param NextToken The token following the identifier. Used to help
3843 /// disambiguate the name.
3844 ///
3845 /// \param CCC The correction callback, if typo correction is desired.
3846 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
3847 IdentifierInfo *&Name, SourceLocation NameLoc,
3848 const Token &NextToken,
3849 CorrectionCandidateCallback *CCC = nullptr);
3850
3851 /// Act on the result of classifying a name as an undeclared (ADL-only)
3852 /// non-type declaration.
3853 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
3854 SourceLocation NameLoc);
3855 /// Act on the result of classifying a name as an undeclared member of a
3856 /// dependent base class.
3857 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
3858 IdentifierInfo *Name,
3859 SourceLocation NameLoc,
3860 bool IsAddressOfOperand);
3861 /// Act on the result of classifying a name as a specific non-type
3862 /// declaration.
3863 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
3864 NamedDecl *Found,
3865 SourceLocation NameLoc,
3866 const Token &NextToken);
3867 /// Act on the result of classifying a name as an overload set.
3868 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
3869
3870 /// Describes the detailed kind of a template name. Used in diagnostics.
3871 enum class TemplateNameKindForDiagnostics {
3872 ClassTemplate,
3873 FunctionTemplate,
3874 VarTemplate,
3875 AliasTemplate,
3876 TemplateTemplateParam,
3877 Concept,
3878 DependentTemplate
3879 };
3880 TemplateNameKindForDiagnostics
3881 getTemplateNameKindForDiagnostics(TemplateName Name);
3882
3883 /// Determine whether it's plausible that E was intended to be a
3884 /// template-name.
3885 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
3886 if (!getLangOpts().CPlusPlus || E.isInvalid())
3887 return false;
3888 Dependent = false;
3889 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E.get()))
3890 return !DRE->hasExplicitTemplateArgs();
3891 if (auto *ME = dyn_cast<MemberExpr>(Val: E.get()))
3892 return !ME->hasExplicitTemplateArgs();
3893 Dependent = true;
3894 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(Val: E.get()))
3895 return !DSDRE->hasExplicitTemplateArgs();
3896 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(Val: E.get()))
3897 return !DSME->hasExplicitTemplateArgs();
3898 // Any additional cases recognized here should also be handled by
3899 // diagnoseExprIntendedAsTemplateName.
3900 return false;
3901 }
3902
3903 void warnOnReservedIdentifier(const NamedDecl *D);
3904 void warnOnCTypeHiddenInCPlusPlus(const NamedDecl *D);
3905
3906 void ProcessPragmaExport(DeclaratorDecl *newDecl);
3907
3908 Decl *ActOnDeclarator(Scope *S, Declarator &D);
3909
3910 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
3911 MultiTemplateParamsArg TemplateParameterLists);
3912
3913 /// Attempt to fold a variable-sized type to a constant-sized type, returning
3914 /// true if we were successful.
3915 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T,
3916 SourceLocation Loc,
3917 unsigned FailedFoldDiagID);
3918
3919 /// Register the given locally-scoped extern "C" declaration so
3920 /// that it can be found later for redeclarations. We include any extern "C"
3921 /// declaration that is not visible in the translation unit here, not just
3922 /// function-scope declarations.
3923 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
3924
3925 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3926 /// If T is the name of a class, then each of the following shall have a
3927 /// name different from T:
3928 /// - every static data member of class T;
3929 /// - every member function of class T
3930 /// - every member of class T that is itself a type;
3931 /// \returns true if the declaration name violates these rules.
3932 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
3933
3934 /// Diagnose a declaration whose declarator-id has the given
3935 /// nested-name-specifier.
3936 ///
3937 /// \param SS The nested-name-specifier of the declarator-id.
3938 ///
3939 /// \param DC The declaration context to which the nested-name-specifier
3940 /// resolves.
3941 ///
3942 /// \param Name The name of the entity being declared.
3943 ///
3944 /// \param Loc The location of the name of the entity being declared.
3945 ///
3946 /// \param IsMemberSpecialization Whether we are declaring a member
3947 /// specialization.
3948 ///
3949 /// \param TemplateId The template-id, if any.
3950 ///
3951 /// \returns true if we cannot safely recover from this error, false
3952 /// otherwise.
3953 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3954 DeclarationName Name, SourceLocation Loc,
3955 TemplateIdAnnotation *TemplateId,
3956 bool IsMemberSpecialization);
3957
3958 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range);
3959
3960 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
3961
3962 bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind,
3963 unsigned &IntVal);
3964
3965 /// Diagnose function specifiers on a declaration of an identifier that
3966 /// does not identify a function.
3967 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
3968
3969 /// Return the declaration shadowed by the given typedef \p D, or null
3970 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3971 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
3972 const LookupResult &R);
3973
3974 /// Return the declaration shadowed by the given variable \p D, or null
3975 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3976 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
3977
3978 /// Return the declaration shadowed by the given variable \p D, or null
3979 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
3980 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
3981 const LookupResult &R);
3982 /// Diagnose variable or built-in function shadowing. Implements
3983 /// -Wshadow.
3984 ///
3985 /// This method is called whenever a VarDecl is added to a "useful"
3986 /// scope.
3987 ///
3988 /// \param ShadowedDecl the declaration that is shadowed by the given variable
3989 /// \param R the lookup of the name
3990 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
3991 const LookupResult &R);
3992
3993 /// Check -Wshadow without the advantage of a previous lookup.
3994 void CheckShadow(Scope *S, VarDecl *D);
3995
3996 /// Warn if 'E', which is an expression that is about to be modified, refers
3997 /// to a shadowing declaration.
3998 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
3999
4000 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
4001 /// when these variables are captured by the lambda.
4002 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
4003
4004 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
4005 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4006 TypedefNameDecl *NewTD);
4007 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
4008 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4009 TypeSourceInfo *TInfo,
4010 LookupResult &Previous);
4011
4012 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4013 /// declares a typedef-name, either using the 'typedef' type specifier or via
4014 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4015 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D,
4016 LookupResult &Previous, bool &Redeclaration);
4017 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4018 TypeSourceInfo *TInfo,
4019 LookupResult &Previous,
4020 MultiTemplateParamsArg TemplateParamLists,
4021 bool &AddToScope,
4022 ArrayRef<BindingDecl *> Bindings = {});
4023
4024private:
4025 // Perform a check on an AsmLabel to verify its consistency and emit
4026 // diagnostics in case of an error.
4027 void CheckAsmLabel(Scope *S, Expr *AsmLabelExpr, StorageClass SC,
4028 TypeSourceInfo *TInfo, VarDecl *);
4029
4030public:
4031 /// Perform semantic checking on a newly-created variable
4032 /// declaration.
4033 ///
4034 /// This routine performs all of the type-checking required for a
4035 /// variable declaration once it has been built. It is used both to
4036 /// check variables after they have been parsed and their declarators
4037 /// have been translated into a declaration, and to check variables
4038 /// that have been instantiated from a template.
4039 ///
4040 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4041 ///
4042 /// Returns true if the variable declaration is a redeclaration.
4043 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
4044 void CheckVariableDeclarationType(VarDecl *NewVD);
4045 void CheckCompleteVariableDeclaration(VarDecl *VD);
4046
4047 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4048 TypeSourceInfo *TInfo,
4049 LookupResult &Previous,
4050 MultiTemplateParamsArg TemplateParamLists,
4051 bool &AddToScope);
4052
4053 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4054 /// and if so, check that it's a valid override and remember it.
4055 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
4056
4057 /// Perform semantic checking of a new function declaration.
4058 ///
4059 /// Performs semantic analysis of the new function declaration
4060 /// NewFD. This routine performs all semantic checking that does not
4061 /// require the actual declarator involved in the declaration, and is
4062 /// used both for the declaration of functions as they are parsed
4063 /// (called via ActOnDeclarator) and for the declaration of functions
4064 /// that have been instantiated via C++ template instantiation (called
4065 /// via InstantiateDecl).
4066 ///
4067 /// \param IsMemberSpecialization whether this new function declaration is
4068 /// a member specialization (that replaces any definition provided by the
4069 /// previous declaration).
4070 ///
4071 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4072 ///
4073 /// \returns true if the function declaration is a redeclaration.
4074 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
4075 LookupResult &Previous,
4076 bool IsMemberSpecialization, bool DeclIsDefn);
4077
4078 /// Checks if the new declaration declared in dependent context must be
4079 /// put in the same redeclaration chain as the specified declaration.
4080 ///
4081 /// \param D Declaration that is checked.
4082 /// \param PrevDecl Previous declaration found with proper lookup method for
4083 /// the same declaration name.
4084 /// \returns True if D must be added to the redeclaration chain which PrevDecl
4085 /// belongs to.
4086 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
4087
4088 /// Determines if we can perform a correct type check for \p D as a
4089 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
4090 /// best-effort check.
4091 ///
4092 /// \param NewD The new declaration.
4093 /// \param OldD The old declaration.
4094 /// \param NewT The portion of the type of the new declaration to check.
4095 /// \param OldT The portion of the type of the old declaration to check.
4096 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
4097 QualType NewT, QualType OldT);
4098 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
4099 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
4100
4101 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
4102 /// containing class. Otherwise it will return implicit SectionAttr if the
4103 /// function is a definition and there is an active value on CodeSegStack
4104 /// (from the current #pragma code-seg value).
4105 ///
4106 /// \param FD Function being declared.
4107 /// \param IsDefinition Whether it is a definition or just a declaration.
4108 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
4109 /// nullptr if no attribute should be added.
4110 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
4111 bool IsDefinition);
4112
4113 /// Common checks for a parameter-declaration that should apply to both
4114 /// function parameters and non-type template parameters.
4115 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
4116
4117 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4118 /// to introduce parameters into function prototype scope.
4119 Decl *ActOnParamDeclarator(Scope *S, Declarator &D,
4120 SourceLocation ExplicitThisLoc = {});
4121
4122 /// Synthesizes a variable for a parameter arising from a
4123 /// typedef.
4124 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc,
4125 QualType T);
4126 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
4127 SourceLocation NameLoc,
4128 const IdentifierInfo *Name, QualType T,
4129 TypeSourceInfo *TSInfo, StorageClass SC);
4130
4131 /// Emit diagnostics if the initializer or any of its explicit or
4132 /// implicitly-generated subexpressions require copying or
4133 /// default-initializing a type that is or contains a C union type that is
4134 /// non-trivial to copy or default-initialize.
4135 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
4136
4137 // These flags are passed to checkNonTrivialCUnion.
4138 enum NonTrivialCUnionKind {
4139 NTCUK_Init = 0x1,
4140 NTCUK_Destruct = 0x2,
4141 NTCUK_Copy = 0x4,
4142 };
4143
4144 /// Emit diagnostics if a non-trivial C union type or a struct that contains
4145 /// a non-trivial C union is used in an invalid context.
4146 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
4147 NonTrivialCUnionContext UseContext,
4148 unsigned NonTrivialKind);
4149
4150 /// Certain globally-unique variables might be accidentally duplicated if
4151 /// built into multiple shared libraries with hidden visibility. This can
4152 /// cause problems if the variable is mutable, its initialization is
4153 /// effectful, or its address is taken.
4154 bool GloballyUniqueObjectMightBeAccidentallyDuplicated(const VarDecl *Dcl);
4155 void DiagnoseUniqueObjectDuplication(const VarDecl *Dcl);
4156
4157 /// AddInitializerToDecl - Adds the initializer Init to the
4158 /// declaration dcl. If DirectInit is true, this is C++ direct
4159 /// initialization rather than copy initialization.
4160 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
4161 void ActOnUninitializedDecl(Decl *dcl);
4162
4163 /// ActOnInitializerError - Given that there was an error parsing an
4164 /// initializer for the given declaration, try to at least re-establish
4165 /// invariants such as whether a variable's type is either dependent or
4166 /// complete.
4167 void ActOnInitializerError(Decl *Dcl);
4168
4169 void ActOnCXXForRangeDecl(Decl *D);
4170 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
4171 IdentifierInfo *Ident,
4172 ParsedAttributes &Attrs);
4173
4174 /// Check if VD needs to be dllexport/dllimport due to being in a
4175 /// dllexport/import function.
4176 void CheckStaticLocalForDllExport(VarDecl *VD);
4177 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
4178
4179 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
4180 /// any semantic actions necessary after any initializer has been attached.
4181 void FinalizeDeclaration(Decl *D);
4182 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4183 ArrayRef<Decl *> Group);
4184
4185 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
4186 /// group, performing any necessary semantic checking.
4187 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
4188
4189 /// Should be called on all declarations that might have attached
4190 /// documentation comments.
4191 void ActOnDocumentableDecl(Decl *D);
4192 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
4193
4194 enum class FnBodyKind {
4195 /// C++26 [dcl.fct.def.general]p1
4196 /// function-body:
4197 /// ctor-initializer[opt] compound-statement
4198 /// function-try-block
4199 Other,
4200 /// = default ;
4201 Default,
4202 /// deleted-function-body
4203 ///
4204 /// deleted-function-body:
4205 /// = delete ;
4206 /// = delete ( unevaluated-string ) ;
4207 Delete
4208 };
4209
4210 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4211 SourceLocation LocAfterDecls);
4212 void CheckForFunctionRedefinition(
4213 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
4214 SkipBodyInfo *SkipBody = nullptr);
4215 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
4216 MultiTemplateParamsArg TemplateParamLists,
4217 SkipBodyInfo *SkipBody = nullptr,
4218 FnBodyKind BodyKind = FnBodyKind::Other);
4219 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
4220 SkipBodyInfo *SkipBody = nullptr,
4221 FnBodyKind BodyKind = FnBodyKind::Other);
4222 void applyFunctionAttributesBeforeParsingBody(Decl *FD);
4223
4224 /// Determine whether we can delay parsing the body of a function or
4225 /// function template until it is used, assuming we don't care about emitting
4226 /// code for that function.
4227 ///
4228 /// This will be \c false if we may need the body of the function in the
4229 /// middle of parsing an expression (where it's impractical to switch to
4230 /// parsing a different function), for instance, if it's constexpr in C++11
4231 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
4232 bool canDelayFunctionBody(const Declarator &D);
4233
4234 /// Determine whether we can skip parsing the body of a function
4235 /// definition, assuming we don't care about analyzing its body or emitting
4236 /// code for that function.
4237 ///
4238 /// This will be \c false only if we may need the body of the function in
4239 /// order to parse the rest of the program (for instance, if it is
4240 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
4241 bool canSkipFunctionBody(Decl *D);
4242
4243 /// Given the set of return statements within a function body,
4244 /// compute the variables that are subject to the named return value
4245 /// optimization.
4246 ///
4247 /// Each of the variables that is subject to the named return value
4248 /// optimization will be marked as NRVO variables in the AST, and any
4249 /// return statement that has a marked NRVO variable as its NRVO candidate can
4250 /// use the named return value optimization.
4251 ///
4252 /// This function applies a very simplistic algorithm for NRVO: if every
4253 /// return statement in the scope of a variable has the same NRVO candidate,
4254 /// that candidate is an NRVO variable.
4255 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
4256
4257 /// Performs semantic analysis at the end of a function body.
4258 ///
4259 /// \param RetainFunctionScopeInfo If \c true, the client is responsible for
4260 /// releasing the associated \p FunctionScopeInfo. This is useful when
4261 /// building e.g. LambdaExprs.
4262 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body,
4263 bool IsInstantiation = false,
4264 bool RetainFunctionScopeInfo = false);
4265 Decl *ActOnSkippedFunctionBody(Decl *Decl);
4266 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
4267
4268 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
4269 /// attribute for which parsing is delayed.
4270 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
4271
4272 /// Diagnose any unused parameters in the given sequence of
4273 /// ParmVarDecl pointers.
4274 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
4275
4276 /// Diagnose whether the size of parameters or return value of a
4277 /// function or obj-c method definition is pass-by-value and larger than a
4278 /// specified threshold.
4279 void
4280 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
4281 QualType ReturnTy, NamedDecl *D);
4282
4283 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc,
4284 SourceLocation RParenLoc);
4285
4286 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S);
4287 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement);
4288
4289 void ActOnPopScope(SourceLocation Loc, Scope *S);
4290
4291 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4292 /// no declarator (e.g. "struct foo;") is parsed.
4293 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4294 const ParsedAttributesView &DeclAttrs,
4295 RecordDecl *&AnonRecord);
4296
4297 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4298 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4299 /// parameters to cope with template friend declarations.
4300 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4301 const ParsedAttributesView &DeclAttrs,
4302 MultiTemplateParamsArg TemplateParams,
4303 bool IsExplicitInstantiation,
4304 RecordDecl *&AnonRecord,
4305 SourceLocation EllipsisLoc = {});
4306
4307 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4308 /// anonymous structure or union. Anonymous unions are a C++ feature
4309 /// (C++ [class.union]) and a C11 feature; anonymous structures
4310 /// are a C11 feature and GNU C++ extension.
4311 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS,
4312 RecordDecl *Record,
4313 const PrintingPolicy &Policy);
4314
4315 /// Called once it is known whether
4316 /// a tag declaration is an anonymous union or struct.
4317 void ActOnDefinedDeclarationSpecifier(Decl *D);
4318
4319 /// Emit diagnostic warnings for placeholder members.
4320 /// We can only do that after the class is fully constructed,
4321 /// as anonymous union/structs can insert placeholders
4322 /// in their parent scope (which might be a Record).
4323 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record);
4324
4325 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4326 /// Microsoft C anonymous structure.
4327 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4328 /// Example:
4329 ///
4330 /// struct A { int a; };
4331 /// struct B { struct A; int b; };
4332 ///
4333 /// void foo() {
4334 /// B var;
4335 /// var.a = 3;
4336 /// }
4337 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4338 RecordDecl *Record);
4339
4340 /// Given a non-tag type declaration, returns an enum useful for indicating
4341 /// what kind of non-tag type this is.
4342 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
4343
4344 /// Determine whether a tag with a given kind is acceptable
4345 /// as a redeclaration of the given tag declaration.
4346 ///
4347 /// \returns true if the new tag kind is acceptable, false otherwise.
4348 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag,
4349 bool isDefinition, SourceLocation NewTagLoc,
4350 const IdentifierInfo *Name);
4351
4352 /// This is invoked when we see 'struct foo' or 'struct {'. In the
4353 /// former case, Name will be non-null. In the later case, Name will be null.
4354 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is
4355 /// a reference/declaration/definition of a tag.
4356 ///
4357 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
4358 /// trailing-type-specifier) other than one in an alias-declaration.
4359 ///
4360 /// \param SkipBody If non-null, will be set to indicate if the caller should
4361 /// skip the definition of this tag and treat it as if it were a declaration.
4362 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4363 SourceLocation KWLoc, CXXScopeSpec &SS,
4364 IdentifierInfo *Name, SourceLocation NameLoc,
4365 const ParsedAttributesView &Attr, AccessSpecifier AS,
4366 SourceLocation ModulePrivateLoc,
4367 MultiTemplateParamsArg TemplateParameterLists,
4368 bool &OwnedDecl, bool &IsDependent,
4369 SourceLocation ScopedEnumKWLoc,
4370 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
4371 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
4372 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
4373
4374 /// ActOnField - Each field of a C struct/union is passed into this in order
4375 /// to create a FieldDecl object for it.
4376 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
4377 Declarator &D, Expr *BitfieldWidth);
4378
4379 /// HandleField - Analyze a field of a C struct or a C++ data member.
4380 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
4381 Declarator &D, Expr *BitfieldWidth,
4382 InClassInitStyle InitStyle, AccessSpecifier AS);
4383
4384 /// Build a new FieldDecl and check its well-formedness.
4385 ///
4386 /// This routine builds a new FieldDecl given the fields name, type,
4387 /// record, etc. \p PrevDecl should refer to any previous declaration
4388 /// with the same name and in the same scope as the field to be
4389 /// created.
4390 ///
4391 /// \returns a new FieldDecl.
4392 ///
4393 /// \todo The Declarator argument is a hack. It will be removed once
4394 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
4395 TypeSourceInfo *TInfo, RecordDecl *Record,
4396 SourceLocation Loc, bool Mutable,
4397 Expr *BitfieldWidth, InClassInitStyle InitStyle,
4398 SourceLocation TSSL, AccessSpecifier AS,
4399 NamedDecl *PrevDecl, Declarator *D = nullptr);
4400
4401 bool CheckNontrivialField(FieldDecl *FD);
4402
4403 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
4404 /// class and class extensions. For every class \@interface and class
4405 /// extension \@interface, if the last ivar is a bitfield of any type,
4406 /// then add an implicit `char :0` ivar to the end of that interface.
4407 void ActOnLastBitfield(SourceLocation DeclStart,
4408 SmallVectorImpl<Decl *> &AllIvarDecls);
4409
4410 // This is used for both record definitions and ObjC interface declarations.
4411 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
4412 ArrayRef<Decl *> Fields, SourceLocation LBrac,
4413 SourceLocation RBrac, const ParsedAttributesView &AttrList);
4414
4415 /// ActOnTagStartDefinition - Invoked when we have entered the
4416 /// scope of a tag's definition (e.g., for an enumeration, class,
4417 /// struct, or union).
4418 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
4419
4420 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
4421 /// Differently from C++, actually parse the body and reject / error out
4422 /// in case of a structural mismatch.
4423 bool ActOnDuplicateDefinition(Scope *S, Decl *Prev, SkipBodyInfo &SkipBody);
4424
4425 typedef void *SkippedDefinitionContext;
4426
4427 /// Invoked when we enter a tag definition that we're skipping.
4428 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
4429
4430 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
4431 /// C++ record definition's base-specifiers clause and are starting its
4432 /// member declarations.
4433 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
4434 SourceLocation FinalLoc,
4435 bool IsFinalSpelledSealed,
4436 bool IsAbstract,
4437 SourceLocation LBraceLoc);
4438
4439 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
4440 /// the definition of a tag (enumeration, class, struct, or union).
4441 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
4442 SourceRange BraceRange);
4443
4444 ASTContext::CXXRecordDeclRelocationInfo
4445 CheckCXX2CRelocatable(const clang::CXXRecordDecl *D);
4446
4447 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
4448
4449 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
4450 /// error parsing the definition of a tag.
4451 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
4452
4453 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
4454 EnumConstantDecl *LastEnumConst,
4455 SourceLocation IdLoc, IdentifierInfo *Id,
4456 Expr *val);
4457
4458 /// Check that this is a valid underlying type for an enum declaration.
4459 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
4460
4461 /// Check whether this is a valid redeclaration of a previous enumeration.
4462 /// \return true if the redeclaration was invalid.
4463 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
4464 QualType EnumUnderlyingTy, bool IsFixed,
4465 const EnumDecl *Prev);
4466
4467 /// Determine whether the body of an anonymous enumeration should be skipped.
4468 /// \param II The name of the first enumerator.
4469 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
4470 SourceLocation IILoc);
4471
4472 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
4473 SourceLocation IdLoc, IdentifierInfo *Id,
4474 const ParsedAttributesView &Attrs,
4475 SourceLocation EqualLoc, Expr *Val,
4476 SkipBodyInfo *SkipBody = nullptr);
4477 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
4478 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
4479 const ParsedAttributesView &Attr);
4480
4481 /// Set the current declaration context until it gets popped.
4482 void PushDeclContext(Scope *S, DeclContext *DC);
4483 void PopDeclContext();
4484
4485 /// EnterDeclaratorContext - Used when we must lookup names in the context
4486 /// of a declarator's nested name specifier.
4487 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
4488 void ExitDeclaratorContext(Scope *S);
4489
4490 /// Enter a template parameter scope, after it's been associated with a
4491 /// particular DeclContext. Causes lookup within the scope to chain through
4492 /// enclosing contexts in the correct order.
4493 void EnterTemplatedContext(Scope *S, DeclContext *DC);
4494
4495 /// Push the parameters of D, which must be a function, into scope.
4496 void ActOnReenterFunctionContext(Scope *S, Decl *D);
4497 void ActOnExitFunctionContext();
4498
4499 /// Add this decl to the scope shadowed decl chains.
4500 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
4501
4502 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
4503 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
4504 /// true if 'D' belongs to the given declaration context.
4505 ///
4506 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
4507 /// enclosing namespace set of the context, rather than contained
4508 /// directly within it.
4509 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
4510 bool AllowInlineNamespace = false) const;
4511
4512 /// Finds the scope corresponding to the given decl context, if it
4513 /// happens to be an enclosing scope. Otherwise return NULL.
4514 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
4515
4516 /// Subroutines of ActOnDeclarator().
4517 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4518 TypeSourceInfo *TInfo);
4519 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New);
4520
4521 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
4522 void mergeDeclAttributes(
4523 NamedDecl *New, Decl *Old,
4524 AvailabilityMergeKind AMK = AvailabilityMergeKind::Redeclaration);
4525
4526 /// CheckAttributesOnDeducedType - Calls Sema functions for attributes that
4527 /// requires the type to be deduced.
4528 void CheckAttributesOnDeducedType(Decl *D);
4529
4530 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
4531 /// same name and scope as a previous declaration 'Old'. Figure out
4532 /// how to resolve this situation, merging decls or emitting
4533 /// diagnostics as appropriate. If there was an error, set New to be invalid.
4534 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
4535 LookupResult &OldDecls);
4536
4537 /// CleanupMergedEnum - We have just merged the decl 'New' by making another
4538 /// definition visible.
4539 /// This method performs any necessary cleanup on the parser state to discard
4540 /// child nodes from newly parsed decl we are retiring.
4541 void CleanupMergedEnum(Scope *S, Decl *New);
4542
4543 /// MergeFunctionDecl - We just parsed a function 'New' from
4544 /// declarator D which has the same name and scope as a previous
4545 /// declaration 'Old'. Figure out how to resolve this situation,
4546 /// merging decls or emitting diagnostics as appropriate.
4547 ///
4548 /// In C++, New and Old must be declarations that are not
4549 /// overloaded. Use IsOverload to determine whether New and Old are
4550 /// overloaded, and to select the Old declaration that New should be
4551 /// merged with.
4552 ///
4553 /// Returns true if there was an error, false otherwise.
4554 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
4555 bool MergeTypeWithOld, bool NewDeclIsDefn);
4556
4557 /// Completes the merge of two function declarations that are
4558 /// known to be compatible.
4559 ///
4560 /// This routine handles the merging of attributes and other
4561 /// properties of function declarations from the old declaration to
4562 /// the new declaration, once we know that New is in fact a
4563 /// redeclaration of Old.
4564 ///
4565 /// \returns false
4566 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
4567 Scope *S, bool MergeTypeWithOld);
4568 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
4569
4570 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4571 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4572 /// situation, merging decls or emitting diagnostics as appropriate.
4573 ///
4574 /// Tentative definition rules (C99 6.9.2p2) are checked by
4575 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4576 /// definitions here, since the initializer hasn't been attached.
4577 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
4578
4579 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4580 /// scope as a previous declaration 'Old'. Figure out how to merge their
4581 /// types, emitting diagnostics as appropriate.
4582 ///
4583 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call
4584 /// back to here in AddInitializerToDecl. We can't check them before the
4585 /// initializer is attached.
4586 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
4587
4588 /// We've just determined that \p Old and \p New both appear to be definitions
4589 /// of the same variable. Either diagnose or fix the problem.
4590 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
4591 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
4592
4593 /// Filters out lookup results that don't fall within the given scope
4594 /// as determined by isDeclInScope.
4595 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4596 bool ConsiderLinkage, bool AllowInlineNamespace);
4597
4598 /// We've determined that \p New is a redeclaration of \p Old. Check that they
4599 /// have compatible owning modules.
4600 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4601
4602 /// [module.interface]p6:
4603 /// A redeclaration of an entity X is implicitly exported if X was introduced
4604 /// by an exported declaration; otherwise it shall not be exported.
4605 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4606
4607 /// A wrapper function for checking the semantic restrictions of
4608 /// a redeclaration within a module.
4609 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4610
4611 /// Check the redefinition in C++20 Modules.
4612 ///
4613 /// [basic.def.odr]p14:
4614 /// For any definable item D with definitions in multiple translation units,
4615 /// - if D is a non-inline non-templated function or variable, or
4616 /// - if the definitions in different translation units do not satisfy the
4617 /// following requirements,
4618 /// the program is ill-formed; a diagnostic is required only if the
4619 /// definable item is attached to a named module and a prior definition is
4620 /// reachable at the point where a later definition occurs.
4621 /// - Each such definition shall not be attached to a named module
4622 /// ([module.unit]).
4623 /// - Each such definition shall consist of the same sequence of tokens, ...
4624 /// ...
4625 ///
4626 /// Return true if the redefinition is not allowed. Return false otherwise.
4627 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const;
4628
4629 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
4630
4631 /// If it's a file scoped decl that must warn if not used, keep track
4632 /// of it.
4633 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
4634
4635 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)>
4636 DiagReceiverTy;
4637
4638 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
4639 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
4640 DiagReceiverTy DiagReceiver);
4641 void DiagnoseUnusedDecl(const NamedDecl *ND);
4642
4643 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
4644 /// unless they are marked attr(unused).
4645 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver);
4646
4647 /// If VD is set but not otherwise used, diagnose, for a parameter or a
4648 /// variable.
4649 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver);
4650
4651 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
4652 /// from S, where a non-field would be declared. This routine copes
4653 /// with the difference between C and C++ scoping rules in structs and
4654 /// unions. For example, the following code is well-formed in C but
4655 /// ill-formed in C++:
4656 /// @code
4657 /// struct S6 {
4658 /// enum { BAR } e;
4659 /// };
4660 ///
4661 /// void test_S6() {
4662 /// struct S6 a;
4663 /// a.e = BAR;
4664 /// }
4665 /// @endcode
4666 /// For the declaration of BAR, this routine will return a different
4667 /// scope. The scope S will be the scope of the unnamed enumeration
4668 /// within S6. In C++, this routine will return the scope associated
4669 /// with S6, because the enumeration's scope is a transparent
4670 /// context but structures can contain non-field names. In C, this
4671 /// routine will return the translation unit scope, since the
4672 /// enumeration's scope is a transparent context and structures cannot
4673 /// contain non-field names.
4674 Scope *getNonFieldDeclScope(Scope *S);
4675
4676 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4677 SourceLocation Loc);
4678
4679 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
4680 /// file scope. lazily create a decl for it. ForRedeclaration is true
4681 /// if we're creating this built-in in anticipation of redeclaring the
4682 /// built-in.
4683 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S,
4684 bool ForRedeclaration, SourceLocation Loc);
4685
4686 /// Get the outermost AttributedType node that sets a calling convention.
4687 /// Valid types should not have multiple attributes with different CCs.
4688 const AttributedType *getCallingConvAttributedType(QualType T) const;
4689
4690 /// GetNameForDeclarator - Determine the full declaration name for the
4691 /// given Declarator.
4692 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
4693
4694 /// Retrieves the declaration name from a parsed unqualified-id.
4695 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
4696
4697 /// ParsingInitForAutoVars - a set of declarations with auto types for which
4698 /// we are currently parsing the initializer.
4699 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars;
4700
4701 /// Look for a locally scoped extern "C" declaration by the given name.
4702 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
4703
4704 void deduceOpenCLAddressSpace(VarDecl *decl);
4705 void deduceHLSLAddressSpace(VarDecl *decl);
4706
4707 /// Adjust the \c DeclContext for a function or variable that might be a
4708 /// function-local external declaration.
4709 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
4710
4711 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4712
4713 /// Checks if the variant/multiversion functions are compatible.
4714 bool areMultiversionVariantFunctionsCompatible(
4715 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
4716 const PartialDiagnostic &NoProtoDiagID,
4717 const PartialDiagnosticAt &NoteCausedDiagIDAt,
4718 const PartialDiagnosticAt &NoSupportDiagIDAt,
4719 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
4720 bool ConstexprSupported, bool CLinkageMayDiffer);
4721
4722 /// type checking declaration initializers (C99 6.7.8)
4723 bool CheckForConstantInitializer(
4724 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant);
4725
4726 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
4727 QualType Type, TypeSourceInfo *TSI,
4728 SourceRange Range, bool DirectInit,
4729 Expr *Init);
4730
4731 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
4732 Expr *Init);
4733
4734 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator);
4735
4736 // Heuristically tells if the function is `get_return_object` member of a
4737 // coroutine promise_type by matching the function name.
4738 static bool CanBeGetReturnObject(const FunctionDecl *FD);
4739 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD);
4740
4741 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4742 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4743 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4744 Scope *S);
4745
4746 /// If this function is a C++ replaceable global allocation function
4747 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
4748 /// adds any function attributes that we know a priori based on the standard.
4749 ///
4750 /// We need to check for duplicate attributes both here and where user-written
4751 /// attributes are applied to declarations.
4752 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4753 FunctionDecl *FD);
4754
4755 /// Adds any function attributes that we know a priori based on
4756 /// the declaration of this function.
4757 ///
4758 /// These attributes can apply both to implicitly-declared builtins
4759 /// (like __builtin___printf_chk) or to library-declared functions
4760 /// like NSLog or printf.
4761 ///
4762 /// We need to check for duplicate attributes both here and where user-written
4763 /// attributes are applied to declarations.
4764 void AddKnownFunctionAttributes(FunctionDecl *FD);
4765
4766 /// VerifyBitField - verifies that a bit field expression is an ICE and has
4767 /// the correct width, and that the field type is valid.
4768 /// Returns false on success.
4769 ExprResult VerifyBitField(SourceLocation FieldLoc,
4770 const IdentifierInfo *FieldName, QualType FieldTy,
4771 bool IsMsStruct, Expr *BitWidth);
4772
4773 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
4774 /// enum. If AllowMask is true, then we also allow the complement of a valid
4775 /// value, to be used as a mask.
4776 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
4777 bool AllowMask) const;
4778
4779 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
4780 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc,
4781 SourceLocation WeakNameLoc);
4782
4783 /// ActOnPragmaRedefineExtname - Called on well formed
4784 /// \#pragma redefine_extname oldname newname.
4785 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName,
4786 IdentifierInfo *AliasName,
4787 SourceLocation PragmaLoc,
4788 SourceLocation WeakNameLoc,
4789 SourceLocation AliasNameLoc);
4790
4791 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
4792 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName,
4793 SourceLocation PragmaLoc,
4794 SourceLocation WeakNameLoc,
4795 SourceLocation AliasNameLoc);
4796
4797 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4798 enum class FunctionEmissionStatus {
4799 Emitted,
4800 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4801 OMPDiscarded, // Discarded due to OpenMP hostness
4802 TemplateDiscarded, // Discarded due to uninstantiated templates
4803 Unknown,
4804 };
4805 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl,
4806 bool Final = false);
4807
4808 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4809 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4810
4811 /// Function or variable declarations to be checked for whether the deferred
4812 /// diagnostics should be emitted.
4813 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
4814
4815private:
4816 /// Map of current shadowing declarations to shadowed declarations. Warn if
4817 /// it looks like the user is trying to modify the shadowing declaration.
4818 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
4819
4820 // We need this to handle
4821 //
4822 // typedef struct {
4823 // void *foo() { return 0; }
4824 // } A;
4825 //
4826 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
4827 // for example. If 'A', foo will have external linkage. If we have '*A',
4828 // foo will have no linkage. Since we can't know until we get to the end
4829 // of the typedef, this function finds out if D might have non-external
4830 // linkage. Callers should verify at the end of the TU if it D has external
4831 // linkage or not.
4832 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
4833
4834#include "clang/Sema/AttrIsTypeDependent.inc"
4835
4836 ///@}
4837
4838 //
4839 //
4840 // -------------------------------------------------------------------------
4841 //
4842 //
4843
4844 /// \name Declaration Attribute Handling
4845 /// Implementations are in SemaDeclAttr.cpp
4846 ///@{
4847
4848public:
4849 /// Describes the kind of priority given to an availability attribute.
4850 ///
4851 /// The sum of priorities deteremines the final priority of the attribute.
4852 /// The final priority determines how the attribute will be merged.
4853 /// An attribute with a lower priority will always remove higher priority
4854 /// attributes for the specified platform when it is being applied. An
4855 /// attribute with a higher priority will not be applied if the declaration
4856 /// already has an availability attribute with a lower priority for the
4857 /// specified platform. The final prirority values are not expected to match
4858 /// the values in this enumeration, but instead should be treated as a plain
4859 /// integer value. This enumeration just names the priority weights that are
4860 /// used to calculate that final vaue.
4861 enum AvailabilityPriority : int {
4862 /// The availability attribute was specified explicitly next to the
4863 /// declaration.
4864 AP_Explicit = 0,
4865
4866 /// The availability attribute was applied using '#pragma clang attribute'.
4867 AP_PragmaClangAttribute = 1,
4868
4869 /// The availability attribute for a specific platform was inferred from
4870 /// an availability attribute for another platform.
4871 AP_InferredFromOtherPlatform = 2,
4872
4873 /// The availability attribute was inferred from an 'anyAppleOS'
4874 /// availability attribute.
4875 AP_InferredFromAnyAppleOS = 3,
4876
4877 /// The availability attribute was inferred from an 'anyAppleOS'
4878 /// availability attribute that was applied using '#pragma clang attribute'.
4879 /// This has the lowest priority.
4880 AP_PragmaClangAttribute_InferredFromAnyAppleOS = 4
4881 };
4882
4883 /// Describes the reason a calling convention specification was ignored, used
4884 /// for diagnostics.
4885 enum class CallingConventionIgnoredReason {
4886 ForThisTarget = 0,
4887 VariadicFunction,
4888 ConstructorDestructor,
4889 BuiltinFunction
4890 };
4891
4892 /// A helper function to provide Attribute Location for the Attr types
4893 /// AND the ParsedAttr.
4894 template <typename AttrInfo>
4895 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
4896 getAttrLoc(const AttrInfo &AL) {
4897 return AL.getLocation();
4898 }
4899 SourceLocation getAttrLoc(const AttributeCommonInfo &CI);
4900
4901 /// If Expr is a valid integer constant, get the value of the integer
4902 /// expression and return success or failure. May output an error.
4903 ///
4904 /// Negative argument is implicitly converted to unsigned, unless
4905 /// \p StrictlyUnsigned is true.
4906 template <typename AttrInfo>
4907 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val,
4908 unsigned Idx = UINT_MAX,
4909 bool StrictlyUnsigned = false) {
4910 std::optional<llvm::APSInt> I = llvm::APSInt(32);
4911 if (Expr->isTypeDependent() ||
4912 !(I = Expr->getIntegerConstantExpr(Ctx: Context))) {
4913 if (Idx != UINT_MAX)
4914 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
4915 << &AI << Idx << AANT_ArgumentIntegerConstant
4916 << Expr->getSourceRange();
4917 else
4918 Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
4919 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
4920 return false;
4921 }
4922
4923 if (!I->isIntN(N: 32)) {
4924 Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
4925 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
4926 return false;
4927 }
4928
4929 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
4930 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
4931 << &AI << /*non-negative*/ 1;
4932 return false;
4933 }
4934
4935 Val = (uint32_t)I->getZExtValue();
4936 return true;
4937 }
4938
4939 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
4940 /// \#pragma weak during processing of other Decls.
4941 /// I couldn't figure out a clean way to generate these in-line, so
4942 /// we store them here and handle separately -- which is a hack.
4943 /// It would be best to refactor this.
4944 SmallVector<Decl *, 2> WeakTopLevelDecl;
4945
4946 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
4947 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
4948
4949 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
4950 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
4951 ExtVectorDeclsType;
4952
4953 /// ExtVectorDecls - This is a list all the extended vector types. This allows
4954 /// us to associate a raw vector type with one of the ext_vector type names.
4955 /// This is only necessary for issuing pretty diagnostics.
4956 ExtVectorDeclsType ExtVectorDecls;
4957
4958 /// Check if the argument \p E is a ASCII string literal. If not emit an error
4959 /// and return false, otherwise set \p Str to the value of the string literal
4960 /// and return true.
4961 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4962 const Expr *E, StringRef &Str,
4963 SourceLocation *ArgLocation = nullptr);
4964
4965 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
4966 /// If not emit an error and return false. If the argument is an identifier it
4967 /// will emit an error with a fixit hint and treat it as if it was a string
4968 /// literal.
4969 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4970 StringRef &Str,
4971 SourceLocation *ArgLocation = nullptr);
4972
4973 /// Determine if type T is a valid subject for a nonnull and similar
4974 /// attributes. Dependent types are considered valid so they can be checked
4975 /// during instantiation time. By default, we look through references (the
4976 /// behavior used by nonnull), but if the second parameter is true, then we
4977 /// treat a reference type as valid.
4978 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4979
4980 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
4981 /// declaration.
4982 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4983 Expr *OE);
4984
4985 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
4986 /// declaration.
4987 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
4988 Expr *ParamExpr);
4989
4990 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4991 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4992
4993 AvailabilityAttr *
4994 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
4995 const IdentifierInfo *Platform, bool Implicit,
4996 VersionTuple Introduced, VersionTuple Deprecated,
4997 VersionTuple Obsoleted, bool IsUnavailable,
4998 StringRef Message, bool IsStrict, StringRef Replacement,
4999 AvailabilityMergeKind AMK, int Priority,
5000 const IdentifierInfo *IIEnvironment,
5001 const IdentifierInfo *InferredPlatformII = nullptr);
5002
5003 AvailabilityAttr *mergeAndInferAvailabilityAttr(
5004 NamedDecl *D, const AttributeCommonInfo &CI,
5005 const IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced,
5006 VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable,
5007 StringRef Message, bool IsStrict, StringRef Replacement,
5008 AvailabilityMergeKind AMK, int Priority,
5009 const IdentifierInfo *IIEnvironment,
5010 const IdentifierInfo *InferredPlatformII);
5011
5012 TypeVisibilityAttr *
5013 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5014 TypeVisibilityAttr::VisibilityType Vis);
5015 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
5016 VisibilityAttr::VisibilityType Vis);
5017 void mergeVisibilityType(Decl *D, SourceLocation Loc,
5018 VisibilityAttr::VisibilityType Type);
5019 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
5020 StringRef Name);
5021
5022 /// Used to implement to perform semantic checking on
5023 /// attribute((section("foo"))) specifiers.
5024 ///
5025 /// In this case, "foo" is passed in to be checked. If the section
5026 /// specifier is invalid, return an Error that indicates the problem.
5027 ///
5028 /// This is a simple quality of implementation feature to catch errors
5029 /// and give good diagnostics in cases when the assembler or code generator
5030 /// would otherwise reject the section specifier.
5031 llvm::Error isValidSectionSpecifier(StringRef Str);
5032 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
5033 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
5034 StringRef Name);
5035
5036 // Check for things we'd like to warn about. Multiversioning issues are
5037 // handled later in the process, once we know how many exist.
5038 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
5039
5040 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5041 StringRef NewUserDiagnostic);
5042 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5043 const IdentifierInfo *Format, int FormatIdx,
5044 int FirstArg);
5045 FormatMatchesAttr *mergeFormatMatchesAttr(Decl *D,
5046 const AttributeCommonInfo &CI,
5047 const IdentifierInfo *Format,
5048 int FormatIdx,
5049 StringLiteral *FormatStr);
5050 ModularFormatAttr *mergeModularFormatAttr(Decl *D,
5051 const AttributeCommonInfo &CI,
5052 const IdentifierInfo *ModularImplFn,
5053 StringRef ImplName,
5054 MutableArrayRef<StringRef> Aspects);
5055
5056 PersonalityAttr *mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
5057 const AttributeCommonInfo &CI);
5058
5059 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
5060 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
5061 bool IsPackExpansion);
5062 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
5063 bool IsPackExpansion);
5064
5065 /// AddAlignValueAttr - Adds an align_value attribute to a particular
5066 /// declaration.
5067 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
5068
5069 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments.
5070 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot,
5071 MutableArrayRef<Expr *> Args);
5072 Attr *CreateAnnotationAttr(const ParsedAttr &AL);
5073
5074 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range,
5075 bool BestCase,
5076 MSInheritanceModel SemanticSpelling);
5077
5078 void CheckAlignasUnderalignment(Decl *D);
5079
5080 /// AddModeAttr - Adds a mode attribute to a particular declaration.
5081 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5082 const IdentifierInfo *Name, bool InInstantiation = false);
5083 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
5084 const AttributeCommonInfo &CI,
5085 const IdentifierInfo *Ident);
5086 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
5087 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
5088 const AttributeCommonInfo &CI);
5089 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
5090 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
5091 const InternalLinkageAttr &AL);
5092
5093 /// Check validaty of calling convention attribute \p attr. If \p FD
5094 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device
5095 /// target. Otherwise, it is specified by \p CFT.
5096 bool CheckCallingConvAttr(
5097 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr,
5098 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget);
5099
5100 /// Checks a regparm attribute, returning true if it is ill-formed and
5101 /// otherwise setting numParams to the appropriate value.
5102 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
5103
5104 /// Create a CUDALaunchBoundsAttr attribute. By default, the function only
5105 /// supports nvptx target architectures and skips MaxBlocks if it is previous
5106 /// to sm_90. Use \p IgnoreArch to skip the architecture check.
5107 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI,
5108 Expr *MaxThreads,
5109 Expr *MinBlocks, Expr *MaxBlocks,
5110 bool IgnoreArch = false);
5111
5112 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
5113 /// declaration.
5114 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5115 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks);
5116
5117 /// Add a cluster_dims attribute to a particular declaration.
5118 CUDAClusterDimsAttr *createClusterDimsAttr(const AttributeCommonInfo &CI,
5119 Expr *X, Expr *Y, Expr *Z);
5120 void addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
5121 Expr *Y, Expr *Z);
5122 /// Add a no_cluster attribute to a particular declaration.
5123 void addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI);
5124
5125 enum class RetainOwnershipKind { NS, CF, OS };
5126
5127 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5128 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
5129
5130 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
5131
5132 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
5133 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
5134 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
5135 const AttributeCommonInfo &CI,
5136 bool BestCase,
5137 MSInheritanceModel Model);
5138
5139 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
5140 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
5141 const EnforceTCBLeafAttr &AL);
5142
5143 /// Helper for delayed processing TransparentUnion or
5144 /// BPFPreserveAccessIndexAttr attribute.
5145 void ProcessDeclAttributeDelayed(Decl *D,
5146 const ParsedAttributesView &AttrList);
5147
5148 // Options for ProcessDeclAttributeList().
5149 struct ProcessDeclAttributeOptions {
5150 ProcessDeclAttributeOptions()
5151 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {}
5152
5153 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) {
5154 ProcessDeclAttributeOptions Result = *this;
5155 Result.IncludeCXX11Attributes = Val;
5156 return Result;
5157 }
5158
5159 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) {
5160 ProcessDeclAttributeOptions Result = *this;
5161 Result.IgnoreTypeAttributes = Val;
5162 return Result;
5163 }
5164
5165 // Should C++11 attributes be processed?
5166 bool IncludeCXX11Attributes;
5167
5168 // Should any type attributes encountered be ignored?
5169 // If this option is false, a diagnostic will be emitted for any type
5170 // attributes of a kind that does not "slide" from the declaration to
5171 // the decl-specifier-seq.
5172 bool IgnoreTypeAttributes;
5173 };
5174
5175 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5176 /// attribute list to the specified decl, ignoring any type attributes.
5177 void ProcessDeclAttributeList(Scope *S, Decl *D,
5178 const ParsedAttributesView &AttrList,
5179 const ProcessDeclAttributeOptions &Options =
5180 ProcessDeclAttributeOptions());
5181
5182 /// Annotation attributes are the only attributes allowed after an access
5183 /// specifier.
5184 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5185 const ParsedAttributesView &AttrList);
5186
5187 /// checkUnusedDeclAttributes - Given a declarator which is not being
5188 /// used to build a declaration, complain about any decl attributes
5189 /// which might be lying around on it.
5190 void checkUnusedDeclAttributes(Declarator &D);
5191
5192 void DiagnoseUnknownAttribute(const ParsedAttr &AL);
5193
5194 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5195 /// \#pragma weak needs a non-definition decl and source may not have one.
5196 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
5197 SourceLocation Loc);
5198
5199 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5200 /// applied to it, possibly with an alias.
5201 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
5202
5203 void ProcessPragmaWeak(Scope *S, Decl *D);
5204 // Decl attributes - this routine is the top level dispatcher.
5205 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
5206
5207 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5208
5209 /// Given a set of delayed diagnostics, re-emit them as if they had
5210 /// been delayed in the current context instead of in the given pool.
5211 /// Essentially, this just moves them to the current pool.
5212 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5213
5214 /// Check that the type is a plain record with one field being a pointer
5215 /// type and the other field being an integer. This matches the common
5216 /// implementation of std::span or sized_allocation_t in P0901R11.
5217 bool CheckSpanLikeType(const AttributeCommonInfo &CI, const QualType &Ty);
5218
5219 /// Check if IdxExpr is a valid parameter index for a function or
5220 /// instance method D. May output an error.
5221 ///
5222 /// \returns true if IdxExpr is a valid index.
5223 template <typename AttrInfo>
5224 bool checkFunctionOrMethodParameterIndex(
5225 const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
5226 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false,
5227 bool CanIndexVariadicArguments = false) {
5228 assert(isFunctionOrMethodOrBlockForAttrSubject(D));
5229
5230 // In C++ the implicit 'this' function parameter also counts.
5231 // Parameters are counted from one.
5232 bool HP = hasFunctionProto(D);
5233 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
5234 bool IV = HP && isFunctionOrMethodVariadic(D);
5235 unsigned NumParams =
5236 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
5237
5238 std::optional<llvm::APSInt> IdxInt;
5239 if (IdxExpr->isTypeDependent() ||
5240 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: Context))) {
5241 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
5242 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
5243 << IdxExpr->getSourceRange();
5244 return false;
5245 }
5246
5247 constexpr unsigned Limit = 1 << ParamIdx::IdxBitWidth;
5248 unsigned IdxSource = IdxInt->getLimitedValue(Limit);
5249 if (IdxSource < 1 || IdxSource == Limit ||
5250 ((!IV || !CanIndexVariadicArguments) && IdxSource > NumParams)) {
5251 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
5252 << &AI << AttrArgNum << IdxExpr->getSourceRange();
5253 return false;
5254 }
5255 if (HasImplicitThisParam && !CanIndexImplicitThis) {
5256 if (IdxSource == 1) {
5257 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
5258 << &AI << IdxExpr->getSourceRange();
5259 return false;
5260 }
5261 }
5262
5263 Idx = ParamIdx(IdxSource, D);
5264 return true;
5265 }
5266
5267 ///@}
5268
5269 //
5270 //
5271 // -------------------------------------------------------------------------
5272 //
5273 //
5274
5275 /// \name C++ Declarations
5276 /// Implementations are in SemaDeclCXX.cpp
5277 ///@{
5278
5279public:
5280 void CheckDelegatingCtorCycles();
5281
5282 /// Called before parsing a function declarator belonging to a function
5283 /// declaration.
5284 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
5285 unsigned TemplateParameterDepth);
5286
5287 /// Called after parsing a function declarator belonging to a function
5288 /// declaration.
5289 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
5290
5291 // Act on C++ namespaces
5292 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5293 SourceLocation NamespaceLoc,
5294 SourceLocation IdentLoc, IdentifierInfo *Ident,
5295 SourceLocation LBrace,
5296 const ParsedAttributesView &AttrList,
5297 UsingDirectiveDecl *&UsingDecl, bool IsNested);
5298
5299 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5300 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5301 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5302
5303 NamespaceDecl *getStdNamespace() const;
5304
5305 /// Retrieve the special "std" namespace, which may require us to
5306 /// implicitly define the namespace.
5307 NamespaceDecl *getOrCreateStdNamespace();
5308
5309 CXXRecordDecl *getStdBadAlloc() const;
5310 EnumDecl *getStdAlignValT() const;
5311
5312 TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const;
5313 FunctionDecl *BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnDecl,
5314 QualType AllocType, SourceLocation);
5315
5316 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
5317 const IdentifierInfo *MemberOrBase);
5318
5319 enum class ComparisonCategoryUsage {
5320 /// The '<=>' operator was used in an expression and a builtin operator
5321 /// was selected.
5322 OperatorInExpression,
5323 /// A defaulted 'operator<=>' needed the comparison category. This
5324 /// typically only applies to 'std::strong_ordering', due to the implicit
5325 /// fallback return value.
5326 DefaultedOperator,
5327 };
5328
5329 /// Lookup the specified comparison category types in the standard
5330 /// library, an check the VarDecls possibly returned by the operator<=>
5331 /// builtins for that type.
5332 ///
5333 /// \return The type of the comparison category type corresponding to the
5334 /// specified Kind, or a null type if an error occurs
5335 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5336 SourceLocation Loc,
5337 ComparisonCategoryUsage Usage);
5338
5339 /// Tests whether Ty is an instance of std::initializer_list and, if
5340 /// it is and Element is not NULL, assigns the element type to Element.
5341 bool isStdInitializerList(QualType Ty, QualType *Element);
5342
5343 /// Tests whether Ty is an instance of std::type_identity and, if
5344 /// it is and TypeArgument is not NULL, assigns the element type to Element.
5345 /// If MalformedDecl is not null, and type_identity was ruled out due to being
5346 /// incorrectly structured despite having the correct name, the faulty Decl
5347 /// will be assigned to MalformedDecl.
5348 bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument,
5349 const Decl **MalformedDecl = nullptr);
5350
5351 /// Looks for the std::initializer_list template and instantiates it
5352 /// with Element, or emits an error if it's not found.
5353 ///
5354 /// \returns The instantiated template, or null on error.
5355 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5356
5357 /// Looks for the std::type_identity template and instantiates it
5358 /// with Type, or returns a null type if type_identity has not been declared
5359 ///
5360 /// \returns The instantiated template, or null if std::type_identity is not
5361 /// declared
5362 QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc);
5363
5364 /// Determine whether Ctor is an initializer-list constructor, as
5365 /// defined in [dcl.init.list]p2.
5366 bool isInitListConstructor(const FunctionDecl *Ctor);
5367
5368 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5369 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5370 SourceLocation IdentLoc,
5371 IdentifierInfo *NamespcName,
5372 const ParsedAttributesView &AttrList);
5373
5374 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5375
5376 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc,
5377 SourceLocation AliasLoc, IdentifierInfo *Alias,
5378 CXXScopeSpec &SS, SourceLocation IdentLoc,
5379 IdentifierInfo *Ident);
5380
5381 /// Remove decls we can't actually see from a lookup being used to declare
5382 /// shadow using decls.
5383 ///
5384 /// \param S - The scope of the potential shadow decl
5385 /// \param Previous - The lookup of a potential shadow decl's name.
5386 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5387
5388 /// Hides a using shadow declaration. This is required by the current
5389 /// using-decl implementation when a resolvable using declaration in a
5390 /// class is followed by a declaration which would hide or override
5391 /// one or more of the using decl's targets; for example:
5392 ///
5393 /// struct Base { void foo(int); };
5394 /// struct Derived : Base {
5395 /// using Base::foo;
5396 /// void foo(int);
5397 /// };
5398 ///
5399 /// The governing language is C++03 [namespace.udecl]p12:
5400 ///
5401 /// When a using-declaration brings names from a base class into a
5402 /// derived class scope, member functions in the derived class
5403 /// override and/or hide member functions with the same name and
5404 /// parameter types in a base class (rather than conflicting).
5405 ///
5406 /// There are two ways to implement this:
5407 /// (1) optimistically create shadow decls when they're not hidden
5408 /// by existing declarations, or
5409 /// (2) don't create any shadow decls (or at least don't make them
5410 /// visible) until we've fully parsed/instantiated the class.
5411 /// The problem with (1) is that we might have to retroactively remove
5412 /// a shadow decl, which requires several O(n) operations because the
5413 /// decl structures are (very reasonably) not designed for removal.
5414 /// (2) avoids this but is very fiddly and phase-dependent.
5415 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5416
5417 /// Determines whether to create a using shadow decl for a particular
5418 /// decl, given the set of decls existing prior to this using lookup.
5419 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5420 const LookupResult &PreviousDecls,
5421 UsingShadowDecl *&PrevShadow);
5422
5423 /// Builds a shadow declaration corresponding to a 'using' declaration.
5424 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5425 NamedDecl *Target,
5426 UsingShadowDecl *PrevDecl);
5427
5428 /// Checks that the given using declaration is not an invalid
5429 /// redeclaration. Note that this is checking only for the using decl
5430 /// itself, not for any ill-formedness among the UsingShadowDecls.
5431 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5432 bool HasTypenameKeyword,
5433 const CXXScopeSpec &SS,
5434 SourceLocation NameLoc,
5435 const LookupResult &Previous);
5436
5437 /// Checks that the given nested-name qualifier used in a using decl
5438 /// in the current context is appropriately related to the current
5439 /// scope. If an error is found, diagnoses it and returns true.
5440 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's
5441 /// the result of that lookup. UD is likewise nullptr, except when we have an
5442 /// already-populated UsingDecl whose shadow decls contain the same
5443 /// information (i.e. we're instantiating a UsingDecl with non-dependent
5444 /// scope).
5445 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5446 const CXXScopeSpec &SS,
5447 const DeclarationNameInfo &NameInfo,
5448 SourceLocation NameLoc,
5449 const LookupResult *R = nullptr,
5450 const UsingDecl *UD = nullptr);
5451
5452 /// Builds a using declaration.
5453 ///
5454 /// \param IsInstantiation - Whether this call arises from an
5455 /// instantiation of an unresolved using declaration. We treat
5456 /// the lookup differently for these declarations.
5457 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5458 SourceLocation UsingLoc,
5459 bool HasTypenameKeyword,
5460 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5461 DeclarationNameInfo NameInfo,
5462 SourceLocation EllipsisLoc,
5463 const ParsedAttributesView &AttrList,
5464 bool IsInstantiation, bool IsUsingIfExists);
5465 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5466 SourceLocation UsingLoc,
5467 SourceLocation EnumLoc,
5468 SourceLocation NameLoc,
5469 TypeSourceInfo *EnumType, EnumDecl *ED);
5470 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5471 ArrayRef<NamedDecl *> Expansions);
5472
5473 /// Additional checks for a using declaration referring to a constructor name.
5474 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5475
5476 /// Given a derived-class using shadow declaration for a constructor and the
5477 /// correspnding base class constructor, find or create the implicit
5478 /// synthesized derived class constructor to use for this initialization.
5479 CXXConstructorDecl *
5480 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5481 ConstructorUsingShadowDecl *DerivedShadow);
5482
5483 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5484 SourceLocation UsingLoc,
5485 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5486 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5487 const ParsedAttributesView &AttrList);
5488 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5489 SourceLocation UsingLoc,
5490 SourceLocation EnumLoc, SourceRange TyLoc,
5491 const IdentifierInfo &II, ParsedType Ty,
5492 const CXXScopeSpec &SS);
5493 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5494 MultiTemplateParamsArg TemplateParams,
5495 SourceLocation UsingLoc, UnqualifiedId &Name,
5496 const ParsedAttributesView &AttrList,
5497 TypeResult Type, Decl *DeclFromDeclSpec);
5498
5499 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5500 /// including handling of its default argument expressions.
5501 ///
5502 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5503 ExprResult BuildCXXConstructExpr(
5504 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5505 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5506 bool HadMultipleCandidates, bool IsListInitialization,
5507 bool IsStdInitListInitialization, bool RequiresZeroInit,
5508 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5509
5510 /// Build a CXXConstructExpr whose constructor has already been resolved if
5511 /// it denotes an inherited constructor.
5512 ExprResult BuildCXXConstructExpr(
5513 SourceLocation ConstructLoc, QualType DeclInitType,
5514 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5515 bool HadMultipleCandidates, bool IsListInitialization,
5516 bool IsStdInitListInitialization, bool RequiresZeroInit,
5517 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5518
5519 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5520 // the constructor can be elidable?
5521 ExprResult BuildCXXConstructExpr(
5522 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
5523 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs,
5524 bool HadMultipleCandidates, bool IsListInitialization,
5525 bool IsStdInitListInitialization, bool RequiresZeroInit,
5526 CXXConstructionKind ConstructKind, SourceRange ParenRange);
5527
5528 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr,
5529 SourceLocation InitLoc);
5530
5531 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
5532 /// constructed variable.
5533 void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit);
5534
5535 /// Helper class that collects exception specifications for
5536 /// implicitly-declared special member functions.
5537 class ImplicitExceptionSpecification {
5538 // Pointer to allow copying
5539 Sema *Self;
5540 // We order exception specifications thus:
5541 // noexcept is the most restrictive, but is only used in C++11.
5542 // throw() comes next.
5543 // Then a throw(collected exceptions)
5544 // Finally no specification, which is expressed as noexcept(false).
5545 // throw(...) is used instead if any called function uses it.
5546 ExceptionSpecificationType ComputedEST;
5547 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
5548 SmallVector<QualType, 4> Exceptions;
5549
5550 void ClearExceptions() {
5551 ExceptionsSeen.clear();
5552 Exceptions.clear();
5553 }
5554
5555 public:
5556 explicit ImplicitExceptionSpecification(Sema &Self)
5557 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
5558 if (!Self.getLangOpts().CPlusPlus11)
5559 ComputedEST = EST_DynamicNone;
5560 }
5561
5562 /// Get the computed exception specification type.
5563 ExceptionSpecificationType getExceptionSpecType() const {
5564 assert(!isComputedNoexcept(ComputedEST) &&
5565 "noexcept(expr) should not be a possible result");
5566 return ComputedEST;
5567 }
5568
5569 /// The number of exceptions in the exception specification.
5570 unsigned size() const { return Exceptions.size(); }
5571
5572 /// The set of exceptions in the exception specification.
5573 const QualType *data() const { return Exceptions.data(); }
5574
5575 /// Integrate another called method into the collected data.
5576 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
5577
5578 /// Integrate an invoked expression into the collected data.
5579 void CalledExpr(Expr *E) { CalledStmt(S: E); }
5580
5581 /// Integrate an invoked statement into the collected data.
5582 void CalledStmt(Stmt *S);
5583
5584 /// Overwrite an EPI's exception specification with this
5585 /// computed exception specification.
5586 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
5587 FunctionProtoType::ExceptionSpecInfo ESI;
5588 ESI.Type = getExceptionSpecType();
5589 if (ESI.Type == EST_Dynamic) {
5590 ESI.Exceptions = Exceptions;
5591 } else if (ESI.Type == EST_None) {
5592 /// C++11 [except.spec]p14:
5593 /// The exception-specification is noexcept(false) if the set of
5594 /// potential exceptions of the special member function contains "any"
5595 ESI.Type = EST_NoexceptFalse;
5596 ESI.NoexceptExpr =
5597 Self->ActOnCXXBoolLiteral(OpLoc: SourceLocation(), Kind: tok::kw_false).get();
5598 }
5599 return ESI;
5600 }
5601 };
5602
5603 /// Evaluate the implicit exception specification for a defaulted
5604 /// special member function.
5605 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
5606
5607 /// Check the given exception-specification and update the
5608 /// exception specification information with the results.
5609 void checkExceptionSpecification(bool IsTopLevel,
5610 ExceptionSpecificationType EST,
5611 ArrayRef<ParsedType> DynamicExceptions,
5612 ArrayRef<SourceRange> DynamicExceptionRanges,
5613 Expr *NoexceptExpr,
5614 SmallVectorImpl<QualType> &Exceptions,
5615 FunctionProtoType::ExceptionSpecInfo &ESI);
5616
5617 /// Add an exception-specification to the given member or friend function
5618 /// (or function template). The exception-specification was parsed
5619 /// after the function itself was declared.
5620 void actOnDelayedExceptionSpecification(
5621 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
5622 ArrayRef<ParsedType> DynamicExceptions,
5623 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr);
5624
5625 class InheritedConstructorInfo;
5626
5627 /// Determine if a special member function should have a deleted
5628 /// definition when it is defaulted.
5629 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
5630 InheritedConstructorInfo *ICI = nullptr,
5631 bool Diagnose = false);
5632
5633 /// Produce notes explaining why a defaulted function was defined as deleted.
5634 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
5635
5636 /// Declare the implicit default constructor for the given class.
5637 ///
5638 /// \param ClassDecl The class declaration into which the implicit
5639 /// default constructor will be added.
5640 ///
5641 /// \returns The implicitly-declared default constructor.
5642 CXXConstructorDecl *
5643 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl);
5644
5645 /// DefineImplicitDefaultConstructor - Checks for feasibility of
5646 /// defining this constructor as the default constructor.
5647 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
5648 CXXConstructorDecl *Constructor);
5649
5650 /// Declare the implicit destructor for the given class.
5651 ///
5652 /// \param ClassDecl The class declaration into which the implicit
5653 /// destructor will be added.
5654 ///
5655 /// \returns The implicitly-declared destructor.
5656 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
5657
5658 /// DefineImplicitDestructor - Checks for feasibility of
5659 /// defining this destructor as the default destructor.
5660 void DefineImplicitDestructor(SourceLocation CurrentLocation,
5661 CXXDestructorDecl *Destructor);
5662
5663 /// Build an exception spec for destructors that don't have one.
5664 ///
5665 /// C++11 says that user-defined destructors with no exception spec get one
5666 /// that looks as if the destructor was implicitly declared.
5667 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
5668
5669 /// Define the specified inheriting constructor.
5670 void DefineInheritingConstructor(SourceLocation UseLoc,
5671 CXXConstructorDecl *Constructor);
5672
5673 /// Declare the implicit copy constructor for the given class.
5674 ///
5675 /// \param ClassDecl The class declaration into which the implicit
5676 /// copy constructor will be added.
5677 ///
5678 /// \returns The implicitly-declared copy constructor.
5679 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
5680
5681 /// DefineImplicitCopyConstructor - Checks for feasibility of
5682 /// defining this constructor as the copy constructor.
5683 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5684 CXXConstructorDecl *Constructor);
5685
5686 /// Declare the implicit move constructor for the given class.
5687 ///
5688 /// \param ClassDecl The Class declaration into which the implicit
5689 /// move constructor will be added.
5690 ///
5691 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
5692 /// declared.
5693 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
5694
5695 /// DefineImplicitMoveConstructor - Checks for feasibility of
5696 /// defining this constructor as the move constructor.
5697 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
5698 CXXConstructorDecl *Constructor);
5699
5700 /// Declare the implicit copy assignment operator for the given class.
5701 ///
5702 /// \param ClassDecl The class declaration into which the implicit
5703 /// copy assignment operator will be added.
5704 ///
5705 /// \returns The implicitly-declared copy assignment operator.
5706 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
5707
5708 /// Defines an implicitly-declared copy assignment operator.
5709 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5710 CXXMethodDecl *MethodDecl);
5711
5712 /// Declare the implicit move assignment operator for the given class.
5713 ///
5714 /// \param ClassDecl The Class declaration into which the implicit
5715 /// move assignment operator will be added.
5716 ///
5717 /// \returns The implicitly-declared move assignment operator, or NULL if it
5718 /// wasn't declared.
5719 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
5720
5721 /// Defines an implicitly-declared move assignment operator.
5722 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
5723 CXXMethodDecl *MethodDecl);
5724
5725 /// Check a completed declaration of an implicit special member.
5726 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
5727
5728 /// Determine whether the given function is an implicitly-deleted
5729 /// special member function.
5730 bool isImplicitlyDeleted(FunctionDecl *FD);
5731
5732 /// Check whether 'this' shows up in the type of a static member
5733 /// function after the (naturally empty) cv-qualifier-seq would be.
5734 ///
5735 /// \returns true if an error occurred.
5736 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
5737
5738 /// Whether this' shows up in the exception specification of a static
5739 /// member function.
5740 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
5741
5742 /// Check whether 'this' shows up in the attributes of the given
5743 /// static member function.
5744 ///
5745 /// \returns true if an error occurred.
5746 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
5747
5748 bool CheckImmediateEscalatingFunctionDefinition(
5749 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI);
5750
5751 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD);
5752
5753 /// Given a constructor and the set of arguments provided for the
5754 /// constructor, convert the arguments and add any required default arguments
5755 /// to form a proper call to this constructor.
5756 ///
5757 /// \returns true if an error occurred, false otherwise.
5758 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
5759 QualType DeclInitType, MultiExprArg ArgsPtr,
5760 SourceLocation Loc,
5761 SmallVectorImpl<Expr *> &ConvertedArgs,
5762 bool AllowExplicit = false,
5763 bool IsListInitialization = false);
5764
5765 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5766 /// initializer for the declaration 'Dcl'.
5767 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5768 /// static data member of class X, names should be looked up in the scope of
5769 /// class X.
5770 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5771
5772 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5773 /// initializer for the declaration 'Dcl'.
5774 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5775
5776 /// Define the "body" of the conversion from a lambda object to a
5777 /// function pointer.
5778 ///
5779 /// This routine doesn't actually define a sensible body; rather, it fills
5780 /// in the initialization expression needed to copy the lambda object into
5781 /// the block, and IR generation actually generates the real body of the
5782 /// block pointer conversion.
5783 void
5784 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc,
5785 CXXConversionDecl *Conv);
5786
5787 /// Define the "body" of the conversion from a lambda object to a
5788 /// block pointer.
5789 ///
5790 /// This routine doesn't actually define a sensible body; rather, it fills
5791 /// in the initialization expression needed to copy the lambda object into
5792 /// the block, and IR generation actually generates the real body of the
5793 /// block pointer conversion.
5794 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5795 CXXConversionDecl *Conv);
5796
5797 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5798 /// linkage specification, including the language and (if present)
5799 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
5800 /// language string literal. LBraceLoc, if valid, provides the location of
5801 /// the '{' brace. Otherwise, this linkage specification does not
5802 /// have any braces.
5803 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
5804 Expr *LangStr, SourceLocation LBraceLoc);
5805
5806 /// ActOnFinishLinkageSpecification - Complete the definition of
5807 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
5808 /// valid, it's the position of the closing '}' brace in a linkage
5809 /// specification that uses braces.
5810 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec,
5811 SourceLocation RBraceLoc);
5812
5813 //===--------------------------------------------------------------------===//
5814 // C++ Classes
5815 //
5816
5817 /// Get the class that is directly named by the current context. This is the
5818 /// class for which an unqualified-id in this scope could name a constructor
5819 /// or destructor.
5820 ///
5821 /// If the scope specifier denotes a class, this will be that class.
5822 /// If the scope specifier is empty, this will be the class whose
5823 /// member-specification we are currently within. Otherwise, there
5824 /// is no such class.
5825 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
5826
5827 /// isCurrentClassName - Determine whether the identifier II is the
5828 /// name of the class type currently being defined. In the case of
5829 /// nested classes, this will only return true if II is the name of
5830 /// the innermost class.
5831 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5832 const CXXScopeSpec *SS = nullptr);
5833
5834 /// Determine whether the identifier II is a typo for the name of
5835 /// the class type currently being defined. If so, update it to the identifier
5836 /// that should have been used.
5837 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5838
5839 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
5840 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
5841 SourceLocation ColonLoc,
5842 const ParsedAttributesView &Attrs);
5843
5844 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
5845 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
5846 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
5847 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
5848 /// present (but parsing it has been deferred).
5849 NamedDecl *
5850 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
5851 MultiTemplateParamsArg TemplateParameterLists,
5852 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5853 InClassInitStyle InitStyle);
5854
5855 /// Enter a new C++ default initializer scope. After calling this, the
5856 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
5857 /// parsing or instantiating the initializer failed.
5858 void ActOnStartCXXInClassMemberInitializer();
5859
5860 /// This is invoked after parsing an in-class initializer for a
5861 /// non-static C++ class member, and after instantiating an in-class
5862 /// initializer in a class template. Such actions are deferred until the class
5863 /// is complete.
5864 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5865 SourceLocation EqualLoc,
5866 ExprResult Init);
5867
5868 /// Handle a C++ member initializer using parentheses syntax.
5869 MemInitResult
5870 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS,
5871 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy,
5872 const DeclSpec &DS, SourceLocation IdLoc,
5873 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
5874 SourceLocation RParenLoc, SourceLocation EllipsisLoc);
5875
5876 /// Handle a C++ member initializer using braced-init-list syntax.
5877 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S,
5878 CXXScopeSpec &SS,
5879 IdentifierInfo *MemberOrBase,
5880 ParsedType TemplateTypeTy,
5881 const DeclSpec &DS, SourceLocation IdLoc,
5882 Expr *InitList, SourceLocation EllipsisLoc);
5883
5884 /// Handle a C++ member initializer.
5885 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S,
5886 CXXScopeSpec &SS,
5887 IdentifierInfo *MemberOrBase,
5888 ParsedType TemplateTypeTy,
5889 const DeclSpec &DS, SourceLocation IdLoc,
5890 Expr *Init, SourceLocation EllipsisLoc);
5891
5892 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init,
5893 SourceLocation IdLoc);
5894
5895 MemInitResult BuildBaseInitializer(QualType BaseType,
5896 TypeSourceInfo *BaseTInfo, Expr *Init,
5897 CXXRecordDecl *ClassDecl,
5898 SourceLocation EllipsisLoc);
5899
5900 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
5901 CXXRecordDecl *ClassDecl);
5902
5903 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5904 CXXCtorInitializer *Initializer);
5905
5906 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5907 ArrayRef<CXXCtorInitializer *> Initializers = {});
5908
5909 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5910 /// mark all the non-trivial destructors of its members and bases as
5911 /// referenced.
5912 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5913 CXXRecordDecl *Record);
5914
5915 /// Mark destructors of virtual bases of this class referenced. In the Itanium
5916 /// C++ ABI, this is done when emitting a destructor for any non-abstract
5917 /// class. In the Microsoft C++ ABI, this is done any time a class's
5918 /// destructor is referenced.
5919 void MarkVirtualBaseDestructorsReferenced(
5920 SourceLocation Location, CXXRecordDecl *ClassDecl,
5921 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases =
5922 nullptr);
5923
5924 /// Do semantic checks to allow the complete destructor variant to be emitted
5925 /// when the destructor is defined in another translation unit. In the Itanium
5926 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
5927 /// can be emitted in separate TUs. To emit the complete variant, run a subset
5928 /// of the checks performed when emitting a regular destructor.
5929 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
5930 CXXDestructorDecl *Dtor);
5931
5932 /// The list of classes whose vtables have been used within
5933 /// this translation unit, and the source locations at which the
5934 /// first use occurred.
5935 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse;
5936
5937 /// The list of vtables that are required but have not yet been
5938 /// materialized.
5939 SmallVector<VTableUse, 16> VTableUses;
5940
5941 /// The set of classes whose vtables have been used within
5942 /// this translation unit, and a bit that will be true if the vtable is
5943 /// required to be emitted (otherwise, it should be emitted only if needed
5944 /// by code generation).
5945 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5946
5947 /// Load any externally-stored vtable uses.
5948 void LoadExternalVTableUses();
5949
5950 /// Note that the vtable for the given class was used at the
5951 /// given location.
5952 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5953 bool DefinitionRequired = false);
5954
5955 /// Mark the exception specifications of all virtual member functions
5956 /// in the given class as needed.
5957 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5958 const CXXRecordDecl *RD);
5959
5960 /// MarkVirtualMembersReferenced - Will mark all members of the given
5961 /// CXXRecordDecl referenced.
5962 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
5963 bool ConstexprOnly = false);
5964
5965 /// Define all of the vtables that have been used in this
5966 /// translation unit and reference any virtual members used by those
5967 /// vtables.
5968 ///
5969 /// \returns true if any work was done, false otherwise.
5970 bool DefineUsedVTables();
5971
5972 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5973 /// special functions, such as the default constructor, copy
5974 /// constructor, or destructor, to the given C++ class (C++
5975 /// [special]p1). This routine can only be executed just before the
5976 /// definition of the class is complete.
5977 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5978
5979 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5980 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc,
5981 ArrayRef<CXXCtorInitializer *> MemInits,
5982 bool AnyErrors);
5983
5984 /// Check class-level dllimport/dllexport attribute. The caller must
5985 /// ensure that referenceDLLExportedClassMethods is called some point later
5986 /// when all outer classes of Class are complete.
5987 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5988 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
5989
5990 void referenceDLLExportedClassMethods();
5991
5992 /// Perform propagation of DLL attributes from a derived class to a
5993 /// templated base class for MS compatibility.
5994 void propagateDLLAttrToBaseClassTemplate(
5995 CXXRecordDecl *Class, Attr *ClassAttr,
5996 ClassTemplateSpecializationDecl *BaseTemplateSpec,
5997 SourceLocation BaseLoc);
5998
5999 /// Perform semantic checks on a class definition that has been
6000 /// completing, introducing implicitly-declared members, checking for
6001 /// abstract types, etc.
6002 ///
6003 /// \param S The scope in which the class was parsed. Null if we didn't just
6004 /// parse a class definition.
6005 /// \param Record The completed class.
6006 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
6007
6008 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
6009 /// conditions that are needed for the attribute to have an effect.
6010 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
6011
6012 /// Check that VTable Pointer authentication is only being set on the first
6013 /// first instantiation of the vtable
6014 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD);
6015
6016 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
6017 Decl *TagDecl, SourceLocation LBrac,
6018 SourceLocation RBrac,
6019 const ParsedAttributesView &AttrList);
6020
6021 /// Perform any semantic analysis which needs to be delayed until all
6022 /// pending class member declarations have been parsed.
6023 void ActOnFinishCXXMemberDecls();
6024 void ActOnFinishCXXNonNestedClass();
6025
6026 /// This is used to implement the constant expression evaluation part of the
6027 /// attribute enable_if extension. There is nothing in standard C++ which
6028 /// would require reentering parameters.
6029 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
6030 unsigned ActOnReenterTemplateScope(Decl *Template,
6031 llvm::function_ref<Scope *()> EnterScope);
6032 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
6033
6034 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6035 /// parsing a top-level (non-nested) C++ class, and we are now
6036 /// parsing those parts of the given Method declaration that could
6037 /// not be parsed earlier (C++ [class.mem]p2), such as default
6038 /// arguments. This action should enter the scope of the given
6039 /// Method declaration as if we had just parsed the qualified method
6040 /// name. However, it should not bring the parameters into scope;
6041 /// that will be performed by ActOnDelayedCXXMethodParameter.
6042 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6043 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
6044 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
6045
6046 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6047 /// processing the delayed method declaration for Method. The method
6048 /// declaration is now considered finished. There may be a separate
6049 /// ActOnStartOfFunctionDef action later (not necessarily
6050 /// immediately!) for this method, if it was also defined inside the
6051 /// class body.
6052 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
6053 void ActOnFinishDelayedMemberInitializers(Decl *Record);
6054
6055 enum class StringEvaluationContext { StaticAssert = 0, Asm = 1 };
6056
6057 bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
6058 StringEvaluationContext EvalContext,
6059 bool ErrorOnInvalidMessage);
6060 bool EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
6061 StringEvaluationContext EvalContext,
6062 bool ErrorOnInvalidMessage);
6063
6064 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6065 Expr *AssertExpr, Expr *AssertMessageExpr,
6066 SourceLocation RParenLoc);
6067 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
6068 Expr *AssertExpr, Expr *AssertMessageExpr,
6069 SourceLocation RParenLoc, bool Failed);
6070
6071 /// Try to print more useful information about a failed static_assert
6072 /// with expression \E
6073 void DiagnoseStaticAssertDetails(const Expr *E);
6074
6075 /// If E represents a built-in type trait, or a known standard type trait,
6076 /// try to print more information about why the type type-trait failed.
6077 /// This assumes we already evaluated the expression to a false boolean value.
6078 void DiagnoseTypeTraitDetails(const Expr *E);
6079
6080 /// Handle a friend type declaration. This works in tandem with
6081 /// ActOnTag.
6082 ///
6083 /// Notes on friend class templates:
6084 ///
6085 /// We generally treat friend class declarations as if they were
6086 /// declaring a class. So, for example, the elaborated type specifier
6087 /// in a friend declaration is required to obey the restrictions of a
6088 /// class-head (i.e. no typedefs in the scope chain), template
6089 /// parameters are required to match up with simple template-ids, &c.
6090 /// However, unlike when declaring a template specialization, it's
6091 /// okay to refer to a template specialization without an empty
6092 /// template parameter declaration, e.g.
6093 /// friend class A<T>::B<unsigned>;
6094 /// We permit this as a special case; if there are any template
6095 /// parameters present at all, require proper matching, i.e.
6096 /// template <> template \<class T> friend class A<int>::B;
6097 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
6098 MultiTemplateParamsArg TemplateParams,
6099 SourceLocation EllipsisLoc);
6100 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
6101 MultiTemplateParamsArg TemplateParams);
6102
6103 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6104 /// the well-formedness of the constructor declarator @p D with type @p
6105 /// R. If there are any errors in the declarator, this routine will
6106 /// emit diagnostics and set the invalid bit to true. In any case, the type
6107 /// will be updated to reflect a well-formed type for the constructor and
6108 /// returned.
6109 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
6110 StorageClass &SC);
6111
6112 /// CheckConstructor - Checks a fully-formed constructor for
6113 /// well-formedness, issuing any diagnostics required. Returns true if
6114 /// the constructor declarator is invalid.
6115 void CheckConstructor(CXXConstructorDecl *Constructor);
6116
6117 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6118 /// the well-formednes of the destructor declarator @p D with type @p
6119 /// R. If there are any errors in the declarator, this routine will
6120 /// emit diagnostics and set the declarator to invalid. Even if this happens,
6121 /// will be updated to reflect a well-formed type for the destructor and
6122 /// returned.
6123 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
6124 StorageClass &SC);
6125
6126 /// CheckDestructor - Checks a fully-formed destructor definition for
6127 /// well-formedness, issuing any diagnostics required. Returns true
6128 /// on error.
6129 bool CheckDestructor(CXXDestructorDecl *Destructor);
6130
6131 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6132 /// well-formednes of the conversion function declarator @p D with
6133 /// type @p R. If there are any errors in the declarator, this routine
6134 /// will emit diagnostics and return true. Otherwise, it will return
6135 /// false. Either way, the type @p R will be updated to reflect a
6136 /// well-formed type for the conversion operator.
6137 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC);
6138
6139 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6140 /// the declaration of the given C++ conversion function. This routine
6141 /// is responsible for recording the conversion function in the C++
6142 /// class, if possible.
6143 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
6144
6145 /// Check the validity of a declarator that we parsed for a deduction-guide.
6146 /// These aren't actually declarators in the grammar, so we need to check that
6147 /// the user didn't specify any pieces that are not part of the
6148 /// deduction-guide grammar. Return true on invalid deduction-guide.
6149 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
6150 StorageClass &SC);
6151
6152 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
6153
6154 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
6155 CXXSpecialMemberKind CSM,
6156 SourceLocation DefaultLoc);
6157 void CheckDelayedMemberExceptionSpecs();
6158
6159 /// Kinds of defaulted comparison operator functions.
6160 enum class DefaultedComparisonKind : unsigned char {
6161 /// This is not a defaultable comparison operator.
6162 None,
6163 /// This is an operator== that should be implemented as a series of
6164 /// subobject comparisons.
6165 Equal,
6166 /// This is an operator<=> that should be implemented as a series of
6167 /// subobject comparisons.
6168 ThreeWay,
6169 /// This is an operator!= that should be implemented as a rewrite in terms
6170 /// of a == comparison.
6171 NotEqual,
6172 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
6173 /// terms of a <=> comparison.
6174 Relational,
6175 };
6176
6177 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
6178 DefaultedComparisonKind DCK);
6179 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
6180 FunctionDecl *Spaceship);
6181 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
6182 DefaultedComparisonKind DCK);
6183
6184 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name,
6185 QualType R, bool IsLambda,
6186 DeclContext *DC = nullptr);
6187 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
6188 DeclarationName Name, QualType R);
6189 void CheckExplicitObjectLambda(Declarator &D);
6190
6191 //===--------------------------------------------------------------------===//
6192 // C++ Derived Classes
6193 //
6194
6195 /// Check the validity of a C++ base class specifier.
6196 ///
6197 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
6198 /// and returns NULL otherwise.
6199 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
6200 SourceRange SpecifierRange, bool Virtual,
6201 AccessSpecifier Access,
6202 TypeSourceInfo *TInfo,
6203 SourceLocation EllipsisLoc);
6204
6205 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
6206 /// one entry in the base class list of a class specifier, for
6207 /// example:
6208 /// class foo : public bar, virtual private baz {
6209 /// 'public bar' and 'virtual private baz' are each base-specifiers.
6210 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
6211 const ParsedAttributesView &Attrs, bool Virtual,
6212 AccessSpecifier Access, ParsedType basetype,
6213 SourceLocation BaseLoc,
6214 SourceLocation EllipsisLoc);
6215
6216 /// Performs the actual work of attaching the given base class
6217 /// specifiers to a C++ class.
6218 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
6219 MutableArrayRef<CXXBaseSpecifier *> Bases);
6220
6221 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
6222 /// class, after checking whether there are any duplicate base
6223 /// classes.
6224 void ActOnBaseSpecifiers(Decl *ClassDecl,
6225 MutableArrayRef<CXXBaseSpecifier *> Bases);
6226
6227 /// Determine whether the type \p Derived is a C++ class that is
6228 /// derived from the type \p Base.
6229 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6230 CXXRecordDecl *Base, CXXBasePaths &Paths);
6231 bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
6232 CXXRecordDecl *Base);
6233 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
6234 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
6235 CXXBasePaths &Paths);
6236
6237 // FIXME: I don't like this name.
6238 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
6239
6240 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6241 SourceLocation Loc, SourceRange Range,
6242 CXXCastPath *BasePath = nullptr,
6243 bool IgnoreAccess = false);
6244
6245 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
6246 /// conversion (where Derived and Base are class types) is
6247 /// well-formed, meaning that the conversion is unambiguous (and
6248 /// that all of the base classes are accessible). Returns true
6249 /// and emits a diagnostic if the code is ill-formed, returns false
6250 /// otherwise. Loc is the location where this routine should point to
6251 /// if there is an error, and Range is the source range to highlight
6252 /// if there is an error.
6253 ///
6254 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
6255 /// diagnostic for the respective type of error will be suppressed, but the
6256 /// check for ill-formed code will still be performed.
6257 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
6258 unsigned InaccessibleBaseID,
6259 unsigned AmbiguousBaseConvID,
6260 SourceLocation Loc, SourceRange Range,
6261 DeclarationName Name, CXXCastPath *BasePath,
6262 bool IgnoreAccess = false);
6263
6264 /// Builds a string representing ambiguous paths from a
6265 /// specific derived class to different subobjects of the same base
6266 /// class.
6267 ///
6268 /// This function builds a string that can be used in error messages
6269 /// to show the different paths that one can take through the
6270 /// inheritance hierarchy to go from the derived class to different
6271 /// subobjects of a base class. The result looks something like this:
6272 /// @code
6273 /// struct D -> struct B -> struct A
6274 /// struct D -> struct C -> struct A
6275 /// @endcode
6276 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
6277
6278 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New,
6279 const CXXMethodDecl *Old);
6280
6281 /// CheckOverridingFunctionReturnType - Checks whether the return types are
6282 /// covariant, according to C++ [class.virtual]p5.
6283 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
6284 const CXXMethodDecl *Old);
6285
6286 // Check that the overriding method has no explicit object parameter.
6287 bool CheckExplicitObjectOverride(CXXMethodDecl *New,
6288 const CXXMethodDecl *Old);
6289
6290 /// Mark the given method pure.
6291 ///
6292 /// \param Method the method to be marked pure.
6293 ///
6294 /// \param InitRange the source range that covers the "0" initializer.
6295 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
6296
6297 /// CheckOverrideControl - Check C++11 override control semantics.
6298 void CheckOverrideControl(NamedDecl *D);
6299
6300 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
6301 /// not used in the declaration of an overriding method.
6302 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
6303
6304 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
6305 /// function overrides a virtual member function marked 'final', according to
6306 /// C++11 [class.virtual]p4.
6307 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
6308 const CXXMethodDecl *Old);
6309
6310 enum AbstractDiagSelID {
6311 AbstractNone = -1,
6312 AbstractReturnType,
6313 AbstractParamType,
6314 AbstractVariableType,
6315 AbstractFieldType,
6316 AbstractIvarType,
6317 AbstractSynthesizedIvarType,
6318 AbstractArrayType
6319 };
6320
6321 struct TypeDiagnoser;
6322
6323 bool isAbstractType(SourceLocation Loc, QualType T);
6324 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
6325 TypeDiagnoser &Diagnoser);
6326 template <typename... Ts>
6327 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
6328 const Ts &...Args) {
6329 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
6330 return RequireNonAbstractType(Loc, T, Diagnoser);
6331 }
6332
6333 void DiagnoseAbstractType(const CXXRecordDecl *RD);
6334
6335 //===--------------------------------------------------------------------===//
6336 // C++ Overloaded Operators [C++ 13.5]
6337 //
6338
6339 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6340 /// of this overloaded operator is well-formed. If so, returns false;
6341 /// otherwise, emits appropriate diagnostics and returns true.
6342 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
6343
6344 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6345 /// of this literal operator function is well-formed. If so, returns
6346 /// false; otherwise, emits appropriate diagnostics and returns true.
6347 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
6348
6349 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
6350 /// found in an explicit(bool) specifier.
6351 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
6352
6353 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
6354 /// Returns true if the explicit specifier is now resolved.
6355 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
6356
6357 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6358 /// C++ if/switch/while/for statement.
6359 /// e.g: "if (int x = f()) {...}"
6360 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
6361
6362 // Emitting members of dllexported classes is delayed until the class
6363 // (including field initializers) is fully parsed.
6364 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses;
6365 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions;
6366
6367 /// Merge the exception specifications of two variable declarations.
6368 ///
6369 /// This is called when there's a redeclaration of a VarDecl. The function
6370 /// checks if the redeclaration might have an exception specification and
6371 /// validates compatibility and merges the specs if necessary.
6372 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
6373
6374 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
6375 /// function, once we already know that they have the same
6376 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
6377 /// error, false otherwise.
6378 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
6379
6380 /// Helpers for dealing with blocks and functions.
6381 void CheckCXXDefaultArguments(FunctionDecl *FD);
6382
6383 /// CheckExtraCXXDefaultArguments - Check for any extra default
6384 /// arguments in the declarator, which is not a function declaration
6385 /// or definition and therefore is not permitted to have default
6386 /// arguments. This routine should be invoked for every declarator
6387 /// that is not a function declaration or definition.
6388 void CheckExtraCXXDefaultArguments(Declarator &D);
6389
6390 CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD) {
6391 return getDefaultedFunctionKind(FD: MD).asSpecialMember();
6392 }
6393
6394 /// Perform semantic analysis for the variable declaration that
6395 /// occurs within a C++ catch clause, returning the newly-created
6396 /// variable.
6397 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
6398 SourceLocation StartLoc,
6399 SourceLocation IdLoc,
6400 const IdentifierInfo *Id);
6401
6402 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6403 /// handler.
6404 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
6405
6406 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
6407
6408 /// Handle a friend tag declaration where the scope specifier was
6409 /// templated.
6410 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
6411 unsigned TagSpec, SourceLocation TagLoc,
6412 CXXScopeSpec &SS, IdentifierInfo *Name,
6413 SourceLocation NameLoc,
6414 SourceLocation EllipsisLoc,
6415 const ParsedAttributesView &Attr,
6416 MultiTemplateParamsArg TempParamLists);
6417
6418 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
6419 SourceLocation DeclStart, Declarator &D,
6420 Expr *BitfieldWidth,
6421 InClassInitStyle InitStyle,
6422 AccessSpecifier AS,
6423 const ParsedAttr &MSPropertyAttr);
6424
6425 /// Diagnose why the specified class does not have a trivial special member of
6426 /// the given kind.
6427 void DiagnoseNontrivial(const CXXRecordDecl *Record,
6428 CXXSpecialMemberKind CSM);
6429
6430 /// Determine whether a defaulted or deleted special member function is
6431 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6432 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6433 bool SpecialMemberIsTrivial(
6434 CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
6435 TrivialABIHandling TAH = TrivialABIHandling::IgnoreTrivialABI,
6436 bool Diagnose = false);
6437
6438 /// For a defaulted function, the kind of defaulted function that it is.
6439 class DefaultedFunctionKind {
6440 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind)
6441 unsigned SpecialMember : 8;
6442 unsigned Comparison : 8;
6443
6444 public:
6445 DefaultedFunctionKind()
6446 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6447 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6448 DefaultedFunctionKind(CXXSpecialMemberKind CSM)
6449 : SpecialMember(llvm::to_underlying(E: CSM)),
6450 Comparison(llvm::to_underlying(E: DefaultedComparisonKind::None)) {}
6451 DefaultedFunctionKind(DefaultedComparisonKind Comp)
6452 : SpecialMember(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid)),
6453 Comparison(llvm::to_underlying(E: Comp)) {}
6454
6455 bool isSpecialMember() const {
6456 return static_cast<CXXSpecialMemberKind>(SpecialMember) !=
6457 CXXSpecialMemberKind::Invalid;
6458 }
6459 bool isComparison() const {
6460 return static_cast<DefaultedComparisonKind>(Comparison) !=
6461 DefaultedComparisonKind::None;
6462 }
6463
6464 explicit operator bool() const {
6465 return isSpecialMember() || isComparison();
6466 }
6467
6468 CXXSpecialMemberKind asSpecialMember() const {
6469 return static_cast<CXXSpecialMemberKind>(SpecialMember);
6470 }
6471 DefaultedComparisonKind asComparison() const {
6472 return static_cast<DefaultedComparisonKind>(Comparison);
6473 }
6474
6475 /// Get the index of this function kind for use in diagnostics.
6476 unsigned getDiagnosticIndex() const {
6477 static_assert(llvm::to_underlying(E: CXXSpecialMemberKind::Invalid) >
6478 llvm::to_underlying(E: CXXSpecialMemberKind::Destructor),
6479 "invalid should have highest index");
6480 static_assert((unsigned)DefaultedComparisonKind::None == 0,
6481 "none should be equal to zero");
6482 return SpecialMember + Comparison;
6483 }
6484 };
6485
6486 /// Determine the kind of defaulting that would be done for a given function.
6487 ///
6488 /// If the function is both a default constructor and a copy / move
6489 /// constructor (due to having a default argument for the first parameter),
6490 /// this picks CXXSpecialMemberKind::DefaultConstructor.
6491 ///
6492 /// FIXME: Check that case is properly handled by all callers.
6493 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
6494
6495 /// Handle a C++11 empty-declaration and attribute-declaration.
6496 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
6497 SourceLocation SemiLoc);
6498
6499 enum class CheckConstexprKind {
6500 /// Diagnose issues that are non-constant or that are extensions.
6501 Diagnose,
6502 /// Identify whether this function satisfies the formal rules for constexpr
6503 /// functions in the current lanugage mode (with no extensions).
6504 CheckValid
6505 };
6506
6507 // Check whether a function declaration satisfies the requirements of a
6508 // constexpr function definition or a constexpr constructor definition. If so,
6509 // return true. If not, produce appropriate diagnostics (unless asked not to
6510 // by Kind) and return false.
6511 //
6512 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
6513 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
6514 CheckConstexprKind Kind);
6515
6516 /// Diagnose methods which overload virtual methods in a base class
6517 /// without overriding any.
6518 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
6519
6520 /// Check if a method overloads virtual methods in a base class without
6521 /// overriding any.
6522 void
6523 FindHiddenVirtualMethods(CXXMethodDecl *MD,
6524 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6525 void
6526 NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6527 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods);
6528
6529 /// ActOnParamDefaultArgument - Check whether the default argument
6530 /// provided for a function parameter is well-formed. If so, attach it
6531 /// to the parameter declaration.
6532 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
6533 Expr *defarg);
6534
6535 /// ActOnParamUnparsedDefaultArgument - We've seen a default
6536 /// argument for a function parameter, but we can't parse it yet
6537 /// because we're inside a class definition. Note that this default
6538 /// argument will be parsed later.
6539 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
6540 SourceLocation ArgLoc);
6541
6542 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
6543 /// the default argument for the parameter param failed.
6544 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
6545 Expr *DefaultArg);
6546 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6547 SourceLocation EqualLoc);
6548 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
6549 SourceLocation EqualLoc);
6550
6551 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
6552 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc,
6553 StringLiteral *Message = nullptr);
6554 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
6555
6556 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
6557 StringLiteral *DeletedMessage = nullptr);
6558 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
6559 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
6560 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
6561
6562 NamedDecl *
6563 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
6564 MultiTemplateParamsArg TemplateParamLists);
6565 void DiagPlaceholderVariableDefinition(SourceLocation Loc);
6566 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
6567 RecordDecl *ClassDecl,
6568 const IdentifierInfo *Name);
6569
6570 UnsignedOrNone GetDecompositionElementCount(QualType DecompType,
6571 SourceLocation Loc);
6572 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
6573
6574 /// Stack containing information needed when in C++2a an 'auto' is encountered
6575 /// in a function declaration parameter type specifier in order to invent a
6576 /// corresponding template parameter in the enclosing abbreviated function
6577 /// template. This information is also present in LambdaScopeInfo, stored in
6578 /// the FunctionScopes stack.
6579 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
6580
6581 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
6582 std::unique_ptr<CXXFieldCollector> FieldCollector;
6583
6584 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
6585 /// Set containing all declared private fields that are not used.
6586 NamedDeclSetType UnusedPrivateFields;
6587
6588 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy;
6589
6590 /// PureVirtualClassDiagSet - a set of class declarations which we have
6591 /// emitted a list of pure virtual functions. Used to prevent emitting the
6592 /// same list more than once.
6593 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
6594
6595 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
6596 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
6597 DelegatingCtorDeclsType;
6598
6599 /// All the delegating constructors seen so far in the file, used for
6600 /// cycle detection at the end of the TU.
6601 DelegatingCtorDeclsType DelegatingCtorDecls;
6602
6603 /// The C++ "std" namespace, where the standard library resides.
6604 LazyDeclPtr StdNamespace;
6605
6606 /// The C++ "std::initializer_list" template, which is defined in
6607 /// \<initializer_list>.
6608 ClassTemplateDecl *StdInitializerList;
6609
6610 /// The C++ "std::type_identity" template, which is defined in
6611 /// \<type_traits>.
6612 ClassTemplateDecl *StdTypeIdentity;
6613
6614 // Contains the locations of the beginning of unparsed default
6615 // argument locations.
6616 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
6617
6618 /// UndefinedInternals - all the used, undefined objects which require a
6619 /// definition in this translation unit.
6620 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
6621
6622 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind>
6623 SpecialMemberDecl;
6624
6625 /// The C++ special members which we are currently in the process of
6626 /// declaring. If this process recursively triggers the declaration of the
6627 /// same special member, we should act as if it is not yet declared.
6628 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
6629
6630 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
6631
6632 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
6633
6634 typedef ProcessingContextState ParsingClassState;
6635 ParsingClassState PushParsingClass() {
6636 ParsingClassDepth++;
6637 return DelayedDiagnostics.pushUndelayed();
6638 }
6639 void PopParsingClass(ParsingClassState state) {
6640 ParsingClassDepth--;
6641 DelayedDiagnostics.popUndelayed(state);
6642 }
6643
6644 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
6645 CXXScopeSpec &SS,
6646 ParsedType TemplateTypeTy,
6647 IdentifierInfo *MemberOrBase);
6648
6649private:
6650 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
6651 QualType ResultTy,
6652 ArrayRef<QualType> Args);
6653 // Helper for ActOnFields to check for all function pointer members.
6654 bool EntirelyFunctionPointers(const RecordDecl *Record);
6655
6656 // A cache representing if we've fully checked the various comparison category
6657 // types stored in ASTContext. The bit-index corresponds to the integer value
6658 // of a ComparisonCategoryType enumerator.
6659 llvm::SmallBitVector FullyCheckedComparisonCategories;
6660
6661 /// Check if there is a field shadowing.
6662 void CheckShadowInheritedFields(const SourceLocation &Loc,
6663 DeclarationName FieldName,
6664 const CXXRecordDecl *RD,
6665 bool DeclIsField = true);
6666
6667 ///@}
6668
6669 //
6670 //
6671 // -------------------------------------------------------------------------
6672 //
6673 //
6674
6675 /// \name C++ Exception Specifications
6676 /// Implementations are in SemaExceptionSpec.cpp
6677 ///@{
6678
6679public:
6680 /// All the overriding functions seen during a class definition
6681 /// that had their exception spec checks delayed, plus the overridden
6682 /// function.
6683 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2>
6684 DelayedOverridingExceptionSpecChecks;
6685
6686 /// All the function redeclarations seen during a class definition that had
6687 /// their exception spec checks delayed, plus the prior declaration they
6688 /// should be checked against. Except during error recovery, the new decl
6689 /// should always be a friend declaration, as that's the only valid way to
6690 /// redeclare a special member before its class is complete.
6691 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2>
6692 DelayedEquivalentExceptionSpecChecks;
6693
6694 /// Determine if we're in a case where we need to (incorrectly) eagerly
6695 /// parse an exception specification to work around a libstdc++ bug.
6696 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6697
6698 /// Check the given noexcept-specifier, convert its expression, and compute
6699 /// the appropriate ExceptionSpecificationType.
6700 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6701 ExceptionSpecificationType &EST);
6702
6703 CanThrowResult canThrow(const Stmt *E);
6704 /// Determine whether the callee of a particular function call can throw.
6705 /// E, D and Loc are all optional.
6706 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
6707 SourceLocation Loc = SourceLocation());
6708 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
6709 const FunctionProtoType *FPT);
6710 void UpdateExceptionSpec(FunctionDecl *FD,
6711 const FunctionProtoType::ExceptionSpecInfo &ESI);
6712
6713 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
6714 /// exception specification. Incomplete types, or pointers to incomplete types
6715 /// other than void are not allowed.
6716 ///
6717 /// \param[in,out] T The exception type. This will be decayed to a pointer
6718 /// type
6719 /// when the input is an array or a function type.
6720 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
6721
6722 /// CheckDistantExceptionSpec - Check if the given type is a pointer or
6723 /// pointer to member to a function with an exception specification. This
6724 /// means that it is invalid to add another level of indirection.
6725 bool CheckDistantExceptionSpec(QualType T);
6726 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
6727
6728 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
6729 /// exception specifications. Exception specifications are equivalent if
6730 /// they allow exactly the same set of exception types. It does not matter how
6731 /// that is achieved. See C++ [except.spec]p2.
6732 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old,
6733 SourceLocation OldLoc,
6734 const FunctionProtoType *New,
6735 SourceLocation NewLoc);
6736 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID,
6737 const PartialDiagnostic &NoteID,
6738 const FunctionProtoType *Old,
6739 SourceLocation OldLoc,
6740 const FunctionProtoType *New,
6741 SourceLocation NewLoc);
6742 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
6743
6744 /// CheckExceptionSpecSubset - Check whether the second function type's
6745 /// exception specification is a subset (or equivalent) of the first function
6746 /// type. This is used by override and pointer assignment checks.
6747 bool CheckExceptionSpecSubset(
6748 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID,
6749 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID,
6750 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter,
6751 SourceLocation SuperLoc, const FunctionProtoType *Subset,
6752 bool SkipSubsetFirstParameter, SourceLocation SubLoc);
6753
6754 /// CheckParamExceptionSpec - Check if the parameter and return types of the
6755 /// two functions have equivalent exception specs. This is part of the
6756 /// assignment and override compatibility check. We do not check the
6757 /// parameters of parameter function pointers recursively, as no sane
6758 /// programmer would even be able to write such a function type.
6759 bool CheckParamExceptionSpec(
6760 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID,
6761 const FunctionProtoType *Target, bool SkipTargetFirstParameter,
6762 SourceLocation TargetLoc, const FunctionProtoType *Source,
6763 bool SkipSourceFirstParameter, SourceLocation SourceLoc);
6764
6765 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
6766
6767 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
6768 /// spec is a subset of base spec.
6769 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
6770 const CXXMethodDecl *Old);
6771
6772 ///@}
6773
6774 //
6775 //
6776 // -------------------------------------------------------------------------
6777 //
6778 //
6779
6780 /// \name Expressions
6781 /// Implementations are in SemaExpr.cpp
6782 ///@{
6783
6784public:
6785 /// Describes how the expressions currently being parsed are
6786 /// evaluated at run-time, if at all.
6787 enum class ExpressionEvaluationContext {
6788 /// The current expression and its subexpressions occur within an
6789 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
6790 /// \c sizeof, where the type of the expression may be significant but
6791 /// no code will be generated to evaluate the value of the expression at
6792 /// run time.
6793 Unevaluated,
6794
6795 /// The current expression occurs within a braced-init-list within
6796 /// an unevaluated operand. This is mostly like a regular unevaluated
6797 /// context, except that we still instantiate constexpr functions that are
6798 /// referenced here so that we can perform narrowing checks correctly.
6799 UnevaluatedList,
6800
6801 /// The current expression occurs within a discarded statement.
6802 /// This behaves largely similarly to an unevaluated operand in preventing
6803 /// definitions from being required, but not in other ways.
6804 DiscardedStatement,
6805
6806 /// The current expression occurs within an unevaluated
6807 /// operand that unconditionally permits abstract references to
6808 /// fields, such as a SIZE operator in MS-style inline assembly.
6809 UnevaluatedAbstract,
6810
6811 /// The current context is "potentially evaluated" in C++11 terms,
6812 /// but the expression is evaluated at compile-time (like the values of
6813 /// cases in a switch statement).
6814 ConstantEvaluated,
6815
6816 /// In addition of being constant evaluated, the current expression
6817 /// occurs in an immediate function context - either a consteval function
6818 /// or a consteval if statement.
6819 ImmediateFunctionContext,
6820
6821 /// The current expression is potentially evaluated at run time,
6822 /// which means that code may be generated to evaluate the value of the
6823 /// expression at run time.
6824 PotentiallyEvaluated,
6825
6826 /// The current expression is potentially evaluated, but any
6827 /// declarations referenced inside that expression are only used if
6828 /// in fact the current expression is used.
6829 ///
6830 /// This value is used when parsing default function arguments, for which
6831 /// we would like to provide diagnostics (e.g., passing non-POD arguments
6832 /// through varargs) but do not want to mark declarations as "referenced"
6833 /// until the default argument is used.
6834 PotentiallyEvaluatedIfUsed
6835 };
6836
6837 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
6838 /// to a variable (constant) that may or may not be odr-used in this Expr, and
6839 /// we won't know until all lvalue-to-rvalue and discarded value conversions
6840 /// have been applied to all subexpressions of the enclosing full expression.
6841 /// This is cleared at the end of each full expression.
6842 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>;
6843 MaybeODRUseExprSet MaybeODRUseExprs;
6844
6845 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
6846
6847 /// Data structure used to record current or nested
6848 /// expression evaluation contexts.
6849 struct ExpressionEvaluationContextRecord {
6850 /// The expression evaluation context.
6851 ExpressionEvaluationContext Context;
6852
6853 /// Whether the enclosing context needed a cleanup.
6854 CleanupInfo ParentCleanup;
6855
6856 /// The number of active cleanup objects when we entered
6857 /// this expression evaluation context.
6858 unsigned NumCleanupObjects;
6859
6860 MaybeODRUseExprSet SavedMaybeODRUseExprs;
6861
6862 /// The lambdas that are present within this context, if it
6863 /// is indeed an unevaluated context.
6864 SmallVector<LambdaExpr *, 2> Lambdas;
6865
6866 /// The declaration that provides context for lambda expressions
6867 /// and block literals if the normal declaration context does not
6868 /// suffice, e.g., in a default function argument.
6869 Decl *ManglingContextDecl;
6870
6871 /// Declaration for initializer if one is currently being
6872 /// parsed. Used when an expression has a possibly unreachable
6873 /// diagnostic to reference the declaration as a whole.
6874 VarDecl *DeclForInitializer = nullptr;
6875
6876 /// If we are processing a decltype type, a set of call expressions
6877 /// for which we have deferred checking the completeness of the return type.
6878 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
6879
6880 /// If we are processing a decltype type, a set of temporary binding
6881 /// expressions for which we have deferred checking the destructor.
6882 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
6883
6884 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
6885
6886 /// Expressions appearing as the LHS of a volatile assignment in this
6887 /// context. We produce a warning for these when popping the context if
6888 /// they are not discarded-value expressions nor unevaluated operands.
6889 SmallVector<Expr *, 2> VolatileAssignmentLHSs;
6890
6891 /// Set of candidates for starting an immediate invocation.
6892 llvm::SmallVector<ImmediateInvocationCandidate, 4>
6893 ImmediateInvocationCandidates;
6894
6895 /// Set of DeclRefExprs referencing a consteval function when used in a
6896 /// context not already known to be immediately invoked.
6897 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
6898
6899 /// P2718R0 - Lifetime extension in range-based for loops.
6900 /// MaterializeTemporaryExprs in for-range-init expressions which need to
6901 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of
6902 /// InLifetimeExtendingContext is true.
6903 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps;
6904
6905 /// Small set of gathered accesses to potentially misaligned members
6906 /// due to the packed attribute.
6907 SmallVector<MisalignedMember, 4> MisalignedMembers;
6908
6909 /// \brief Describes whether we are in an expression constext which we have
6910 /// to handle differently.
6911 enum ExpressionKind {
6912 EK_Decltype,
6913 EK_TemplateArgument,
6914 EK_AttrArgument,
6915 EK_VariableInit,
6916 EK_Other
6917 } ExprContext;
6918
6919 // A context can be nested in both a discarded statement context and
6920 // an immediate function context, so they need to be tracked independently.
6921 bool InDiscardedStatement;
6922 bool InImmediateFunctionContext;
6923 bool InImmediateEscalatingFunctionContext;
6924
6925 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
6926
6927 // We are in a constant context, but we also allow
6928 // non constant expressions, for example for array bounds (which may be
6929 // VLAs).
6930 bool InConditionallyConstantEvaluateContext = false;
6931
6932 /// Whether we are currently in a context in which all temporaries must be
6933 /// lifetime-extended, even if they're not bound to a reference (for
6934 /// example, in a for-range initializer).
6935 bool InLifetimeExtendingContext = false;
6936
6937 /// Whether evaluating an expression for a switch case label.
6938 bool IsCaseExpr = false;
6939
6940 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr.
6941 bool RebuildDefaultArgOrDefaultInit = false;
6942
6943 // When evaluating immediate functions in the initializer of a default
6944 // argument or default member initializer, this is the declaration whose
6945 // default initializer is being evaluated and the location of the call
6946 // or constructor definition.
6947 struct InitializationContext {
6948 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
6949 DeclContext *Context)
6950 : Loc(Loc), Decl(Decl), Context(Context) {
6951 assert(Decl && Context && "invalid initialization context");
6952 }
6953
6954 SourceLocation Loc;
6955 ValueDecl *Decl = nullptr;
6956 DeclContext *Context = nullptr;
6957 };
6958 std::optional<InitializationContext> DelayedDefaultInitializationContext;
6959
6960 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
6961 unsigned NumCleanupObjects,
6962 CleanupInfo ParentCleanup,
6963 Decl *ManglingContextDecl,
6964 ExpressionKind ExprContext)
6965 : Context(Context), ParentCleanup(ParentCleanup),
6966 NumCleanupObjects(NumCleanupObjects),
6967 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
6968 InDiscardedStatement(false), InImmediateFunctionContext(false),
6969 InImmediateEscalatingFunctionContext(false) {}
6970
6971 bool isUnevaluated() const {
6972 return Context == ExpressionEvaluationContext::Unevaluated ||
6973 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
6974 Context == ExpressionEvaluationContext::UnevaluatedList;
6975 }
6976
6977 bool isPotentiallyEvaluated() const {
6978 return Context == ExpressionEvaluationContext::PotentiallyEvaluated ||
6979 Context ==
6980 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed ||
6981 Context == ExpressionEvaluationContext::ConstantEvaluated;
6982 }
6983
6984 bool isConstantEvaluated() const {
6985 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
6986 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
6987 }
6988
6989 bool isImmediateFunctionContext() const {
6990 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
6991 (Context == ExpressionEvaluationContext::DiscardedStatement &&
6992 InImmediateFunctionContext) ||
6993 // C++23 [expr.const]p14:
6994 // An expression or conversion is in an immediate function
6995 // context if it is potentially evaluated and either:
6996 // * its innermost enclosing non-block scope is a function
6997 // parameter scope of an immediate function, or
6998 // * its enclosing statement is enclosed by the compound-
6999 // statement of a consteval if statement.
7000 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
7001 InImmediateFunctionContext);
7002 }
7003
7004 bool isDiscardedStatementContext() const {
7005 return Context == ExpressionEvaluationContext::DiscardedStatement ||
7006 ((Context ==
7007 ExpressionEvaluationContext::ImmediateFunctionContext ||
7008 isPotentiallyEvaluated()) &&
7009 InDiscardedStatement);
7010 }
7011 };
7012
7013 const ExpressionEvaluationContextRecord &currentEvaluationContext() const {
7014 assert(!ExprEvalContexts.empty() &&
7015 "Must be in an expression evaluation context");
7016 return ExprEvalContexts.back();
7017 }
7018
7019 ExpressionEvaluationContextRecord &currentEvaluationContext() {
7020 assert(!ExprEvalContexts.empty() &&
7021 "Must be in an expression evaluation context");
7022 return ExprEvalContexts.back();
7023 }
7024
7025 ExpressionEvaluationContextRecord &parentEvaluationContext() {
7026 assert(ExprEvalContexts.size() >= 2 &&
7027 "Must be in an expression evaluation context");
7028 return ExprEvalContexts[ExprEvalContexts.size() - 2];
7029 }
7030
7031 const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
7032 return const_cast<Sema *>(this)->parentEvaluationContext();
7033 }
7034
7035 bool isAttrContext() const {
7036 return ExprEvalContexts.back().ExprContext ==
7037 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument;
7038 }
7039
7040 /// Increment when we find a reference; decrement when we find an ignored
7041 /// assignment. Ultimately the value is 0 if every reference is an ignored
7042 /// assignment.
7043 ///
7044 /// Uses canonical VarDecl as key so in-class decls and out-of-class defs of
7045 /// static data members get tracked as a single entry.
7046 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
7047
7048 /// Used to control the generation of ExprWithCleanups.
7049 CleanupInfo Cleanup;
7050
7051 /// ExprCleanupObjects - This is the stack of objects requiring
7052 /// cleanup that are created by the current full expression.
7053 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
7054
7055 /// Determine whether the use of this declaration is valid, without
7056 /// emitting diagnostics.
7057 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
7058 // A version of DiagnoseUseOfDecl that should be used if overload resolution
7059 // has been used to find this declaration, which means we don't have to bother
7060 // checking the trailing requires clause.
7061 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) {
7062 return DiagnoseUseOfDecl(
7063 D, Locs: Loc, /*UnknownObjCClass=*/UnknownObjCClass: nullptr, /*ObjCPropertyAccess=*/ObjCPropertyAccess: false,
7064 /*AvoidPartialAvailabilityChecks=*/AvoidPartialAvailabilityChecks: false, /*ClassReceiver=*/ClassReceiver: nullptr,
7065 /*SkipTrailingRequiresClause=*/SkipTrailingRequiresClause: true);
7066 }
7067
7068 /// Determine whether the use of this declaration is valid, and
7069 /// emit any corresponding diagnostics.
7070 ///
7071 /// This routine diagnoses various problems with referencing
7072 /// declarations that can occur when using a declaration. For example,
7073 /// it might warn if a deprecated or unavailable declaration is being
7074 /// used, or produce an error (and return true) if a C++0x deleted
7075 /// function is being used.
7076 ///
7077 /// \returns true if there was an error (this declaration cannot be
7078 /// referenced), false otherwise.
7079 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
7080 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
7081 bool ObjCPropertyAccess = false,
7082 bool AvoidPartialAvailabilityChecks = false,
7083 ObjCInterfaceDecl *ClassReceiver = nullptr,
7084 bool SkipTrailingRequiresClause = false);
7085
7086 /// Emit a note explaining that this function is deleted.
7087 void NoteDeletedFunction(FunctionDecl *FD);
7088
7089 /// DiagnoseSentinelCalls - This routine checks whether a call or
7090 /// message-send is to a declaration with the sentinel attribute, and
7091 /// if so, it checks that the requirements of the sentinel are
7092 /// satisfied.
7093 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
7094 ArrayRef<Expr *> Args);
7095
7096 void PushExpressionEvaluationContext(
7097 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
7098 ExpressionEvaluationContextRecord::ExpressionKind Type =
7099 ExpressionEvaluationContextRecord::EK_Other);
7100
7101 void PushExpressionEvaluationContextForFunction(
7102 ExpressionEvaluationContext NewContext, FunctionDecl *FD);
7103
7104 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
7105 void PushExpressionEvaluationContext(
7106 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
7107 ExpressionEvaluationContextRecord::ExpressionKind Type =
7108 ExpressionEvaluationContextRecord::EK_Other);
7109 void PopExpressionEvaluationContext();
7110
7111 void DiscardCleanupsInEvaluationContext();
7112
7113 ExprResult TransformToPotentiallyEvaluated(Expr *E);
7114 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
7115 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
7116
7117 /// Check whether E, which is either a discarded-value expression or an
7118 /// unevaluated operand, is a simple-assignment to a volatlie-qualified
7119 /// lvalue, and if so, remove it from the list of volatile-qualified
7120 /// assignments that we are going to warn are deprecated.
7121 void CheckUnusedVolatileAssignment(Expr *E);
7122
7123 ExprResult ActOnConstantExpression(ExprResult Res);
7124
7125 // Functions for marking a declaration referenced. These functions also
7126 // contain the relevant logic for marking if a reference to a function or
7127 // variable is an odr-use (in the C++11 sense). There are separate variants
7128 // for expressions referring to a decl; these exist because odr-use marking
7129 // needs to be delayed for some constant variables when we build one of the
7130 // named expressions.
7131 //
7132 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
7133 // should usually be true. This only needs to be set to false if the lack of
7134 // odr-use cannot be determined from the current context (for instance,
7135 // because the name denotes a virtual function and was written without an
7136 // explicit nested-name-specifier).
7137 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
7138
7139 /// Mark a function referenced, and check whether it is odr-used
7140 /// (C++ [basic.def.odr]p2, C99 6.9p3)
7141 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
7142 bool MightBeOdrUse = true);
7143
7144 /// Mark a variable referenced, and check whether it is odr-used
7145 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
7146 /// used directly for normal expressions referring to VarDecl.
7147 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
7148
7149 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
7150 ///
7151 /// Note, this may change the dependence of the DeclRefExpr, and so needs to
7152 /// be handled with care if the DeclRefExpr is not newly-created.
7153 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
7154
7155 /// Perform reference-marking and odr-use handling for a MemberExpr.
7156 void MarkMemberReferenced(MemberExpr *E);
7157
7158 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
7159 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
7160 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc,
7161 unsigned CapturingScopeIndex);
7162
7163 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
7164 void CleanupVarDeclMarking();
7165
7166 /// Try to capture the given variable.
7167 ///
7168 /// \param Var The variable to capture.
7169 ///
7170 /// \param Loc The location at which the capture occurs.
7171 ///
7172 /// \param Kind The kind of capture, which may be implicit (for either a
7173 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
7174 ///
7175 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
7176 /// an explicit lambda capture.
7177 ///
7178 /// \param BuildAndDiagnose Whether we are actually supposed to add the
7179 /// captures or diagnose errors. If false, this routine merely check whether
7180 /// the capture can occur without performing the capture itself or complaining
7181 /// if the variable cannot be captured.
7182 ///
7183 /// \param CaptureType Will be set to the type of the field used to capture
7184 /// this variable in the innermost block or lambda. Only valid when the
7185 /// variable can be captured.
7186 ///
7187 /// \param DeclRefType Will be set to the type of a reference to the capture
7188 /// from within the current scope. Only valid when the variable can be
7189 /// captured.
7190 ///
7191 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
7192 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
7193 /// This is useful when enclosing lambdas must speculatively capture
7194 /// variables that may or may not be used in certain specializations of
7195 /// a nested generic lambda.
7196 ///
7197 /// \returns true if an error occurred (i.e., the variable cannot be
7198 /// captured) and false if the capture succeeded.
7199 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7200 TryCaptureKind Kind, SourceLocation EllipsisLoc,
7201 bool BuildAndDiagnose, QualType &CaptureType,
7202 QualType &DeclRefType,
7203 const unsigned *const FunctionScopeIndexToStopAt);
7204
7205 /// Try to capture the given variable.
7206 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
7207 TryCaptureKind Kind = TryCaptureKind::Implicit,
7208 SourceLocation EllipsisLoc = SourceLocation());
7209
7210 /// Checks if the variable must be captured.
7211 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc);
7212
7213 /// Given a variable, determine the type that a reference to that
7214 /// variable will have in the given scope.
7215 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc);
7216
7217 /// Mark all of the declarations referenced within a particular AST node as
7218 /// referenced. Used when template instantiation instantiates a non-dependent
7219 /// type -- entities referenced by the type are now referenced.
7220 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
7221
7222 /// Mark any declarations that appear within this expression or any
7223 /// potentially-evaluated subexpressions as "referenced".
7224 ///
7225 /// \param SkipLocalVariables If true, don't mark local variables as
7226 /// 'referenced'.
7227 /// \param StopAt Subexpressions that we shouldn't recurse into.
7228 void MarkDeclarationsReferencedInExpr(Expr *E,
7229 bool SkipLocalVariables = false,
7230 ArrayRef<const Expr *> StopAt = {});
7231
7232 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
7233 /// conversion.
7234 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
7235
7236 /// Conditionally issue a diagnostic based on the statements's reachability
7237 /// analysis.
7238 ///
7239 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
7240 /// the function body is parsed, and then do a basic reachability analysis to
7241 /// determine if the statement is reachable. If it is unreachable, the
7242 /// diagnostic will not be emitted.
7243 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7244 const PartialDiagnostic &PD);
7245
7246 /// Conditionally issue a diagnostic based on the current
7247 /// evaluation context.
7248 ///
7249 /// \param Statement If Statement is non-null, delay reporting the
7250 /// diagnostic until the function body is parsed, and then do a basic
7251 /// reachability analysis to determine if the statement is reachable.
7252 /// If it is unreachable, the diagnostic will not be emitted.
7253 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
7254 const PartialDiagnostic &PD);
7255 /// Similar, but diagnostic is only produced if all the specified statements
7256 /// are reachable.
7257 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
7258 const PartialDiagnostic &PD);
7259
7260 // Primary Expressions.
7261 SourceRange getExprRange(Expr *E) const;
7262
7263 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
7264 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
7265 bool HasTrailingLParen, bool IsAddressOfOperand,
7266 CorrectionCandidateCallback *CCC = nullptr,
7267 bool IsInlineAsmIdentifier = false);
7268
7269 /// Decomposes the given name into a DeclarationNameInfo, its location, and
7270 /// possibly a list of template arguments.
7271 ///
7272 /// If this produces template arguments, it is permitted to call
7273 /// DecomposeTemplateName.
7274 ///
7275 /// This actually loses a lot of source location information for
7276 /// non-standard name kinds; we should consider preserving that in
7277 /// some way.
7278 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
7279 TemplateArgumentListInfo &Buffer,
7280 DeclarationNameInfo &NameInfo,
7281 const TemplateArgumentListInfo *&TemplateArgs);
7282
7283 /// Diagnose a lookup that found results in an enclosing class during error
7284 /// recovery. This usually indicates that the results were found in a
7285 /// dependent base class that could not be searched as part of a template
7286 /// definition. Always issues a diagnostic (though this may be only a warning
7287 /// in MS compatibility mode).
7288 ///
7289 /// Return \c true if the error is unrecoverable, or \c false if the caller
7290 /// should attempt to recover using these lookup results.
7291 bool DiagnoseDependentMemberLookup(const LookupResult &R);
7292
7293 /// Diagnose an empty lookup.
7294 ///
7295 /// \return false if new lookup candidates were found
7296 bool
7297 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
7298 CorrectionCandidateCallback &CCC,
7299 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
7300 ArrayRef<Expr *> Args = {},
7301 DeclContext *LookupCtx = nullptr);
7302
7303 /// If \p D cannot be odr-used in the current expression evaluation context,
7304 /// return a reason explaining why. Otherwise, return NOUR_None.
7305 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
7306
7307 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7308 SourceLocation Loc,
7309 const CXXScopeSpec *SS = nullptr);
7310 DeclRefExpr *
7311 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7312 const DeclarationNameInfo &NameInfo,
7313 const CXXScopeSpec *SS = nullptr,
7314 NamedDecl *FoundD = nullptr,
7315 SourceLocation TemplateKWLoc = SourceLocation(),
7316 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7317
7318 /// BuildDeclRefExpr - Build an expression that references a
7319 /// declaration that does not require a closure capture.
7320 DeclRefExpr *
7321 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
7322 const DeclarationNameInfo &NameInfo,
7323 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr,
7324 SourceLocation TemplateKWLoc = SourceLocation(),
7325 const TemplateArgumentListInfo *TemplateArgs = nullptr);
7326
7327 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R,
7328 bool HasTrailingLParen);
7329
7330 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
7331 /// declaration name, generally during template instantiation.
7332 /// There's a large number of things which don't need to be done along
7333 /// this path.
7334 ExprResult BuildQualifiedDeclarationNameExpr(
7335 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
7336 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
7337
7338 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
7339 bool NeedsADL,
7340 bool AcceptInvalidDecl = false);
7341
7342 /// Complete semantic analysis for a reference to the given declaration.
7343 ExprResult BuildDeclarationNameExpr(
7344 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
7345 NamedDecl *FoundD = nullptr,
7346 const TemplateArgumentListInfo *TemplateArgs = nullptr,
7347 bool AcceptInvalidDecl = false);
7348
7349 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens,
7350 // where Tokens representing function local predefined macros (such as
7351 // __FUNCTION__) are replaced (expanded) with string-literal Tokens.
7352 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks);
7353
7354 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK);
7355 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
7356 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val);
7357
7358 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero);
7359
7360 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
7361 ExprResult ActOnCharacterConstant(const Token &Tok,
7362 Scope *UDLScope = nullptr);
7363 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
7364 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R,
7365 MultiExprArg Val);
7366 ExprResult ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,
7367 unsigned NumUserSpecifiedExprs,
7368 SourceLocation InitLoc,
7369 SourceLocation LParenLoc,
7370 SourceLocation RParenLoc);
7371
7372 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
7373 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle
7374 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come
7375 /// from multiple tokens. However, the common case is that StringToks points
7376 /// to one string.
7377 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
7378 Scope *UDLScope = nullptr);
7379
7380 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks);
7381
7382 /// ControllingExprOrType is either an opaque pointer coming out of a
7383 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface
7384 /// into two so we don't take a void *, but that's awkward because one of
7385 /// the operands is either a ParsedType or an Expr *, which doesn't lend
7386 /// itself to generic code very well.
7387 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
7388 SourceLocation DefaultLoc,
7389 SourceLocation RParenLoc,
7390 bool PredicateIsExpr,
7391 void *ControllingExprOrType,
7392 ArrayRef<ParsedType> ArgTypes,
7393 ArrayRef<Expr *> ArgExprs);
7394 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME:
7395 /// it'd be better to split this interface into two so we don't take a
7396 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that
7397 /// isn't a trivial change.
7398 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
7399 SourceLocation DefaultLoc,
7400 SourceLocation RParenLoc,
7401 bool PredicateIsExpr,
7402 void *ControllingExprOrType,
7403 ArrayRef<TypeSourceInfo *> Types,
7404 ArrayRef<Expr *> Exprs);
7405
7406 // Binary/Unary Operators. 'Tok' is the token for the operator.
7407 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
7408 Expr *InputExpr, bool IsAfterAmp = false);
7409 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc,
7410 Expr *Input, bool IsAfterAmp = false);
7411
7412 /// Unary Operators. 'Tok' is the token for the operator.
7413 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
7414 Expr *Input, bool IsAfterAmp = false);
7415
7416 /// Determine whether the given expression is a qualified member
7417 /// access expression, of a form that could be turned into a pointer to member
7418 /// with the address-of operator.
7419 bool isQualifiedMemberAccess(Expr *E);
7420 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
7421 const Expr *Op,
7422 const CXXMethodDecl *MD);
7423
7424 /// CheckAddressOfOperand - The operand of & must be either a function
7425 /// designator or an lvalue designating an object. If it is an lvalue, the
7426 /// object cannot be declared with storage class register or be a bit field.
7427 /// Note: The usual conversions are *not* applied to the operand of the &
7428 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7429 /// In C++, the operand might be an overloaded function name, in which case
7430 /// we allow the '&' but retain the overloaded-function type.
7431 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
7432
7433 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
7434 /// _Alignas(type-name) .
7435 /// [dcl.align] An alignment-specifier of the form
7436 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
7437 ///
7438 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
7439 /// _Alignas(_Alignof(type-name)).
7440 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
7441 SourceLocation OpLoc, SourceRange R);
7442 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
7443 SourceLocation OpLoc, SourceRange R);
7444
7445 /// Build a sizeof or alignof expression given a type operand.
7446 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
7447 SourceLocation OpLoc,
7448 UnaryExprOrTypeTrait ExprKind,
7449 SourceRange R);
7450
7451 /// Build a sizeof or alignof expression given an expression
7452 /// operand.
7453 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
7454 UnaryExprOrTypeTrait ExprKind);
7455
7456 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
7457 /// expr and the same for @c alignof and @c __alignof
7458 /// Note that the ArgRange is invalid if isType is false.
7459 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
7460 UnaryExprOrTypeTrait ExprKind,
7461 bool IsType, void *TyOrEx,
7462 SourceRange ArgRange);
7463
7464 /// Check for operands with placeholder types and complain if found.
7465 /// Returns ExprError() if there was an error and no recovery was possible.
7466 ExprResult CheckPlaceholderExpr(Expr *E);
7467 bool CheckVecStepExpr(Expr *E);
7468
7469 /// Check the constraints on expression operands to unary type expression
7470 /// and type traits.
7471 ///
7472 /// Completes any types necessary and validates the constraints on the operand
7473 /// expression. The logic mostly mirrors the type-based overload, but may
7474 /// modify the expression as it completes the type for that expression through
7475 /// template instantiation, etc.
7476 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
7477
7478 /// Check the constraints on operands to unary expression and type
7479 /// traits.
7480 ///
7481 /// This will complete any types necessary, and validate the various
7482 /// constraints on those operands.
7483 ///
7484 /// The UsualUnaryConversions() function is *not* called by this routine.
7485 /// C99 6.3.2.1p[2-4] all state:
7486 /// Except when it is the operand of the sizeof operator ...
7487 ///
7488 /// C++ [expr.sizeof]p4
7489 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
7490 /// standard conversions are not applied to the operand of sizeof.
7491 ///
7492 /// This policy is followed for all of the unary trait expressions.
7493 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
7494 SourceRange ExprRange,
7495 UnaryExprOrTypeTrait ExprKind,
7496 StringRef KWName);
7497
7498 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
7499 tok::TokenKind Kind, Expr *Input);
7500
7501 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
7502 MultiExprArg ArgExprs,
7503 SourceLocation RLoc);
7504 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
7505 Expr *Idx, SourceLocation RLoc);
7506
7507 ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx,
7508 SourceLocation RBLoc);
7509
7510 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
7511 Expr *ColumnIdx,
7512 SourceLocation RBLoc);
7513
7514 /// ConvertArgumentsForCall - Converts the arguments specified in
7515 /// Args/NumArgs to the parameter types of the function FDecl with
7516 /// function prototype Proto. Call is the call expression itself, and
7517 /// Fn is the function expression. For a C++ member function, this
7518 /// routine does not attempt to convert the object argument. Returns
7519 /// true if the call is ill-formed.
7520 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl,
7521 const FunctionProtoType *Proto,
7522 ArrayRef<Expr *> Args, SourceLocation RParenLoc,
7523 bool ExecConfig = false);
7524
7525 /// CheckStaticArrayArgument - If the given argument corresponds to a static
7526 /// array parameter, check that it is non-null, and that if it is formed by
7527 /// array-to-pointer decay, the underlying array is sufficiently large.
7528 ///
7529 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of
7530 /// the array type derivation, then for each call to the function, the value
7531 /// of the corresponding actual argument shall provide access to the first
7532 /// element of an array with at least as many elements as specified by the
7533 /// size expression.
7534 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param,
7535 const Expr *ArgExpr);
7536
7537 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
7538 /// This provides the location of the left/right parens and a list of comma
7539 /// locations.
7540 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7541 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7542 Expr *ExecConfig = nullptr);
7543
7544 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7545 /// This provides the location of the left/right parens and a list of comma
7546 /// locations.
7547 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
7548 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7549 Expr *ExecConfig = nullptr,
7550 bool IsExecConfig = false,
7551 bool AllowRecovery = false);
7552
7553 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7554 // with the specified CallArgs
7555 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7556 MultiExprArg CallArgs);
7557
7558 using ADLCallKind = CallExpr::ADLCallKind;
7559
7560 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7561 /// i.e. an expression not of \p OverloadTy. The expression should
7562 /// unary-convert to an expression of function-pointer or
7563 /// block-pointer type.
7564 ///
7565 /// \param NDecl the declaration being called, if available
7566 ExprResult
7567 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
7568 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
7569 Expr *Config = nullptr, bool IsExecConfig = false,
7570 ADLCallKind UsesADL = ADLCallKind::NotADL);
7571
7572 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D,
7573 ParsedType &Ty, SourceLocation RParenLoc,
7574 Expr *CastExpr);
7575
7576 /// Prepares for a scalar cast, performing all the necessary stages
7577 /// except the final cast and returning the kind required.
7578 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
7579
7580 /// Build an altivec or OpenCL literal.
7581 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
7582 SourceLocation RParenLoc, Expr *E,
7583 TypeSourceInfo *TInfo);
7584
7585 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7586 /// the ParenListExpr into a sequence of comma binary operators.
7587 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
7588
7589 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7590 SourceLocation RParenLoc, Expr *InitExpr);
7591
7592 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
7593 TypeSourceInfo *TInfo,
7594 SourceLocation RParenLoc,
7595 Expr *LiteralExpr);
7596
7597 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7598 SourceLocation RBraceLoc);
7599
7600 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7601 SourceLocation RBraceLoc, bool IsExplicit);
7602
7603 /// Binary Operators. 'Tok' is the token for the operator.
7604 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind,
7605 Expr *LHSExpr, Expr *RHSExpr);
7606 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7607 Expr *LHSExpr, Expr *RHSExpr,
7608 bool ForFoldExpression = false);
7609
7610 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7611 /// operator @p Opc at location @c TokLoc. This routine only supports
7612 /// built-in operations; ActOnBinOp handles overloaded operators.
7613 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
7614 Expr *LHSExpr, Expr *RHSExpr,
7615 bool ForFoldExpression = false);
7616 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
7617 UnresolvedSetImpl &Functions);
7618
7619 /// Look for instances where it is likely the comma operator is confused with
7620 /// another operator. There is an explicit list of acceptable expressions for
7621 /// the left hand side of the comma operator, otherwise emit a warning.
7622 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
7623
7624 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7625 /// in the case of a the GNU conditional expr extension.
7626 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
7627 SourceLocation ColonLoc, Expr *CondExpr,
7628 Expr *LHSExpr, Expr *RHSExpr);
7629
7630 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7631 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
7632 LabelDecl *TheDecl);
7633
7634 void ActOnStartStmtExpr();
7635 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
7636 SourceLocation RPLoc);
7637 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
7638 SourceLocation RPLoc, unsigned TemplateDepth);
7639 // Handle the final expression in a statement expression.
7640 ExprResult ActOnStmtExprResult(ExprResult E);
7641 void ActOnStmtExprError();
7642
7643 /// __builtin_offsetof(type, a.b[123][456].c)
7644 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
7645 TypeSourceInfo *TInfo,
7646 const Designation &Desig,
7647 SourceLocation RParenLoc);
7648 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc,
7649 SourceLocation TypeLoc,
7650 ParsedType ParsedArgTy,
7651 const Designation &Desig,
7652 SourceLocation RParenLoc);
7653
7654 // __builtin_choose_expr(constExpr, expr1, expr2)
7655 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr,
7656 Expr *LHSExpr, Expr *RHSExpr,
7657 SourceLocation RPLoc);
7658
7659 // __builtin_va_arg(expr, type)
7660 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
7661 SourceLocation RPLoc);
7662 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
7663 TypeSourceInfo *TInfo, SourceLocation RPLoc);
7664
7665 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(),
7666 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location()
7667 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind,
7668 SourceLocation BuiltinLoc,
7669 SourceLocation RPLoc);
7670
7671 // #embed
7672 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,
7673 StringLiteral *BinaryData, StringRef FileName);
7674
7675 // Build a potentially resolved SourceLocExpr.
7676 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
7677 SourceLocation BuiltinLoc, SourceLocation RPLoc,
7678 DeclContext *ParentContext);
7679
7680 // __null
7681 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
7682
7683 bool CheckCaseExpression(Expr *E);
7684
7685 //===------------------------- "Block" Extension ------------------------===//
7686
7687 /// ActOnBlockStart - This callback is invoked when a block literal is
7688 /// started.
7689 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
7690
7691 /// ActOnBlockArguments - This callback allows processing of block arguments.
7692 /// If there are no arguments, this is still invoked.
7693 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
7694 Scope *CurScope);
7695
7696 /// ActOnBlockError - If there is an error parsing a block, this callback
7697 /// is invoked to pop the information about the block from the action impl.
7698 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
7699
7700 /// ActOnBlockStmtExpr - This is called when the body of a block statement
7701 /// literal was successfully completed. ^(int x){...}
7702 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
7703 Scope *CurScope);
7704
7705 //===---------------------------- Clang Extensions ----------------------===//
7706
7707 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7708 /// provided arguments.
7709 ///
7710 /// __builtin_convertvector( value, dst type )
7711 ///
7712 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7713 SourceLocation BuiltinLoc,
7714 SourceLocation RParenLoc);
7715
7716 //===---------------------------- OpenCL Features -----------------------===//
7717
7718 /// Parse a __builtin_astype expression.
7719 ///
7720 /// __builtin_astype( value, dst type )
7721 ///
7722 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7723 SourceLocation BuiltinLoc,
7724 SourceLocation RParenLoc);
7725
7726 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7727 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
7728 SourceLocation BuiltinLoc,
7729 SourceLocation RParenLoc);
7730
7731 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
7732 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
7733 ArrayRef<Expr *> SubExprs,
7734 QualType T = QualType());
7735
7736 /// Cast a base object to a member's actual type.
7737 ///
7738 /// There are two relevant checks:
7739 ///
7740 /// C++ [class.access.base]p7:
7741 ///
7742 /// If a class member access operator [...] is used to access a non-static
7743 /// data member or non-static member function, the reference is ill-formed
7744 /// if the left operand [...] cannot be implicitly converted to a pointer to
7745 /// the naming class of the right operand.
7746 ///
7747 /// C++ [expr.ref]p7:
7748 ///
7749 /// If E2 is a non-static data member or a non-static member function, the
7750 /// program is ill-formed if the class of which E2 is directly a member is
7751 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2.
7752 ///
7753 /// Note that the latter check does not consider access; the access of the
7754 /// "real" base class is checked as appropriate when checking the access of
7755 /// the member name.
7756 ExprResult PerformObjectMemberConversion(Expr *From,
7757 NestedNameSpecifier Qualifier,
7758 NamedDecl *FoundDecl,
7759 NamedDecl *Member);
7760
7761 /// CheckCallReturnType - Checks that a call expression's return type is
7762 /// complete. Returns true on failure. The location passed in is the location
7763 /// that best represents the call.
7764 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7765 CallExpr *CE, FunctionDecl *FD);
7766
7767 /// Emit a warning for all pending noderef expressions that we recorded.
7768 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
7769
7770 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
7771
7772 /// Instantiate or parse a C++ default argument expression as necessary.
7773 /// Return true on error.
7774 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7775 ParmVarDecl *Param, Expr *Init = nullptr,
7776 bool SkipImmediateInvocations = true);
7777
7778 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
7779 /// the default expr if needed.
7780 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
7781 ParmVarDecl *Param, Expr *Init = nullptr);
7782
7783 /// Wrap the expression in a ConstantExpr if it is a potential immediate
7784 /// invocation.
7785 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
7786
7787 void MarkExpressionAsImmediateEscalating(Expr *E);
7788
7789 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
7790 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType);
7791
7792 /// Abstract base class used for diagnosing integer constant
7793 /// expression violations.
7794 class VerifyICEDiagnoser {
7795 public:
7796 bool Suppress;
7797
7798 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {}
7799
7800 virtual SemaDiagnosticBuilder
7801 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
7802 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7803 SourceLocation Loc) = 0;
7804 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
7805 virtual ~VerifyICEDiagnoser() {}
7806 };
7807
7808 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
7809 /// and reports the appropriate diagnostics. Returns false on success.
7810 /// Can optionally return the value of the expression.
7811 ExprResult
7812 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7813 VerifyICEDiagnoser &Diagnoser,
7814 AllowFoldKind CanFold = AllowFoldKind::No);
7815 ExprResult
7816 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
7817 unsigned DiagID,
7818 AllowFoldKind CanFold = AllowFoldKind::No);
7819 ExprResult
7820 VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr,
7821 AllowFoldKind CanFold = AllowFoldKind::No);
7822 ExprResult
7823 VerifyIntegerConstantExpression(Expr *E,
7824 AllowFoldKind CanFold = AllowFoldKind::No) {
7825 return VerifyIntegerConstantExpression(E, Result: nullptr, CanFold);
7826 }
7827
7828 /// DiagnoseAssignmentAsCondition - Given that an expression is
7829 /// being used as a boolean condition, warn if it's an assignment.
7830 void DiagnoseAssignmentAsCondition(Expr *E);
7831
7832 /// Redundant parentheses over an equality comparison can indicate
7833 /// that the user intended an assignment used as condition.
7834 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
7835
7836 class FullExprArg {
7837 public:
7838 FullExprArg() : E(nullptr) {}
7839 FullExprArg(Sema &actions) : E(nullptr) {}
7840
7841 ExprResult release() { return E; }
7842
7843 Expr *get() const { return E; }
7844
7845 Expr *operator->() { return E; }
7846
7847 private:
7848 // FIXME: No need to make the entire Sema class a friend when it's just
7849 // Sema::MakeFullExpr that needs access to the constructor below.
7850 friend class Sema;
7851
7852 explicit FullExprArg(Expr *expr) : E(expr) {}
7853
7854 Expr *E;
7855 };
7856
7857 FullExprArg MakeFullExpr(Expr *Arg) {
7858 return MakeFullExpr(Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation());
7859 }
7860 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
7861 return FullExprArg(
7862 ActOnFinishFullExpr(Expr: Arg, CC, /*DiscardedValue*/ DiscardedValue: false).get());
7863 }
7864 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
7865 ExprResult FE =
7866 ActOnFinishFullExpr(Expr: Arg, CC: Arg ? Arg->getExprLoc() : SourceLocation(),
7867 /*DiscardedValue*/ DiscardedValue: true);
7868 return FullExprArg(FE.get());
7869 }
7870
7871 class ConditionResult {
7872 Decl *ConditionVar;
7873 ExprResult Condition;
7874 bool Invalid;
7875 std::optional<bool> KnownValue;
7876
7877 friend class Sema;
7878 ConditionResult(Sema &S, Decl *ConditionVar, ExprResult Condition,
7879 bool IsConstexpr)
7880 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) {
7881 if (IsConstexpr && Condition.get()) {
7882 if (std::optional<llvm::APSInt> Val =
7883 Condition.get()->getIntegerConstantExpr(Ctx: S.Context)) {
7884 KnownValue = !!(*Val);
7885 }
7886 }
7887 }
7888 explicit ConditionResult(bool Invalid)
7889 : ConditionVar(nullptr), Condition(Invalid), Invalid(Invalid),
7890 KnownValue(std::nullopt) {}
7891
7892 public:
7893 ConditionResult() : ConditionResult(false) {}
7894 bool isInvalid() const { return Invalid; }
7895 std::pair<VarDecl *, Expr *> get() const {
7896 return std::make_pair(x: cast_or_null<VarDecl>(Val: ConditionVar),
7897 y: Condition.get());
7898 }
7899 std::optional<bool> getKnownValue() const { return KnownValue; }
7900 };
7901 static ConditionResult ConditionError() { return ConditionResult(true); }
7902
7903 /// CheckBooleanCondition - Diagnose problems involving the use of
7904 /// the given expression as a boolean condition (e.g. in an if
7905 /// statement). Also performs the standard function and array
7906 /// decays, possibly changing the input variable.
7907 ///
7908 /// \param Loc - A location associated with the condition, e.g. the
7909 /// 'if' keyword.
7910 /// \return true iff there were any errors
7911 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
7912 bool IsConstexpr = false);
7913
7914 enum class ConditionKind {
7915 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
7916 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
7917 Switch ///< An integral condition for a 'switch' statement.
7918 };
7919
7920 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
7921 ConditionKind CK, bool MissingOK = false);
7922
7923 QualType CheckConditionalOperands( // C99 6.5.15
7924 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
7925 ExprObjectKind &OK, SourceLocation QuestionLoc);
7926
7927 /// Emit a specialized diagnostic when one expression is a null pointer
7928 /// constant and the other is not a pointer. Returns true if a diagnostic is
7929 /// emitted.
7930 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7931 SourceLocation QuestionLoc);
7932
7933 /// type checking for vector binary operators.
7934 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7935 SourceLocation Loc, bool IsCompAssign,
7936 bool AllowBothBool, bool AllowBoolConversion,
7937 bool AllowBoolOperation, bool ReportInvalid);
7938
7939 /// Return a signed ext_vector_type that is of identical size and number of
7940 /// elements. For floating point vectors, return an integer type of identical
7941 /// size and number of elements. In the non ext_vector_type case, search from
7942 /// the largest type to the smallest type to avoid cases where long long ==
7943 /// long, where long gets picked over long long.
7944 QualType GetSignedVectorType(QualType V);
7945 QualType GetSignedSizelessVectorType(QualType V);
7946
7947 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7948 /// operates on extended vector types. Instead of producing an IntTy result,
7949 /// like a scalar comparison, a vector comparison produces a vector of integer
7950 /// types.
7951 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7952 SourceLocation Loc,
7953 BinaryOperatorKind Opc);
7954 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7955 SourceLocation Loc,
7956 BinaryOperatorKind Opc);
7957 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7958 SourceLocation Loc,
7959 BinaryOperatorKind Opc);
7960 QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7961 SourceLocation Loc,
7962 BinaryOperatorKind Opc);
7963 // type checking for sizeless vector binary operators.
7964 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
7965 SourceLocation Loc, bool IsCompAssign,
7966 ArithConvKind OperationKind);
7967
7968 /// Type checking for matrix binary operators.
7969 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
7970 SourceLocation Loc,
7971 bool IsCompAssign);
7972 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
7973 SourceLocation Loc, bool IsCompAssign);
7974
7975 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from
7976 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE
7977 /// VLST) allowed?
7978 ///
7979 /// This will also return false if the two given types do not make sense from
7980 /// the perspective of SVE bitcasts.
7981 bool isValidSveBitcast(QualType srcType, QualType destType);
7982
7983 /// Are the two types matrix types and do they have the same dimensions i.e.
7984 /// do they have the same number of rows and the same number of columns?
7985 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
7986
7987 bool areVectorTypesSameSize(QualType srcType, QualType destType);
7988
7989 /// Are the two types lax-compatible vector types? That is, given
7990 /// that one of them is a vector, do they have equal storage sizes,
7991 /// where the storage size is the number of elements times the element
7992 /// size?
7993 ///
7994 /// This will also return false if either of the types is neither a
7995 /// vector nor a real type.
7996 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
7997
7998 /// Is this a legal conversion between two types, one of which is
7999 /// known to be a vector type?
8000 bool isLaxVectorConversion(QualType srcType, QualType destType);
8001
8002 // This returns true if at least one of the types is an altivec vector.
8003 bool anyAltivecTypes(QualType srcType, QualType destType);
8004
8005 // type checking C++ declaration initializers (C++ [dcl.init]).
8006
8007 /// Check a cast of an unknown-any type. We intentionally only
8008 /// trigger this for C-style casts.
8009 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
8010 Expr *CastExpr, CastKind &CastKind,
8011 ExprValueKind &VK, CXXCastPath &Path);
8012
8013 /// Force an expression with unknown-type to an expression of the
8014 /// given type.
8015 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
8016
8017 /// Type-check an expression that's being passed to an
8018 /// __unknown_anytype parameter.
8019 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result,
8020 QualType &paramType);
8021
8022 // CheckMatrixCast - Check type constraints for matrix casts.
8023 // We allow casting between matrixes of the same dimensions i.e. when they
8024 // have the same number of rows and column. Returns true if the cast is
8025 // invalid.
8026 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8027 CastKind &Kind);
8028
8029 // CheckVectorCast - check type constraints for vectors.
8030 // Since vectors are an extension, there are no C standard reference for this.
8031 // We allow casting between vectors and integer datatypes of the same size.
8032 // returns true if the cast is invalid
8033 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8034 CastKind &Kind);
8035
8036 /// Prepare `SplattedExpr` for a vector splat operation, adding
8037 /// implicit casts if necessary.
8038 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
8039
8040 /// Prepare `SplattedExpr` for a matrix splat operation, adding
8041 /// implicit casts if necessary.
8042 ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr);
8043
8044 // CheckExtVectorCast - check type constraints for extended vectors.
8045 // Since vectors are an extension, there are no C standard reference for this.
8046 // We allow casting between vectors and integer datatypes of the same size,
8047 // or vectors and the element type of that vector.
8048 // returns the cast expr
8049 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
8050 CastKind &Kind);
8051
8052 QualType PreferredConditionType(ConditionKind K) const {
8053 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
8054 }
8055
8056 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts
8057 // functions and arrays to their respective pointers (C99 6.3.2.1), and
8058 // promotes floating-piont types according to the language semantics.
8059 ExprResult UsualUnaryConversions(Expr *E);
8060
8061 // UsualUnaryFPConversions - promotes floating-point types according to the
8062 // current language semantics.
8063 ExprResult UsualUnaryFPConversions(Expr *E);
8064
8065 /// CallExprUnaryConversions - a special case of an unary conversion
8066 /// performed on a function designator of a call expression.
8067 ExprResult CallExprUnaryConversions(Expr *E);
8068
8069 // DefaultFunctionArrayConversion - converts functions and arrays
8070 // to their respective pointers (C99 6.3.2.1).
8071 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8072
8073 // DefaultFunctionArrayLvalueConversion - converts functions and
8074 // arrays to their respective pointers and performs the
8075 // lvalue-to-rvalue conversion.
8076 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8077 bool Diagnose = true);
8078
8079 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8080 // the operand. This function is a no-op if the operand has a function type
8081 // or an array type.
8082 ExprResult DefaultLvalueConversion(Expr *E);
8083
8084 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8085 // do not have a prototype. Integer promotions are performed on each
8086 // argument, and arguments that have type float are promoted to double.
8087 ExprResult DefaultArgumentPromotion(Expr *E);
8088
8089 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
8090 const FunctionProtoType *Proto,
8091 Expr *Fn);
8092
8093 /// Determine the degree of POD-ness for an expression.
8094 /// Incomplete types are considered POD, since this check can be performed
8095 /// when we're in an unevaluated context.
8096 VarArgKind isValidVarArgType(const QualType &Ty);
8097
8098 /// Check to see if the given expression is a valid argument to a variadic
8099 /// function, issuing a diagnostic if not.
8100 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
8101
8102 /// GatherArgumentsForCall - Collector argument expressions for various
8103 /// form of call prototypes.
8104 bool GatherArgumentsForCall(
8105 SourceLocation CallLoc, FunctionDecl *FDecl,
8106 const FunctionProtoType *Proto, unsigned FirstParam,
8107 ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs,
8108 VariadicCallType CallType = VariadicCallType::DoesNotApply,
8109 bool AllowExplicit = false, bool IsListInitialization = false);
8110
8111 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
8112 // will create a runtime trap if the resulting type is not a POD type.
8113 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
8114 FunctionDecl *FDecl);
8115
8116 // Check that the usual arithmetic conversions can be performed on this pair
8117 // of expressions that might be of enumeration type.
8118 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc,
8119 ArithConvKind ACK);
8120
8121 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
8122 // operands and then handles various conversions that are common to binary
8123 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
8124 // routine returns the first non-arithmetic type found. The client is
8125 // responsible for emitting appropriate error diagnostics.
8126 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
8127 SourceLocation Loc, ArithConvKind ACK);
8128
8129 bool IsAssignConvertCompatible(AssignConvertType ConvTy) {
8130 switch (ConvTy) {
8131 default:
8132 return false;
8133 case AssignConvertType::Compatible:
8134 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
8135 case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:
8136 return true;
8137 }
8138 llvm_unreachable("impossible");
8139 }
8140
8141 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
8142 /// assignment conversion type specified by ConvTy. This returns true if the
8143 /// conversion was invalid or false if the conversion was accepted.
8144 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc,
8145 QualType DstType, QualType SrcType,
8146 Expr *SrcExpr, AssignmentAction Action,
8147 bool *Complained = nullptr);
8148
8149 /// CheckAssignmentConstraints - Perform type checking for assignment,
8150 /// argument passing, variable initialization, and function return values.
8151 /// C99 6.5.16.
8152 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
8153 QualType LHSType,
8154 QualType RHSType);
8155
8156 /// Check assignment constraints and optionally prepare for a conversion of
8157 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
8158 /// is true.
8159 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
8160 ExprResult &RHS, CastKind &Kind,
8161 bool ConvertRHS = true);
8162
8163 /// Check assignment constraints for an assignment of RHS to LHSType.
8164 ///
8165 /// \param LHSType The destination type for the assignment.
8166 /// \param RHS The source expression for the assignment.
8167 /// \param Diagnose If \c true, diagnostics may be produced when checking
8168 /// for assignability. If a diagnostic is produced, \p RHS will be
8169 /// set to ExprError(). Note that this function may still return
8170 /// without producing a diagnostic, even for an invalid assignment.
8171 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
8172 /// in an audited Core Foundation API and does not need to be checked
8173 /// for ARC retain issues.
8174 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
8175 /// conversions necessary to perform the assignment. If \c false,
8176 /// \p Diagnose must also be \c false.
8177 AssignConvertType CheckSingleAssignmentConstraints(
8178 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
8179 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
8180
8181 // If the lhs type is a transparent union, check whether we
8182 // can initialize the transparent union with the given expression.
8183 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
8184 ExprResult &RHS);
8185
8186 /// the following "Check" methods will return a valid/converted QualType
8187 /// or a null QualType (indicating an error diagnostic was issued).
8188
8189 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
8190 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8191 ExprResult &RHS);
8192
8193 /// Diagnose cases where a scalar was implicitly converted to a vector and
8194 /// diagnose the underlying types. Otherwise, diagnose the error
8195 /// as invalid vector logical operands for non-C++ cases.
8196 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8197 ExprResult &RHS);
8198
8199 QualType CheckMultiplyDivideOperands( // C99 6.5.5
8200 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8201 BinaryOperatorKind Opc);
8202 QualType CheckRemainderOperands( // C99 6.5.5
8203 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8204 bool IsCompAssign = false);
8205 QualType CheckAdditionOperands( // C99 6.5.6
8206 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8207 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8208 QualType CheckSubtractionOperands( // C99 6.5.6
8209 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8210 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr);
8211 QualType CheckShiftOperands( // C99 6.5.7
8212 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8213 BinaryOperatorKind Opc, bool IsCompAssign = false);
8214 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
8215 QualType CheckCompareOperands( // C99 6.5.8/9
8216 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8217 BinaryOperatorKind Opc);
8218 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
8219 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8220 BinaryOperatorKind Opc);
8221 QualType CheckLogicalOperands( // C99 6.5.[13,14]
8222 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
8223 BinaryOperatorKind Opc);
8224 // CheckAssignmentOperands is used for both simple and compound assignment.
8225 // For simple assignment, pass both expressions and a null converted type.
8226 // For compound assignment, pass both expressions and the converted type.
8227 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
8228 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType,
8229 BinaryOperatorKind Opc);
8230
8231 /// To be used for checking whether the arguments being passed to
8232 /// function exceeds the number of parameters expected for it.
8233 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
8234 bool PartialOverloading = false) {
8235 // We check whether we're just after a comma in code-completion.
8236 if (NumArgs > 0 && PartialOverloading)
8237 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
8238 return NumArgs > NumParams;
8239 }
8240
8241 /// Whether the AST is currently being rebuilt to correct immediate
8242 /// invocations. Immediate invocation candidates and references to consteval
8243 /// functions aren't tracked when this is set.
8244 bool RebuildingImmediateInvocation = false;
8245
8246 bool isAlwaysConstantEvaluatedContext() const {
8247 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8248 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) &&
8249 !Ctx.InConditionallyConstantEvaluateContext;
8250 }
8251
8252 /// Determines whether we are currently in a context that
8253 /// is not evaluated as per C++ [expr] p5.
8254 bool isUnevaluatedContext() const {
8255 return currentEvaluationContext().isUnevaluated();
8256 }
8257
8258 bool isImmediateFunctionContext() const {
8259 return currentEvaluationContext().isImmediateFunctionContext();
8260 }
8261
8262 bool isInLifetimeExtendingContext() const {
8263 return currentEvaluationContext().InLifetimeExtendingContext;
8264 }
8265
8266 bool needsRebuildOfDefaultArgOrInit() const {
8267 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit;
8268 }
8269
8270 bool isCheckingDefaultArgumentOrInitializer() const {
8271 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext();
8272 return (Ctx.Context ==
8273 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) ||
8274 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer;
8275 }
8276
8277 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8278 InnermostDeclarationWithDelayedImmediateInvocations() const {
8279 assert(!ExprEvalContexts.empty() &&
8280 "Must be in an expression evaluation context");
8281 for (const auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8282 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8283 Ctx.DelayedDefaultInitializationContext)
8284 return Ctx.DelayedDefaultInitializationContext;
8285 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8286 Ctx.isUnevaluated())
8287 break;
8288 }
8289 return std::nullopt;
8290 }
8291
8292 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
8293 OutermostDeclarationWithDelayedImmediateInvocations() const {
8294 assert(!ExprEvalContexts.empty() &&
8295 "Must be in an expression evaluation context");
8296 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res;
8297 for (auto &Ctx : llvm::reverse(C: ExprEvalContexts)) {
8298 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
8299 !Ctx.DelayedDefaultInitializationContext && Res)
8300 break;
8301 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() ||
8302 Ctx.isUnevaluated())
8303 break;
8304 Res = Ctx.DelayedDefaultInitializationContext;
8305 }
8306 return Res;
8307 }
8308
8309 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
8310 return getDefaultedFunctionKind(FD).asComparison();
8311 }
8312
8313 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p
8314 /// SelfAssigned when inside a CXXMethodDecl.
8315 const FieldDecl *
8316 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned);
8317
8318 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
8319
8320 template <typename... Ts>
8321 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
8322 const Ts &...Args) {
8323 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8324 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
8325 }
8326
8327 template <typename... Ts>
8328 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
8329 const Ts &...Args) {
8330 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
8331 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
8332 }
8333
8334 /// Abstract class used to diagnose incomplete types.
8335 struct TypeDiagnoser {
8336 TypeDiagnoser() {}
8337
8338 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
8339 virtual ~TypeDiagnoser() {}
8340 };
8341
8342 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
8343 protected:
8344 unsigned DiagID;
8345 std::tuple<const Ts &...> Args;
8346
8347 template <std::size_t... Is>
8348 void emit(const SemaDiagnosticBuilder &DB,
8349 std::index_sequence<Is...>) const {
8350 // Apply all tuple elements to the builder in order.
8351 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
8352 (void)Dummy;
8353 }
8354
8355 public:
8356 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8357 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
8358 assert(DiagID != 0 && "no diagnostic for type diagnoser");
8359 }
8360
8361 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8362 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
8363 emit(DB, std::index_sequence_for<Ts...>());
8364 DB << T;
8365 }
8366 };
8367
8368 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
8369 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
8370 /// For example, a diagnostic with no other parameters would generally have
8371 /// the form "...%select{incomplete|sizeless}0 type %1...".
8372 template <typename... Ts>
8373 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
8374 public:
8375 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args)
8376 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
8377
8378 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
8379 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
8380 this->emit(DB, std::index_sequence_for<Ts...>());
8381 DB << T->isSizelessType() << T;
8382 }
8383 };
8384
8385 /// Check an argument list for placeholders that we won't try to
8386 /// handle later.
8387 bool CheckArgsForPlaceholders(MultiExprArg args);
8388
8389 /// The C++ "std::source_location::__impl" struct, defined in
8390 /// \<source_location>.
8391 RecordDecl *StdSourceLocationImplDecl;
8392
8393 /// A stack of expression evaluation contexts.
8394 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
8395
8396 // Set of failed immediate invocations to avoid double diagnosing.
8397 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
8398
8399 /// List of SourceLocations where 'self' is implicitly retained inside a
8400 /// block.
8401 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
8402 ImplicitlyRetainedSelfLocs;
8403
8404 /// Do an explicit extend of the given block pointer if we're in ARC.
8405 void maybeExtendBlockObject(ExprResult &E);
8406
8407 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied;
8408 SourceLocation LocationOfExcessPrecisionNotSatisfied;
8409 void DiagnosePrecisionLossInComplexDivision();
8410
8411private:
8412 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
8413
8414 /// Methods for marking which expressions involve dereferencing a pointer
8415 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
8416 /// they are parsed, meaning that a noderef pointer may not be accessed. For
8417 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
8418 /// `*p`, but need to check that `address of` is called on it. This requires
8419 /// keeping a container of all pending expressions and checking if the address
8420 /// of them are eventually taken.
8421 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
8422 void CheckAddressOfNoDeref(const Expr *E);
8423
8424 ///@}
8425
8426 //
8427 //
8428 // -------------------------------------------------------------------------
8429 //
8430 //
8431
8432 /// \name C++ Expressions
8433 /// Implementations are in SemaExprCXX.cpp
8434 ///@{
8435
8436public:
8437 /// The C++ "std::bad_alloc" class, which is defined by the C++
8438 /// standard library.
8439 LazyDeclPtr StdBadAlloc;
8440
8441 /// The C++ "std::align_val_t" enum class, which is defined by the C++
8442 /// standard library.
8443 LazyDeclPtr StdAlignValT;
8444
8445 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
8446 RecordDecl *CXXTypeInfoDecl;
8447
8448 /// A flag to remember whether the implicit forms of operator new and delete
8449 /// have been declared.
8450 bool GlobalNewDeleteDeclared;
8451
8452 /// Delete-expressions to be analyzed at the end of translation unit
8453 ///
8454 /// This list contains class members, and locations of delete-expressions
8455 /// that could not be proven as to whether they mismatch with new-expression
8456 /// used in initializer of the field.
8457 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
8458
8459 /// Handle the result of the special case name lookup for inheriting
8460 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
8461 /// constructor names in member using declarations, even if 'X' is not the
8462 /// name of the corresponding type.
8463 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
8464 SourceLocation NameLoc,
8465 const IdentifierInfo &Name);
8466
8467 ParsedType getConstructorName(const IdentifierInfo &II,
8468 SourceLocation NameLoc, Scope *S,
8469 CXXScopeSpec &SS, bool EnteringContext);
8470 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc,
8471 Scope *S, CXXScopeSpec &SS,
8472 ParsedType ObjectType, bool EnteringContext);
8473
8474 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
8475 ParsedType ObjectType);
8476
8477 /// Build a C++ typeid expression with a type operand.
8478 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8479 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8480
8481 /// Build a C++ typeid expression with an expression operand.
8482 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc,
8483 Expr *Operand, SourceLocation RParenLoc);
8484
8485 /// ActOnCXXTypeid - Parse typeid( something ).
8486 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
8487 bool isType, void *TyOrExpr,
8488 SourceLocation RParenLoc);
8489
8490 /// Build a Microsoft __uuidof expression with a type operand.
8491 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8492 TypeSourceInfo *Operand, SourceLocation RParenLoc);
8493
8494 /// Build a Microsoft __uuidof expression with an expression operand.
8495 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc,
8496 Expr *Operand, SourceLocation RParenLoc);
8497
8498 /// ActOnCXXUuidof - Parse __uuidof( something ).
8499 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
8500 bool isType, void *TyOrExpr,
8501 SourceLocation RParenLoc);
8502
8503 //// ActOnCXXThis - Parse 'this' pointer.
8504 ExprResult ActOnCXXThis(SourceLocation Loc);
8505
8506 /// Check whether the type of 'this' is valid in the current context.
8507 bool CheckCXXThisType(SourceLocation Loc, QualType Type);
8508
8509 /// Build a CXXThisExpr and mark it referenced in the current context.
8510 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
8511 void MarkThisReferenced(CXXThisExpr *This);
8512
8513 /// Try to retrieve the type of the 'this' pointer.
8514 ///
8515 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
8516 QualType getCurrentThisType();
8517
8518 /// When non-NULL, the C++ 'this' expression is allowed despite the
8519 /// current context not being a non-static member function. In such cases,
8520 /// this provides the type used for 'this'.
8521 QualType CXXThisTypeOverride;
8522
8523 /// RAII object used to temporarily allow the C++ 'this' expression
8524 /// to be used, with the given qualifiers on the current class type.
8525 class CXXThisScopeRAII {
8526 Sema &S;
8527 QualType OldCXXThisTypeOverride;
8528 bool Enabled;
8529
8530 public:
8531 /// Introduce a new scope where 'this' may be allowed (when enabled),
8532 /// using the given declaration (which is either a class template or a
8533 /// class) along with the given qualifiers.
8534 /// along with the qualifiers placed on '*this'.
8535 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
8536 bool Enabled = true);
8537
8538 ~CXXThisScopeRAII();
8539 CXXThisScopeRAII(const CXXThisScopeRAII &) = delete;
8540 CXXThisScopeRAII &operator=(const CXXThisScopeRAII &) = delete;
8541 };
8542
8543 /// Make sure the value of 'this' is actually available in the current
8544 /// context, if it is a potentially evaluated context.
8545 ///
8546 /// \param Loc The location at which the capture of 'this' occurs.
8547 ///
8548 /// \param Explicit Whether 'this' is explicitly captured in a lambda
8549 /// capture list.
8550 ///
8551 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
8552 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
8553 /// This is useful when enclosing lambdas must speculatively capture
8554 /// 'this' that may or may not be used in certain specializations of
8555 /// a nested generic lambda (depending on whether the name resolves to
8556 /// a non-static member function or a static function).
8557 /// \return returns 'true' if failed, 'false' if success.
8558 bool CheckCXXThisCapture(
8559 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true,
8560 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
8561 bool ByCopy = false);
8562
8563 /// Determine whether the given type is the type of *this that is used
8564 /// outside of the body of a member function for a type that is currently
8565 /// being defined.
8566 bool isThisOutsideMemberFunctionBody(QualType BaseType);
8567
8568 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
8569 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
8570
8571 /// Build a boolean-typed literal expression.
8572 ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value);
8573
8574 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
8575 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
8576
8577 //// ActOnCXXThrow - Parse throw expressions.
8578 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
8579 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
8580 bool IsThrownVarInScope);
8581
8582 /// CheckCXXThrowOperand - Validate the operand of a throw.
8583 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
8584
8585 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
8586 /// Can be interpreted either as function-style casting ("int(x)")
8587 /// or class type construction ("ClassType(x,y,z)")
8588 /// or creation of a value-initialized type ("int()").
8589 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
8590 SourceLocation LParenOrBraceLoc,
8591 MultiExprArg Exprs,
8592 SourceLocation RParenOrBraceLoc,
8593 bool ListInitialization);
8594
8595 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
8596 SourceLocation LParenLoc,
8597 MultiExprArg Exprs,
8598 SourceLocation RParenLoc,
8599 bool ListInitialization);
8600
8601 /// Parsed a C++ 'new' expression (C++ 5.3.4).
8602 ///
8603 /// E.g.:
8604 /// @code new (memory) int[size][4] @endcode
8605 /// or
8606 /// @code ::new Foo(23, "hello") @endcode
8607 ///
8608 /// \param StartLoc The first location of the expression.
8609 /// \param UseGlobal True if 'new' was prefixed with '::'.
8610 /// \param PlacementLParen Opening paren of the placement arguments.
8611 /// \param PlacementArgs Placement new arguments.
8612 /// \param PlacementRParen Closing paren of the placement arguments.
8613 /// \param TypeIdParens If the type is in parens, the source range.
8614 /// \param D The type to be allocated, as well as array dimensions.
8615 /// \param Initializer The initializing expression or initializer-list, or
8616 /// null if there is none.
8617 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
8618 SourceLocation PlacementLParen,
8619 MultiExprArg PlacementArgs,
8620 SourceLocation PlacementRParen,
8621 SourceRange TypeIdParens, Declarator &D,
8622 Expr *Initializer);
8623 ExprResult
8624 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen,
8625 MultiExprArg PlacementArgs, SourceLocation PlacementRParen,
8626 SourceRange TypeIdParens, QualType AllocType,
8627 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize,
8628 SourceRange DirectInitRange, Expr *Initializer);
8629
8630 /// Determine whether \p FD is an aligned allocation or deallocation
8631 /// function that is unavailable.
8632 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
8633
8634 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
8635 /// function that is unavailable.
8636 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
8637 SourceLocation Loc);
8638
8639 /// Checks that a type is suitable as the allocated type
8640 /// in a new-expression.
8641 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
8642 SourceRange R);
8643
8644 /// Finds the overloads of operator new and delete that are appropriate
8645 /// for the allocation.
8646 bool FindAllocationFunctions(
8647 SourceLocation StartLoc, SourceRange Range,
8648 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
8649 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
8650 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
8651 FunctionDecl *&OperatorDelete, bool Diagnose = true);
8652
8653 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
8654 /// delete. These are:
8655 /// @code
8656 /// // C++03:
8657 /// void* operator new(std::size_t) throw(std::bad_alloc);
8658 /// void* operator new[](std::size_t) throw(std::bad_alloc);
8659 /// void operator delete(void *) throw();
8660 /// void operator delete[](void *) throw();
8661 /// // C++11:
8662 /// void* operator new(std::size_t);
8663 /// void* operator new[](std::size_t);
8664 /// void operator delete(void *) noexcept;
8665 /// void operator delete[](void *) noexcept;
8666 /// // C++1y:
8667 /// void* operator new(std::size_t);
8668 /// void* operator new[](std::size_t);
8669 /// void operator delete(void *) noexcept;
8670 /// void operator delete[](void *) noexcept;
8671 /// void operator delete(void *, std::size_t) noexcept;
8672 /// void operator delete[](void *, std::size_t) noexcept;
8673 /// @endcode
8674 /// Note that the placement and nothrow forms of new are *not* implicitly
8675 /// declared. Their use requires including \<new\>.
8676 void DeclareGlobalNewDelete();
8677 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
8678 ArrayRef<QualType> Params);
8679
8680 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
8681 DeclarationName Name, FunctionDecl *&Operator,
8682 ImplicitDeallocationParameters,
8683 bool Diagnose = true);
8684 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
8685 ImplicitDeallocationParameters,
8686 DeclarationName Name,
8687 bool Diagnose = true);
8688 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
8689 CXXRecordDecl *RD,
8690 bool Diagnose,
8691 bool LookForGlobal,
8692 DeclarationName Name);
8693
8694 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
8695 /// @code ::delete ptr; @endcode
8696 /// or
8697 /// @code delete [] ptr; @endcode
8698 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
8699 bool ArrayForm, Expr *Operand);
8700 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
8701 bool IsDelete, bool CallCanBeVirtual,
8702 bool WarnOnNonAbstractTypes,
8703 SourceLocation DtorLoc);
8704
8705 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
8706 Expr *Operand, SourceLocation RParen);
8707 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8708 SourceLocation RParen);
8709
8710 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base,
8711 SourceLocation OpLoc,
8712 tok::TokenKind OpKind,
8713 ParsedType &ObjectType,
8714 bool &MayBePseudoDestructor);
8715
8716 ExprResult BuildPseudoDestructorExpr(
8717 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8718 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc,
8719 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType);
8720
8721 ExprResult ActOnPseudoDestructorExpr(
8722 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind,
8723 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc,
8724 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName);
8725
8726 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8727 SourceLocation OpLoc,
8728 tok::TokenKind OpKind,
8729 SourceLocation TildeLoc,
8730 const DeclSpec &DS);
8731
8732 /// MaybeCreateExprWithCleanups - If the current full-expression
8733 /// requires any cleanups, surround it with a ExprWithCleanups node.
8734 /// Otherwise, just returns the passed-in expression.
8735 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
8736 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
8737 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
8738
8739 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
8740 return ActOnFinishFullExpr(
8741 Expr, CC: Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
8742 }
8743 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
8744 bool DiscardedValue, bool IsConstexpr = false,
8745 bool IsTemplateArgument = false);
8746 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
8747
8748 /// Process the expression contained within a decltype. For such expressions,
8749 /// certain semantic checks on temporaries are delayed until this point, and
8750 /// are omitted for the 'topmost' call in the decltype expression. If the
8751 /// topmost call bound a temporary, strip that temporary off the expression.
8752 ExprResult ActOnDecltypeExpression(Expr *E);
8753
8754 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
8755 bool IsUDSuffix);
8756
8757 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
8758
8759 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
8760 SourceLocation StmtLoc,
8761 ConditionKind CK);
8762
8763 /// Check the use of the given variable as a C++ condition in an if,
8764 /// while, do-while, or switch statement.
8765 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
8766 SourceLocation StmtLoc, ConditionKind CK);
8767
8768 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
8769 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
8770
8771 /// Helper function to determine whether this is the (deprecated) C++
8772 /// conversion from a string literal to a pointer to non-const char or
8773 /// non-const wchar_t (for narrow and wide string literals,
8774 /// respectively).
8775 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
8776
8777 /// PerformImplicitConversion - Perform an implicit conversion of the
8778 /// expression From to the type ToType using the pre-computed implicit
8779 /// conversion sequence ICS. Returns the converted
8780 /// expression. Action is the kind of conversion we're performing,
8781 /// used in the error message.
8782 ExprResult PerformImplicitConversion(
8783 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS,
8784 AssignmentAction Action,
8785 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
8786
8787 /// PerformImplicitConversion - Perform an implicit conversion of the
8788 /// expression From to the type ToType by following the standard
8789 /// conversion sequence SCS. Returns the converted
8790 /// expression. Flavor is the context in which we're performing this
8791 /// conversion, for use in error messages.
8792 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
8793 const StandardConversionSequence &SCS,
8794 AssignmentAction Action,
8795 CheckedConversionKind CCK);
8796
8797 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N);
8798
8799 /// Parsed one of the type trait support pseudo-functions.
8800 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8801 ArrayRef<ParsedType> Args,
8802 SourceLocation RParenLoc);
8803 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
8804 ArrayRef<TypeSourceInfo *> Args,
8805 SourceLocation RParenLoc);
8806
8807 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
8808 /// pseudo-functions.
8809 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8810 ParsedType LhsTy, Expr *DimExpr,
8811 SourceLocation RParen);
8812
8813 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc,
8814 TypeSourceInfo *TSInfo, Expr *DimExpr,
8815 SourceLocation RParen);
8816
8817 /// ActOnExpressionTrait - Parsed one of the unary type trait support
8818 /// pseudo-functions.
8819 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8820 Expr *Queried, SourceLocation RParen);
8821
8822 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc,
8823 Expr *Queried, SourceLocation RParen);
8824
8825 QualType CheckPointerToMemberOperands( // C++ 5.5
8826 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc,
8827 bool isIndirect);
8828 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
8829 ExprResult &RHS,
8830 SourceLocation QuestionLoc);
8831
8832 //// Determines if a type is trivially relocatable
8833 /// according to the C++26 rules.
8834 // FIXME: This is in Sema because it requires
8835 // overload resolution, can we move to ASTContext?
8836 bool IsCXXTriviallyRelocatableType(QualType T);
8837 bool IsCXXTriviallyRelocatableType(const CXXRecordDecl &RD);
8838
8839 /// Check the operands of ?: under C++ semantics.
8840 ///
8841 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
8842 /// extension. In this case, LHS == Cond. (But they're not aliases.)
8843 ///
8844 /// This function also implements GCC's vector extension and the
8845 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions
8846 /// permit the use of a?b:c where the type of a is that of a integer vector
8847 /// with the same number of elements and size as the vectors of b and c. If
8848 /// one of either b or c is a scalar it is implicitly converted to match the
8849 /// type of the vector. Otherwise the expression is ill-formed. If both b and
8850 /// c are scalars, then b and c are checked and converted to the type of a if
8851 /// possible.
8852 ///
8853 /// The expressions are evaluated differently for GCC's and OpenCL's
8854 /// extensions. For the GCC extension, the ?: operator is evaluated as
8855 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
8856 /// For the OpenCL extensions, the ?: operator is evaluated as
8857 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
8858 /// most-significant-bit-set(a[n]) ? b[n] : c[n]).
8859 QualType CXXCheckConditionalOperands( // C++ 5.16
8860 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK,
8861 ExprObjectKind &OK, SourceLocation questionLoc);
8862
8863 /// Find a merged pointer type and convert the two expressions to it.
8864 ///
8865 /// This finds the composite pointer type for \p E1 and \p E2 according to
8866 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
8867 /// it. It does not emit diagnostics (FIXME: that's not true if \p
8868 /// ConvertArgs is \c true).
8869 ///
8870 /// \param Loc The location of the operator requiring these two expressions to
8871 /// be converted to the composite pointer type.
8872 ///
8873 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target
8874 /// type.
8875 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
8876 bool ConvertArgs = true);
8877 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1,
8878 ExprResult &E2, bool ConvertArgs = true) {
8879 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
8880 QualType Composite =
8881 FindCompositePointerType(Loc, E1&: E1Tmp, E2&: E2Tmp, ConvertArgs);
8882 E1 = E1Tmp;
8883 E2 = E2Tmp;
8884 return Composite;
8885 }
8886
8887 /// MaybeBindToTemporary - If the passed in expression has a record type with
8888 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
8889 /// it simply returns the passed in expression.
8890 ExprResult MaybeBindToTemporary(Expr *E);
8891
8892 /// IgnoredValueConversions - Given that an expression's result is
8893 /// syntactically ignored, perform any conversions that are
8894 /// required.
8895 ExprResult IgnoredValueConversions(Expr *E);
8896
8897 ExprResult CheckUnevaluatedOperand(Expr *E);
8898
8899 IfExistsResult
8900 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
8901 const DeclarationNameInfo &TargetNameInfo);
8902
8903 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S,
8904 SourceLocation KeywordLoc,
8905 bool IsIfExists, CXXScopeSpec &SS,
8906 UnqualifiedId &Name);
8907
8908 RequiresExprBodyDecl *
8909 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8910 ArrayRef<ParmVarDecl *> LocalParameters,
8911 Scope *BodyScope);
8912 void ActOnFinishRequiresExpr();
8913 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8914 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc,
8915 CXXScopeSpec &SS,
8916 SourceLocation NameLoc,
8917 const IdentifierInfo *TypeName,
8918 TemplateIdAnnotation *TemplateId);
8919 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8920 SourceLocation NoexceptLoc);
8921 concepts::Requirement *ActOnCompoundRequirement(
8922 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8923 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8924 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8925 concepts::ExprRequirement *BuildExprRequirement(
8926 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8927 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8928 concepts::ExprRequirement *BuildExprRequirement(
8929 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8930 bool IsSatisfied, SourceLocation NoexceptLoc,
8931 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8932 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8933 concepts::TypeRequirement *BuildTypeRequirement(
8934 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8935 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8936 concepts::NestedRequirement *
8937 BuildNestedRequirement(StringRef InvalidConstraintEntity,
8938 const ASTConstraintSatisfaction &Satisfaction);
8939 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8940 RequiresExprBodyDecl *Body,
8941 SourceLocation LParenLoc,
8942 ArrayRef<ParmVarDecl *> LocalParameters,
8943 SourceLocation RParenLoc,
8944 ArrayRef<concepts::Requirement *> Requirements,
8945 SourceLocation ClosingBraceLoc);
8946
8947private:
8948 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
8949 bool IsDelete);
8950
8951 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
8952 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
8953 bool DeleteWasArrayForm);
8954
8955 ///@}
8956
8957 //
8958 //
8959 // -------------------------------------------------------------------------
8960 //
8961 //
8962
8963 /// \name Member Access Expressions
8964 /// Implementations are in SemaExprMember.cpp
8965 ///@{
8966
8967public:
8968 /// Check whether an expression might be an implicit class member access.
8969 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
8970 bool IsAddressOfOperand);
8971
8972 /// Builds an expression which might be an implicit member expression.
8973 ExprResult BuildPossibleImplicitMemberExpr(
8974 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
8975 const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
8976
8977 /// Builds an implicit member access expression. The current context
8978 /// is known to be an instance method, and the given unqualified lookup
8979 /// set is known to contain only instance members, at least one of which
8980 /// is from an appropriate type.
8981 ExprResult
8982 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8983 LookupResult &R,
8984 const TemplateArgumentListInfo *TemplateArgs,
8985 bool IsDefiniteInstance, const Scope *S);
8986
8987 ExprResult ActOnDependentMemberExpr(
8988 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc,
8989 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
8990 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
8991 const TemplateArgumentListInfo *TemplateArgs);
8992
8993 /// The main callback when the parser finds something like
8994 /// expression . [nested-name-specifier] identifier
8995 /// expression -> [nested-name-specifier] identifier
8996 /// where 'identifier' encompasses a fairly broad spectrum of
8997 /// possibilities, including destructor and operator references.
8998 ///
8999 /// \param OpKind either tok::arrow or tok::period
9000 /// \param ObjCImpDecl the current Objective-C \@implementation
9001 /// decl; this is an ugly hack around the fact that Objective-C
9002 /// \@implementations aren't properly put in the context chain
9003 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
9004 tok::TokenKind OpKind, CXXScopeSpec &SS,
9005 SourceLocation TemplateKWLoc,
9006 UnqualifiedId &Member, Decl *ObjCImpDecl);
9007
9008 MemberExpr *
9009 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
9010 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
9011 ValueDecl *Member, DeclAccessPair FoundDecl,
9012 bool HadMultipleCandidates,
9013 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
9014 ExprValueKind VK, ExprObjectKind OK,
9015 const TemplateArgumentListInfo *TemplateArgs = nullptr);
9016
9017 // Check whether the declarations we found through a nested-name
9018 // specifier in a member expression are actually members of the base
9019 // type. The restriction here is:
9020 //
9021 // C++ [expr.ref]p2:
9022 // ... In these cases, the id-expression shall name a
9023 // member of the class or of one of its base classes.
9024 //
9025 // So it's perfectly legitimate for the nested-name specifier to name
9026 // an unrelated class, and for us to find an overload set including
9027 // decls from classes which are not superclasses, as long as the decl
9028 // we actually pick through overload resolution is from a superclass.
9029 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
9030 const CXXScopeSpec &SS,
9031 const LookupResult &R);
9032
9033 // This struct is for use by ActOnMemberAccess to allow
9034 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
9035 // changing the access operator from a '.' to a '->' (to see if that is the
9036 // change needed to fix an error about an unknown member, e.g. when the class
9037 // defines a custom operator->).
9038 struct ActOnMemberAccessExtraArgs {
9039 Scope *S;
9040 UnqualifiedId &Id;
9041 Decl *ObjCImpDecl;
9042 };
9043
9044 ExprResult BuildMemberReferenceExpr(
9045 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
9046 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
9047 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
9048 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
9049 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9050
9051 ExprResult
9052 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
9053 bool IsArrow, const CXXScopeSpec &SS,
9054 SourceLocation TemplateKWLoc,
9055 NamedDecl *FirstQualifierInScope, LookupResult &R,
9056 const TemplateArgumentListInfo *TemplateArgs,
9057 const Scope *S, bool SuppressQualifierCheck = false,
9058 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
9059
9060 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
9061 SourceLocation OpLoc,
9062 const CXXScopeSpec &SS, FieldDecl *Field,
9063 DeclAccessPair FoundDecl,
9064 const DeclarationNameInfo &MemberNameInfo);
9065
9066 /// Perform conversions on the LHS of a member access expression.
9067 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
9068
9069 ExprResult BuildAnonymousStructUnionMemberReference(
9070 const CXXScopeSpec &SS, SourceLocation nameLoc,
9071 IndirectFieldDecl *indirectField,
9072 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none),
9073 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation());
9074
9075private:
9076 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
9077
9078 ///@}
9079
9080 //
9081 //
9082 // -------------------------------------------------------------------------
9083 //
9084 //
9085
9086 /// \name Initializers
9087 /// Implementations are in SemaInit.cpp
9088 ///@{
9089
9090public:
9091 /// Stack of types that correspond to the parameter entities that are
9092 /// currently being copy-initialized. Can be empty.
9093 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
9094
9095 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *>
9096 AggregateDeductionCandidates;
9097
9098 bool IsStringInit(Expr *Init, const ArrayType *AT);
9099
9100 /// Determine whether we can perform aggregate initialization for the purposes
9101 /// of overload resolution.
9102 bool CanPerformAggregateInitializationForOverloadResolution(
9103 const InitializedEntity &Entity, InitListExpr *From);
9104
9105 ExprResult ActOnDesignatedInitializer(Designation &Desig,
9106 SourceLocation EqualOrColonLoc,
9107 bool GNUSyntax, ExprResult Init);
9108
9109 /// Check that the lifetime of the initializer (and its subobjects) is
9110 /// sufficient for initializing the entity, and perform lifetime extension
9111 /// (when permitted) if not.
9112 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
9113
9114 MaterializeTemporaryExpr *
9115 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
9116 bool BoundToLvalueReference);
9117
9118 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9119 /// it as an xvalue. In C++98, the result will still be a prvalue, because
9120 /// we don't have xvalues there.
9121 ExprResult TemporaryMaterializationConversion(Expr *E);
9122
9123 ExprResult PerformQualificationConversion(
9124 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
9125 CheckedConversionKind CCK = CheckedConversionKind::Implicit);
9126
9127 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
9128 ExprResult Init);
9129 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
9130 SourceLocation EqualLoc, ExprResult Init,
9131 bool TopLevelOfInitList = false,
9132 bool AllowExplicit = false);
9133
9134 QualType DeduceTemplateSpecializationFromInitializer(
9135 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
9136 const InitializationKind &Kind, MultiExprArg Init);
9137
9138 ///@}
9139
9140 //
9141 //
9142 // -------------------------------------------------------------------------
9143 //
9144 //
9145
9146 /// \name C++ Lambda Expressions
9147 /// Implementations are in SemaLambda.cpp
9148 ///@{
9149
9150public:
9151 /// Create a new lambda closure type.
9152 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
9153 TypeSourceInfo *Info,
9154 unsigned LambdaDependencyKind,
9155 LambdaCaptureDefault CaptureDefault);
9156
9157 /// Number lambda for linkage purposes if necessary.
9158 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method,
9159 std::optional<CXXRecordDecl::LambdaNumbering>
9160 NumberingOverride = std::nullopt);
9161
9162 /// Endow the lambda scope info with the relevant properties.
9163 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
9164 SourceRange IntroducerRange,
9165 LambdaCaptureDefault CaptureDefault,
9166 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
9167 bool Mutable);
9168
9169 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange,
9170 CXXRecordDecl *Class);
9171
9172 void AddTemplateParametersToLambdaCallOperator(
9173 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
9174 TemplateParameterList *TemplateParams);
9175
9176 void
9177 CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc,
9178 SourceLocation CallOperatorLoc,
9179 const AssociatedConstraint &TrailingRequiresClause,
9180 TypeSourceInfo *MethodTyInfo,
9181 ConstexprSpecKind ConstexprKind, StorageClass SC,
9182 ArrayRef<ParmVarDecl *> Params,
9183 bool HasExplicitResultType);
9184
9185 /// Returns true if the explicit object parameter was invalid.
9186 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method,
9187 SourceLocation CallLoc);
9188
9189 /// Perform initialization analysis of the init-capture and perform
9190 /// any implicit conversions such as an lvalue-to-rvalue conversion if
9191 /// not being used to initialize a reference.
9192 ParsedType actOnLambdaInitCaptureInitialization(
9193 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
9194 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
9195 return ParsedType::make(P: buildLambdaInitCaptureInitialization(
9196 Loc, ByRef, EllipsisLoc, NumExpansions: std::nullopt, Id,
9197 DirectInit: InitKind != LambdaCaptureInitKind::CopyInit, Init));
9198 }
9199 QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
9200 SourceLocation EllipsisLoc,
9201 UnsignedOrNone NumExpansions,
9202 IdentifierInfo *Id,
9203 bool DirectInit, Expr *&Init);
9204
9205 /// Create a dummy variable within the declcontext of the lambda's
9206 /// call operator, for name lookup purposes for a lambda init capture.
9207 ///
9208 /// CodeGen handles emission of lambda captures, ignoring these dummy
9209 /// variables appropriately.
9210 VarDecl *createLambdaInitCaptureVarDecl(
9211 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
9212 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
9213
9214 /// Add an init-capture to a lambda scope.
9215 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef);
9216
9217 /// Note that we have finished the explicit captures for the
9218 /// given lambda.
9219 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
9220
9221 /// Deduce a block or lambda's return type based on the return
9222 /// statements present in the body.
9223 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
9224
9225 /// Once the Lambdas capture are known, we can start to create the closure,
9226 /// call operator method, and keep track of the captures.
9227 /// We do the capture lookup here, but they are not actually captured until
9228 /// after we know what the qualifiers of the call operator are.
9229 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
9230 Scope *CurContext);
9231
9232 /// This is called after parsing the explicit template parameter list
9233 /// on a lambda (if it exists) in C++2a.
9234 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
9235 SourceLocation LAngleLoc,
9236 ArrayRef<NamedDecl *> TParams,
9237 SourceLocation RAngleLoc,
9238 ExprResult RequiresClause);
9239
9240 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
9241 SourceLocation MutableLoc);
9242
9243 void ActOnLambdaClosureParameters(
9244 Scope *LambdaScope,
9245 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo);
9246
9247 /// ActOnStartOfLambdaDefinition - This is called just before we start
9248 /// parsing the body of a lambda; it analyzes the explicit captures and
9249 /// arguments, and sets up various data-structures for the body of the
9250 /// lambda.
9251 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
9252 Declarator &ParamInfo, const DeclSpec &DS);
9253
9254 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
9255 /// is invoked to pop the information about the lambda.
9256 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
9257 bool IsInstantiation = false);
9258
9259 /// ActOnLambdaExpr - This is called when the body of a lambda expression
9260 /// was successfully completed.
9261 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body);
9262
9263 /// Does copying/destroying the captured variable have side effects?
9264 bool CaptureHasSideEffects(const sema::Capture &From);
9265
9266 /// Diagnose if an explicit lambda capture is unused. Returns true if a
9267 /// diagnostic is emitted.
9268 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
9269 SourceRange FixItRange,
9270 const sema::Capture &From);
9271
9272 /// Build a FieldDecl suitable to hold the given capture.
9273 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
9274
9275 /// Initialize the given capture with a suitable expression.
9276 ExprResult BuildCaptureInit(const sema::Capture &Capture,
9277 SourceLocation ImplicitCaptureLoc,
9278 bool IsOpenMPMapping = false);
9279
9280 /// Complete a lambda-expression having processed and attached the
9281 /// lambda body.
9282 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc);
9283
9284 /// Get the return type to use for a lambda's conversion function(s) to
9285 /// function pointer type, given the type of the call operator.
9286 QualType
9287 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
9288 CallingConv CC);
9289
9290 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
9291 SourceLocation ConvLocation,
9292 CXXConversionDecl *Conv, Expr *Src);
9293
9294 class LambdaScopeForCallOperatorInstantiationRAII
9295 : private FunctionScopeRAII {
9296 public:
9297 LambdaScopeForCallOperatorInstantiationRAII(
9298 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
9299 LocalInstantiationScope &Scope,
9300 bool ShouldAddDeclsFromParentScope = true);
9301 };
9302
9303 /// Compute the mangling number context for a lambda expression or
9304 /// block literal. Also return the extra mangling decl if any.
9305 ///
9306 /// \param DC - The DeclContext containing the lambda expression or
9307 /// block literal.
9308 std::tuple<MangleNumberingContext *, Decl *>
9309 getCurrentMangleNumberContext(const DeclContext *DC);
9310
9311 ///@}
9312
9313 //
9314 //
9315 // -------------------------------------------------------------------------
9316 //
9317 //
9318
9319 /// \name Name Lookup
9320 ///
9321 /// These routines provide name lookup that is used during semantic
9322 /// analysis to resolve the various kinds of names (identifiers,
9323 /// overloaded operator names, constructor names, etc.) into zero or
9324 /// more declarations within a particular scope. The major entry
9325 /// points are LookupName, which performs unqualified name lookup,
9326 /// and LookupQualifiedName, which performs qualified name lookup.
9327 ///
9328 /// All name lookup is performed based on some specific criteria,
9329 /// which specify what names will be visible to name lookup and how
9330 /// far name lookup should work. These criteria are important both
9331 /// for capturing language semantics (certain lookups will ignore
9332 /// certain names, for example) and for performance, since name
9333 /// lookup is often a bottleneck in the compilation of C++. Name
9334 /// lookup criteria is specified via the LookupCriteria enumeration.
9335 ///
9336 /// The results of name lookup can vary based on the kind of name
9337 /// lookup performed, the current language, and the translation
9338 /// unit. In C, for example, name lookup will either return nothing
9339 /// (no entity found) or a single declaration. In C++, name lookup
9340 /// can additionally refer to a set of overloaded functions or
9341 /// result in an ambiguity. All of the possible results of name
9342 /// lookup are captured by the LookupResult class, which provides
9343 /// the ability to distinguish among them.
9344 ///
9345 /// Implementations are in SemaLookup.cpp
9346 ///@{
9347
9348public:
9349 /// Tracks whether we are in a context where typo correction is
9350 /// disabled.
9351 bool DisableTypoCorrection;
9352
9353 /// The number of typos corrected by CorrectTypo.
9354 unsigned TyposCorrected;
9355
9356 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9357 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9358
9359 /// A cache containing identifiers for which typo correction failed and
9360 /// their locations, so that repeated attempts to correct an identifier in a
9361 /// given location are ignored if typo correction already failed for it.
9362 IdentifierSourceLocations TypoCorrectionFailures;
9363
9364 /// SpecialMemberOverloadResult - The overloading result for a special member
9365 /// function.
9366 ///
9367 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
9368 /// integer are used to determine whether overload resolution succeeded.
9369 class SpecialMemberOverloadResult {
9370 public:
9371 enum Kind { NoMemberOrDeleted, Ambiguous, Success };
9372
9373 private:
9374 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
9375
9376 public:
9377 SpecialMemberOverloadResult() {}
9378 SpecialMemberOverloadResult(CXXMethodDecl *MD)
9379 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
9380
9381 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
9382 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
9383
9384 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
9385 void setKind(Kind K) { Pair.setInt(K); }
9386 };
9387
9388 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode,
9389 public SpecialMemberOverloadResult {
9390 public:
9391 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
9392 : FastFoldingSetNode(ID) {}
9393 };
9394
9395 /// A cache of special member function overload resolution results
9396 /// for C++ records.
9397 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
9398
9399 enum class AcceptableKind { Visible, Reachable };
9400
9401 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
9402 // TODO: make this is a typesafe union.
9403 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
9404 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
9405
9406 /// Describes the kind of name lookup to perform.
9407 enum LookupNameKind {
9408 /// Ordinary name lookup, which finds ordinary names (functions,
9409 /// variables, typedefs, etc.) in C and most kinds of names
9410 /// (functions, variables, members, types, etc.) in C++.
9411 LookupOrdinaryName = 0,
9412 /// Tag name lookup, which finds the names of enums, classes,
9413 /// structs, and unions.
9414 LookupTagName,
9415 /// Label name lookup.
9416 LookupLabel,
9417 /// Member name lookup, which finds the names of
9418 /// class/struct/union members.
9419 LookupMemberName,
9420 /// Look up of an operator name (e.g., operator+) for use with
9421 /// operator overloading. This lookup is similar to ordinary name
9422 /// lookup, but will ignore any declarations that are class members.
9423 LookupOperatorName,
9424 /// Look up a name following ~ in a destructor name. This is an ordinary
9425 /// lookup, but prefers tags to typedefs.
9426 LookupDestructorName,
9427 /// Look up of a name that precedes the '::' scope resolution
9428 /// operator in C++. This lookup completely ignores operator, object,
9429 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
9430 LookupNestedNameSpecifierName,
9431 /// Look up a namespace name within a C++ using directive or
9432 /// namespace alias definition, ignoring non-namespace names (C++
9433 /// [basic.lookup.udir]p1).
9434 LookupNamespaceName,
9435 /// Look up all declarations in a scope with the given name,
9436 /// including resolved using declarations. This is appropriate
9437 /// for checking redeclarations for a using declaration.
9438 LookupUsingDeclName,
9439 /// Look up an ordinary name that is going to be redeclared as a
9440 /// name with linkage. This lookup ignores any declarations that
9441 /// are outside of the current scope unless they have linkage. See
9442 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
9443 LookupRedeclarationWithLinkage,
9444 /// Look up a friend of a local class. This lookup does not look
9445 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
9446 LookupLocalFriendName,
9447 /// Look up the name of an Objective-C protocol.
9448 LookupObjCProtocolName,
9449 /// Look up implicit 'self' parameter of an objective-c method.
9450 LookupObjCImplicitSelfParam,
9451 /// Look up the name of an OpenMP user-defined reduction operation.
9452 LookupOMPReductionName,
9453 /// Look up the name of an OpenMP user-defined mapper.
9454 LookupOMPMapperName,
9455 /// Look up any declaration with any name.
9456 LookupAnyName
9457 };
9458
9459 /// The possible outcomes of name lookup for a literal operator.
9460 enum LiteralOperatorLookupResult {
9461 /// The lookup resulted in an error.
9462 LOLR_Error,
9463 /// The lookup found no match but no diagnostic was issued.
9464 LOLR_ErrorNoDiagnostic,
9465 /// The lookup found a single 'cooked' literal operator, which
9466 /// expects a normal literal to be built and passed to it.
9467 LOLR_Cooked,
9468 /// The lookup found a single 'raw' literal operator, which expects
9469 /// a string literal containing the spelling of the literal token.
9470 LOLR_Raw,
9471 /// The lookup found an overload set of literal operator templates,
9472 /// which expect the characters of the spelling of the literal token to be
9473 /// passed as a non-type template argument pack.
9474 LOLR_Template,
9475 /// The lookup found an overload set of literal operator templates,
9476 /// which expect the character type and characters of the spelling of the
9477 /// string literal token to be passed as template arguments.
9478 LOLR_StringTemplatePack,
9479 };
9480
9481 SpecialMemberOverloadResult
9482 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg,
9483 bool VolatileArg, bool RValueThis, bool ConstThis,
9484 bool VolatileThis);
9485
9486 RedeclarationKind forRedeclarationInCurContext() const;
9487
9488 /// Look up a name, looking for a single declaration. Return
9489 /// null if the results were absent, ambiguous, or overloaded.
9490 ///
9491 /// It is preferable to use the elaborated form and explicitly handle
9492 /// ambiguity and overloaded.
9493 NamedDecl *LookupSingleName(
9494 Scope *S, DeclarationName Name, SourceLocation Loc,
9495 LookupNameKind NameKind,
9496 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration);
9497
9498 /// Lookup a builtin function, when name lookup would otherwise
9499 /// fail.
9500 bool LookupBuiltin(LookupResult &R);
9501 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
9502
9503 /// Perform unqualified name lookup starting from a given
9504 /// scope.
9505 ///
9506 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
9507 /// used to find names within the current scope. For example, 'x' in
9508 /// @code
9509 /// int x;
9510 /// int f() {
9511 /// return x; // unqualified name look finds 'x' in the global scope
9512 /// }
9513 /// @endcode
9514 ///
9515 /// Different lookup criteria can find different names. For example, a
9516 /// particular scope can have both a struct and a function of the same
9517 /// name, and each can be found by certain lookup criteria. For more
9518 /// information about lookup criteria, see the documentation for the
9519 /// class LookupCriteria.
9520 ///
9521 /// @param S The scope from which unqualified name lookup will
9522 /// begin. If the lookup criteria permits, name lookup may also search
9523 /// in the parent scopes.
9524 ///
9525 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
9526 /// look up and the lookup kind), and is updated with the results of lookup
9527 /// including zero or more declarations and possibly additional information
9528 /// used to diagnose ambiguities.
9529 ///
9530 /// @returns \c true if lookup succeeded and false otherwise.
9531 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
9532 bool ForceNoCPlusPlus = false);
9533
9534 /// Perform qualified name lookup into a given context.
9535 ///
9536 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
9537 /// names when the context of those names is explicit specified, e.g.,
9538 /// "std::vector" or "x->member", or as part of unqualified name lookup.
9539 ///
9540 /// Different lookup criteria can find different names. For example, a
9541 /// particular scope can have both a struct and a function of the same
9542 /// name, and each can be found by certain lookup criteria. For more
9543 /// information about lookup criteria, see the documentation for the
9544 /// class LookupCriteria.
9545 ///
9546 /// \param R captures both the lookup criteria and any lookup results found.
9547 ///
9548 /// \param LookupCtx The context in which qualified name lookup will
9549 /// search. If the lookup criteria permits, name lookup may also search
9550 /// in the parent contexts or (for C++ classes) base classes.
9551 ///
9552 /// \param InUnqualifiedLookup true if this is qualified name lookup that
9553 /// occurs as part of unqualified name lookup.
9554 ///
9555 /// \returns true if lookup succeeded, false if it failed.
9556 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9557 bool InUnqualifiedLookup = false);
9558
9559 /// Performs qualified name lookup or special type of lookup for
9560 /// "__super::" scope specifier.
9561 ///
9562 /// This routine is a convenience overload meant to be called from contexts
9563 /// that need to perform a qualified name lookup with an optional C++ scope
9564 /// specifier that might require special kind of lookup.
9565 ///
9566 /// \param R captures both the lookup criteria and any lookup results found.
9567 ///
9568 /// \param LookupCtx The context in which qualified name lookup will
9569 /// search.
9570 ///
9571 /// \param SS An optional C++ scope-specifier.
9572 ///
9573 /// \returns true if lookup succeeded, false if it failed.
9574 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
9575 CXXScopeSpec &SS);
9576
9577 /// Performs name lookup for a name that was parsed in the
9578 /// source code, and may contain a C++ scope specifier.
9579 ///
9580 /// This routine is a convenience routine meant to be called from
9581 /// contexts that receive a name and an optional C++ scope specifier
9582 /// (e.g., "N::M::x"). It will then perform either qualified or
9583 /// unqualified name lookup (with LookupQualifiedName or LookupName,
9584 /// respectively) on the given name and return those results. It will
9585 /// perform a special type of lookup for "__super::" scope specifier.
9586 ///
9587 /// @param S The scope from which unqualified name lookup will
9588 /// begin.
9589 ///
9590 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
9591 ///
9592 /// @param EnteringContext Indicates whether we are going to enter the
9593 /// context of the scope-specifier SS (if present).
9594 ///
9595 /// @returns True if any decls were found (but possibly ambiguous)
9596 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
9597 QualType ObjectType, bool AllowBuiltinCreation = false,
9598 bool EnteringContext = false);
9599
9600 /// Perform qualified name lookup into all base classes of the given
9601 /// class.
9602 ///
9603 /// \param R captures both the lookup criteria and any lookup results found.
9604 ///
9605 /// \param Class The context in which qualified name lookup will
9606 /// search. Name lookup will search in all base classes merging the results.
9607 ///
9608 /// @returns True if any decls were found (but possibly ambiguous)
9609 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
9610
9611 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
9612 UnresolvedSetImpl &Functions);
9613
9614 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
9615 /// If GnuLabelLoc is a valid source location, then this is a definition
9616 /// of an __label__ label name, otherwise it is a normal label definition
9617 /// or use.
9618 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
9619 SourceLocation GnuLabelLoc = SourceLocation());
9620
9621 /// Perform a name lookup for a label with the specified name; this does not
9622 /// create a new label if the lookup fails.
9623 LabelDecl *LookupExistingLabel(IdentifierInfo *II, SourceLocation IdentLoc);
9624
9625 /// Look up the constructors for the given class.
9626 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
9627
9628 /// Look up the default constructor for the given class.
9629 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
9630
9631 /// Look up the copying constructor for the given class.
9632 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
9633 unsigned Quals);
9634
9635 /// Look up the copying assignment operator for the given class.
9636 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
9637 bool RValueThis, unsigned ThisQuals);
9638
9639 /// Look up the moving constructor for the given class.
9640 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
9641 unsigned Quals);
9642
9643 /// Look up the moving assignment operator for the given class.
9644 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
9645 bool RValueThis, unsigned ThisQuals);
9646
9647 /// Look for the destructor of the given class.
9648 ///
9649 /// During semantic analysis, this routine should be used in lieu of
9650 /// CXXRecordDecl::getDestructor().
9651 ///
9652 /// \returns The destructor for this class.
9653 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
9654
9655 /// Force the declaration of any implicitly-declared members of this
9656 /// class.
9657 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
9658
9659 /// Make a merged definition of an existing hidden definition \p ND
9660 /// visible at the specified location.
9661 void makeMergedDefinitionVisible(NamedDecl *ND);
9662
9663 /// Check ODR hashes for C/ObjC when merging types from modules.
9664 /// Differently from C++, actually parse the body and reject in case
9665 /// of a mismatch.
9666 template <typename T,
9667 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
9668 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
9669 if (Duplicate->getODRHash() != Previous->getODRHash())
9670 return false;
9671
9672 // Make the previous decl visible.
9673 makeMergedDefinitionVisible(ND: Previous);
9674 return true;
9675 }
9676
9677 /// Get the set of additional modules that should be checked during
9678 /// name lookup. A module and its imports become visible when instanting a
9679 /// template defined within it.
9680 llvm::DenseSet<Module *> &getLookupModules();
9681
9682 bool hasVisibleMergedDefinition(const NamedDecl *Def);
9683 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
9684
9685 /// Determine if the template parameter \p D has a visible default argument.
9686 bool
9687 hasVisibleDefaultArgument(const NamedDecl *D,
9688 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9689 /// Determine if the template parameter \p D has a reachable default argument.
9690 bool hasReachableDefaultArgument(
9691 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9692 /// Determine if the template parameter \p D has a reachable default argument.
9693 bool hasAcceptableDefaultArgument(const NamedDecl *D,
9694 llvm::SmallVectorImpl<Module *> *Modules,
9695 Sema::AcceptableKind Kind);
9696
9697 /// Determine if there is a visible declaration of \p D that is an explicit
9698 /// specialization declaration for a specialization of a template. (For a
9699 /// member specialization, use hasVisibleMemberSpecialization.)
9700 bool hasVisibleExplicitSpecialization(
9701 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9702 /// Determine if there is a reachable declaration of \p D that is an explicit
9703 /// specialization declaration for a specialization of a template. (For a
9704 /// member specialization, use hasReachableMemberSpecialization.)
9705 bool hasReachableExplicitSpecialization(
9706 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9707
9708 /// Determine if there is a visible declaration of \p D that is a member
9709 /// specialization declaration (as opposed to an instantiated declaration).
9710 bool hasVisibleMemberSpecialization(
9711 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9712 /// Determine if there is a reachable declaration of \p D that is a member
9713 /// specialization declaration (as opposed to an instantiated declaration).
9714 bool hasReachableMemberSpecialization(
9715 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9716
9717 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
9718
9719 /// Determine whether any declaration of an entity is visible.
9720 bool
9721 hasVisibleDeclaration(const NamedDecl *D,
9722 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9723 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
9724 }
9725
9726 bool hasVisibleDeclarationSlow(const NamedDecl *D,
9727 llvm::SmallVectorImpl<Module *> *Modules);
9728 /// Determine whether any declaration of an entity is reachable.
9729 bool
9730 hasReachableDeclaration(const NamedDecl *D,
9731 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
9732 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
9733 }
9734 bool hasReachableDeclarationSlow(
9735 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
9736
9737 void diagnoseTypo(const TypoCorrection &Correction,
9738 const PartialDiagnostic &TypoDiag,
9739 bool ErrorRecovery = true);
9740
9741 /// Diagnose a successfully-corrected typo. Separated from the correction
9742 /// itself to allow external validation of the result, etc.
9743 ///
9744 /// \param Correction The result of performing typo correction.
9745 /// \param TypoDiag The diagnostic to produce. This will have the corrected
9746 /// string added to it (and usually also a fixit).
9747 /// \param PrevNote A note to use when indicating the location of the entity
9748 /// to which we are correcting. Will have the correction string added
9749 /// to it.
9750 /// \param ErrorRecovery If \c true (the default), the caller is going to
9751 /// recover from the typo as if the corrected string had been typed.
9752 /// In this case, \c PDiag must be an error, and we will attach a fixit
9753 /// to it.
9754 void diagnoseTypo(const TypoCorrection &Correction,
9755 const PartialDiagnostic &TypoDiag,
9756 const PartialDiagnostic &PrevNote,
9757 bool ErrorRecovery = true);
9758
9759 /// Find the associated classes and namespaces for
9760 /// argument-dependent lookup for a call with the given set of
9761 /// arguments.
9762 ///
9763 /// This routine computes the sets of associated classes and associated
9764 /// namespaces searched by argument-dependent lookup
9765 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
9766 void FindAssociatedClassesAndNamespaces(
9767 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
9768 AssociatedNamespaceSet &AssociatedNamespaces,
9769 AssociatedClassSet &AssociatedClasses);
9770
9771 /// Produce a diagnostic describing the ambiguity that resulted
9772 /// from name lookup.
9773 ///
9774 /// \param Result The result of the ambiguous lookup to be diagnosed.
9775 void DiagnoseAmbiguousLookup(LookupResult &Result);
9776
9777 /// LookupLiteralOperator - Determine which literal operator should be used
9778 /// for a user-defined literal, per C++11 [lex.ext].
9779 ///
9780 /// Normal overload resolution is not used to select which literal operator to
9781 /// call for a user-defined literal. Look up the provided literal operator
9782 /// name, and filter the results to the appropriate set for the given argument
9783 /// types.
9784 LiteralOperatorLookupResult
9785 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
9786 bool AllowRaw, bool AllowTemplate,
9787 bool AllowStringTemplate, bool DiagnoseMissing,
9788 StringLiteral *StringLit = nullptr);
9789
9790 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
9791 ArrayRef<Expr *> Args, ADLResult &Functions);
9792
9793 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
9794 VisibleDeclConsumer &Consumer,
9795 bool IncludeGlobalScope = true,
9796 bool LoadExternal = true);
9797 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
9798 VisibleDeclConsumer &Consumer,
9799 bool IncludeGlobalScope = true,
9800 bool IncludeDependentBases = false,
9801 bool LoadExternal = true);
9802
9803 /// Try to "correct" a typo in the source code by finding
9804 /// visible declarations whose names are similar to the name that was
9805 /// present in the source code.
9806 ///
9807 /// \param TypoName the \c DeclarationNameInfo structure that contains
9808 /// the name that was present in the source code along with its location.
9809 ///
9810 /// \param LookupKind the name-lookup criteria used to search for the name.
9811 ///
9812 /// \param S the scope in which name lookup occurs.
9813 ///
9814 /// \param SS the nested-name-specifier that precedes the name we're
9815 /// looking for, if present.
9816 ///
9817 /// \param CCC A CorrectionCandidateCallback object that provides further
9818 /// validation of typo correction candidates. It also provides flags for
9819 /// determining the set of keywords permitted.
9820 ///
9821 /// \param MemberContext if non-NULL, the context in which to look for
9822 /// a member access expression.
9823 ///
9824 /// \param EnteringContext whether we're entering the context described by
9825 /// the nested-name-specifier SS.
9826 ///
9827 /// \param OPT when non-NULL, the search for visible declarations will
9828 /// also walk the protocols in the qualified interfaces of \p OPT.
9829 ///
9830 /// \returns a \c TypoCorrection containing the corrected name if the typo
9831 /// along with information such as the \c NamedDecl where the corrected name
9832 /// was declared, and any additional \c NestedNameSpecifier needed to access
9833 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
9834 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
9835 Sema::LookupNameKind LookupKind, Scope *S,
9836 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9837 CorrectTypoKind Mode,
9838 DeclContext *MemberContext = nullptr,
9839 bool EnteringContext = false,
9840 const ObjCObjectPointerType *OPT = nullptr,
9841 bool RecordFailure = true);
9842
9843 /// Kinds of missing import. Note, the values of these enumerators correspond
9844 /// to %select values in diagnostics.
9845 enum class MissingImportKind {
9846 Declaration,
9847 Definition,
9848 DefaultArgument,
9849 ExplicitSpecialization,
9850 PartialSpecialization
9851 };
9852
9853 /// Diagnose that the specified declaration needs to be visible but
9854 /// isn't, and suggest a module import that would resolve the problem.
9855 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9856 MissingImportKind MIK, bool Recover = true);
9857 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
9858 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
9859 MissingImportKind MIK, bool Recover);
9860
9861 /// Called on #pragma clang __debug dump II
9862 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
9863
9864 /// Called on #pragma clang __debug dump E
9865 void ActOnPragmaDump(Expr *E);
9866
9867private:
9868 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
9869 //
9870 // The boolean value will be true to indicate that the namespace was loaded
9871 // from an AST/PCH file, or false otherwise.
9872 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces;
9873
9874 /// Whether we have already loaded known namespaces from an extenal
9875 /// source.
9876 bool LoadedExternalKnownNamespaces;
9877
9878 bool CppLookupName(LookupResult &R, Scope *S);
9879
9880 /// Determine if we could use all the declarations in the module.
9881 bool isUsableModule(const Module *M);
9882
9883 /// Helper for CorrectTypo used to create and populate a new
9884 /// TypoCorrectionConsumer. Returns nullptr if typo correction should be
9885 /// skipped entirely.
9886 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(
9887 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind,
9888 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
9889 DeclContext *MemberContext, bool EnteringContext,
9890 const ObjCObjectPointerType *OPT, bool ErrorRecovery);
9891
9892 /// Cache for module units which is usable for current module.
9893 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
9894
9895 /// Record the typo correction failure and return an empty correction.
9896 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
9897 bool RecordFailure = true) {
9898 if (RecordFailure)
9899 TypoCorrectionFailures[Typo].insert(V: TypoLoc);
9900 return TypoCorrection();
9901 }
9902
9903 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
9904
9905 /// Determine whether two declarations should be linked together, given that
9906 /// the old declaration might not be visible and the new declaration might
9907 /// not have external linkage.
9908 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
9909 const NamedDecl *New) {
9910 if (isVisible(D: Old))
9911 return true;
9912 // See comment in below overload for why it's safe to compute the linkage
9913 // of the new declaration here.
9914 if (New->isExternallyDeclarable()) {
9915 assert(Old->isExternallyDeclarable() &&
9916 "should not have found a non-externally-declarable previous decl");
9917 return true;
9918 }
9919 return false;
9920 }
9921 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
9922
9923 ///@}
9924
9925 //
9926 //
9927 // -------------------------------------------------------------------------
9928 //
9929 //
9930
9931 /// \name Modules
9932 /// Implementations are in SemaModule.cpp
9933 ///@{
9934
9935public:
9936 /// Get the module unit whose scope we are currently within.
9937 Module *getCurrentModule() const {
9938 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
9939 }
9940
9941 /// Is the module scope we are an implementation unit?
9942 bool currentModuleIsImplementation() const {
9943 if (ModuleScopes.empty())
9944 return false;
9945 const Module *M = ModuleScopes.back().Module;
9946 return M->isModuleImplementation() || M->isModulePartitionImplementation();
9947 }
9948
9949 // When loading a non-modular PCH files, this is used to restore module
9950 // visibility.
9951 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
9952 VisibleModules.setVisible(M: Mod, Loc: ImportLoc);
9953 }
9954
9955 enum class ModuleDeclKind {
9956 Interface, ///< 'export module X;'
9957 Implementation, ///< 'module X;'
9958 PartitionInterface, ///< 'export module X:Y;'
9959 PartitionImplementation, ///< 'module X:Y;'
9960 };
9961
9962 /// An enumeration to represent the transition of states in parsing module
9963 /// fragments and imports. If we are not parsing a C++20 TU, or we find
9964 /// an error in state transition, the state is set to NotACXX20Module.
9965 enum class ModuleImportState {
9966 FirstDecl, ///< Parsing the first decl in a TU.
9967 GlobalFragment, ///< after 'module;' but before 'module X;'
9968 ImportAllowed, ///< after 'module X;' but before any non-import decl.
9969 ImportFinished, ///< after any non-import decl.
9970 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
9971 ///< non-import decl.
9972 PrivateFragmentImportFinished, ///< after 'module :private;' but a
9973 ///< non-import decl has already been seen.
9974 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
9975 };
9976
9977 /// The parser has processed a module-declaration that begins the definition
9978 /// of a module interface or implementation.
9979 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
9980 SourceLocation ModuleLoc, ModuleDeclKind MDK,
9981 ModuleIdPath Path, ModuleIdPath Partition,
9982 ModuleImportState &ImportState,
9983 bool SeenNoTrivialPPDirective);
9984
9985 /// The parser has processed a global-module-fragment declaration that begins
9986 /// the definition of the global module fragment of the current module unit.
9987 /// \param ModuleLoc The location of the 'module' keyword.
9988 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
9989
9990 /// The parser has processed a private-module-fragment declaration that begins
9991 /// the definition of the private module fragment of the current module unit.
9992 /// \param ModuleLoc The location of the 'module' keyword.
9993 /// \param PrivateLoc The location of the 'private' keyword.
9994 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
9995 SourceLocation PrivateLoc);
9996
9997 /// The parser has processed a module import declaration.
9998 ///
9999 /// \param StartLoc The location of the first token in the declaration. This
10000 /// could be the location of an '@', 'export', or 'import'.
10001 /// \param ExportLoc The location of the 'export' keyword, if any.
10002 /// \param ImportLoc The location of the 'import' keyword.
10003 /// \param Path The module toplevel name as an access path.
10004 /// \param IsPartition If the name is for a partition.
10005 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10006 SourceLocation ExportLoc,
10007 SourceLocation ImportLoc, ModuleIdPath Path,
10008 bool IsPartition = false);
10009 DeclResult ActOnModuleImport(SourceLocation StartLoc,
10010 SourceLocation ExportLoc,
10011 SourceLocation ImportLoc, Module *M,
10012 ModuleIdPath Path = {});
10013
10014 /// The parser has processed a module import translated from a
10015 /// #include or similar preprocessing directive.
10016 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10017 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
10018
10019 /// The parsed has entered a submodule.
10020 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
10021 /// The parser has left a submodule.
10022 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
10023
10024 /// Create an implicit import of the given module at the given
10025 /// source location, for error recovery, if possible.
10026 ///
10027 /// This routine is typically used when an entity found by name lookup
10028 /// is actually hidden within a module that we know about but the user
10029 /// has forgotten to import.
10030 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
10031 Module *Mod);
10032
10033 /// We have parsed the start of an export declaration, including the '{'
10034 /// (if present).
10035 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
10036 SourceLocation LBraceLoc);
10037
10038 /// Complete the definition of an export declaration.
10039 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
10040 SourceLocation RBraceLoc);
10041
10042private:
10043 /// The parser has begun a translation unit to be compiled as a C++20
10044 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
10045 void HandleStartOfHeaderUnit();
10046
10047 struct ModuleScope {
10048 SourceLocation BeginLoc;
10049 clang::Module *Module = nullptr;
10050 VisibleModuleSet OuterVisibleModules;
10051 };
10052 /// The modules we're currently parsing.
10053 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
10054
10055 /// For an interface unit, this is the implicitly imported interface unit.
10056 clang::Module *ThePrimaryInterface = nullptr;
10057
10058 /// The explicit global module fragment of the current translation unit.
10059 /// The explicit Global Module Fragment, as specified in C++
10060 /// [module.global.frag].
10061 clang::Module *TheGlobalModuleFragment = nullptr;
10062
10063 /// The implicit global module fragments of the current translation unit.
10064 ///
10065 /// The contents in the implicit global module fragment can't be discarded.
10066 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
10067
10068 /// Namespace definitions that we will export when they finish.
10069 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces;
10070
10071 /// In a C++ standard module, inline declarations require a definition to be
10072 /// present at the end of a definition domain. This set holds the decls to
10073 /// be checked at the end of the TU.
10074 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
10075
10076 /// Helper function to judge if we are in module purview.
10077 /// Return false if we are not in a module.
10078 bool isCurrentModulePurview() const;
10079
10080 /// Enter the scope of the explicit global module fragment.
10081 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
10082 /// Leave the scope of the explicit global module fragment.
10083 void PopGlobalModuleFragment();
10084
10085 /// Enter the scope of an implicit global module fragment.
10086 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc);
10087 /// Leave the scope of an implicit global module fragment.
10088 void PopImplicitGlobalModuleFragment();
10089
10090 VisibleModuleSet VisibleModules;
10091
10092 /// Whether we had imported any named modules.
10093 bool HadImportedNamedModules = false;
10094 /// The set of instantiations we need to check if they references TU-local
10095 /// entity from TUs. This only makes sense if we imported any named modules.
10096 llvm::SmallVector<std::pair<FunctionDecl *, SourceLocation>>
10097 PendingCheckReferenceForTULocal;
10098 /// Implement [basic.link]p18, which requires that we can't use TU-local
10099 /// entities from other TUs (ignoring header units).
10100 void checkReferenceToTULocalFromOtherTU(FunctionDecl *FD,
10101 SourceLocation PointOfInstantiation);
10102 /// Implement [basic.link]p17, which diagnose for non TU local exposure in
10103 /// module interface or module partition.
10104 void checkExposure(const TranslationUnitDecl *TU);
10105
10106 ///@}
10107
10108 //
10109 //
10110 // -------------------------------------------------------------------------
10111 //
10112 //
10113
10114 /// \name C++ Overloading
10115 /// Implementations are in SemaOverload.cpp
10116 ///@{
10117
10118public:
10119 /// Whether deferrable diagnostics should be deferred.
10120 bool DeferDiags = false;
10121
10122 /// RAII class to control scope of DeferDiags.
10123 class DeferDiagsRAII {
10124 Sema &S;
10125 bool SavedDeferDiags = false;
10126
10127 public:
10128 DeferDiagsRAII(Sema &S, bool DeferDiags)
10129 : S(S), SavedDeferDiags(S.DeferDiags) {
10130 S.DeferDiags = SavedDeferDiags || DeferDiags;
10131 }
10132 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
10133 DeferDiagsRAII(const DeferDiagsRAII &) = delete;
10134 DeferDiagsRAII &operator=(const DeferDiagsRAII &) = delete;
10135 };
10136
10137 /// Flag indicating if Sema is building a recovery call expression.
10138 ///
10139 /// This flag is used to avoid building recovery call expressions
10140 /// if Sema is already doing so, which would cause infinite recursions.
10141 bool IsBuildingRecoveryCallExpr;
10142
10143 /// Determine whether the given New declaration is an overload of the
10144 /// declarations in Old. This routine returns OverloadKind::Match or
10145 /// OverloadKind::NonFunction if New and Old cannot be overloaded, e.g., if
10146 /// New has the same signature as some function in Old (C++ 1.3.10) or if the
10147 /// Old declarations aren't functions (or function templates) at all. When it
10148 /// does return OverloadKind::Match or OverloadKind::NonFunction, MatchedDecl
10149 /// will point to the decl that New cannot be overloaded with. This decl may
10150 /// be a UsingShadowDecl on top of the underlying declaration.
10151 ///
10152 /// Example: Given the following input:
10153 ///
10154 /// void f(int, float); // #1
10155 /// void f(int, int); // #2
10156 /// int f(int, int); // #3
10157 ///
10158 /// When we process #1, there is no previous declaration of "f", so IsOverload
10159 /// will not be used.
10160 ///
10161 /// When we process #2, Old contains only the FunctionDecl for #1. By
10162 /// comparing the parameter types, we see that #1 and #2 are overloaded (since
10163 /// they have different signatures), so this routine returns
10164 /// OverloadKind::Overload; MatchedDecl is unchanged.
10165 ///
10166 /// When we process #3, Old is an overload set containing #1 and #2. We
10167 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing)
10168 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return
10169 /// types of functions are not part of the signature), IsOverload returns
10170 /// OverloadKind::Match and MatchedDecl will be set to point to the
10171 /// FunctionDecl for #2.
10172 ///
10173 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a
10174 /// class by a using declaration. The rules for whether to hide shadow
10175 /// declarations ignore some properties which otherwise figure into a function
10176 /// template's signature.
10177 OverloadKind CheckOverload(Scope *S, FunctionDecl *New,
10178 const LookupResult &OldDecls, NamedDecl *&OldDecl,
10179 bool UseMemberUsingDeclRules);
10180 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
10181 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10182
10183 // Checks whether MD constitutes an override the base class method BaseMD.
10184 // When checking for overrides, the object object members are ignored.
10185 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
10186 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true);
10187
10188 enum class AllowedExplicit {
10189 /// Allow no explicit functions to be used.
10190 None,
10191 /// Allow explicit conversion functions but not explicit constructors.
10192 Conversions,
10193 /// Allow both explicit conversion functions and explicit constructors.
10194 All
10195 };
10196
10197 ImplicitConversionSequence TryImplicitConversion(
10198 Expr *From, QualType ToType, bool SuppressUserConversions,
10199 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle,
10200 bool AllowObjCWritebackConversion);
10201
10202 /// PerformImplicitConversion - Perform an implicit conversion of the
10203 /// expression From to the type ToType. Returns the
10204 /// converted expression. Flavor is the kind of conversion we're
10205 /// performing, used in the error message. If @p AllowExplicit,
10206 /// explicit user-defined conversions are permitted.
10207 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
10208 AssignmentAction Action,
10209 bool AllowExplicit = false);
10210
10211 /// IsIntegralPromotion - Determines whether the conversion from the
10212 /// expression From (whose potentially-adjusted type is FromType) to
10213 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
10214 /// sets PromotedType to the promoted type.
10215 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
10216
10217 /// IsFloatingPointPromotion - Determines whether the conversion from
10218 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
10219 /// returns true and sets PromotedType to the promoted type.
10220 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
10221
10222 /// Determine if a conversion is a complex promotion.
10223 ///
10224 /// A complex promotion is defined as a complex -> complex conversion
10225 /// where the conversion between the underlying real types is a
10226 /// floating-point or integral promotion.
10227 bool IsComplexPromotion(QualType FromType, QualType ToType);
10228
10229 /// IsOverflowBehaviorTypePromotion - Determines whether the conversion from
10230 /// FromType to ToType involves an OverflowBehaviorType FromType being
10231 /// promoted to an OverflowBehaviorType ToType which has a larger bitwidth.
10232 /// If so, returns true and sets FromType to ToType.
10233 bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType);
10234
10235 /// IsOverflowBehaviorTypeConversion - Determines whether the conversion from
10236 /// FromType to ToType necessarily involves both an OverflowBehaviorType and
10237 /// a non-OverflowBehaviorType. If so, returns true and sets FromType to
10238 /// ToType.
10239 bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType);
10240
10241 /// IsPointerConversion - Determines whether the conversion of the
10242 /// expression From, which has the (possibly adjusted) type FromType,
10243 /// can be converted to the type ToType via a pointer conversion (C++
10244 /// 4.10). If so, returns true and places the converted type (that
10245 /// might differ from ToType in its cv-qualifiers at some level) into
10246 /// ConvertedType.
10247 ///
10248 /// This routine also supports conversions to and from block pointers
10249 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
10250 /// pointers to interfaces. FIXME: Once we've determined the
10251 /// appropriate overloading rules for Objective-C, we may want to
10252 /// split the Objective-C checks into a different routine; however,
10253 /// GCC seems to consider all of these conversions to be pointer
10254 /// conversions, so for now they live here. IncompatibleObjC will be
10255 /// set if the conversion is an allowed Objective-C conversion that
10256 /// should result in a warning.
10257 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
10258 bool InOverloadResolution, QualType &ConvertedType,
10259 bool &IncompatibleObjC);
10260
10261 /// isObjCPointerConversion - Determines whether this is an
10262 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
10263 /// with the same arguments and return values.
10264 bool isObjCPointerConversion(QualType FromType, QualType ToType,
10265 QualType &ConvertedType, bool &IncompatibleObjC);
10266 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
10267 QualType &ConvertedType);
10268
10269 /// FunctionParamTypesAreEqual - This routine checks two function proto types
10270 /// for equality of their parameter types. Caller has already checked that
10271 /// they have same number of parameters. If the parameters are different,
10272 /// ArgPos will have the parameter index of the first different parameter.
10273 /// If `Reversed` is true, the parameters of `NewType` will be compared in
10274 /// reverse order. That's useful if one of the functions is being used as a
10275 /// C++20 synthesized operator overload with a reversed parameter order.
10276 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
10277 ArrayRef<QualType> New,
10278 unsigned *ArgPos = nullptr,
10279 bool Reversed = false);
10280
10281 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
10282 const FunctionProtoType *NewType,
10283 unsigned *ArgPos = nullptr,
10284 bool Reversed = false);
10285
10286 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
10287 const FunctionDecl *NewFunction,
10288 unsigned *ArgPos = nullptr,
10289 bool Reversed = false);
10290
10291 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
10292 /// function types. Catches different number of parameter, mismatch in
10293 /// parameter types, and different return types.
10294 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType,
10295 QualType ToType);
10296
10297 /// CheckPointerConversion - Check the pointer conversion from the
10298 /// expression From to the type ToType. This routine checks for
10299 /// ambiguous or inaccessible derived-to-base pointer
10300 /// conversions for which IsPointerConversion has already returned
10301 /// true. It returns true and produces a diagnostic if there was an
10302 /// error, or returns false otherwise.
10303 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind,
10304 CXXCastPath &BasePath, bool IgnoreBaseAccess,
10305 bool Diagnose = true);
10306
10307 /// IsMemberPointerConversion - Determines whether the conversion of the
10308 /// expression From, which has the (possibly adjusted) type FromType, can be
10309 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
10310 /// If so, returns true and places the converted type (that might differ from
10311 /// ToType in its cv-qualifiers at some level) into ConvertedType.
10312 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
10313 bool InOverloadResolution,
10314 QualType &ConvertedType);
10315
10316 enum class MemberPointerConversionResult {
10317 Success,
10318 DifferentPointee,
10319 NotDerived,
10320 Ambiguous,
10321 Virtual,
10322 Inaccessible
10323 };
10324 enum class MemberPointerConversionDirection : bool { Downcast, Upcast };
10325 /// CheckMemberPointerConversion - Check the member pointer conversion from
10326 /// the expression From to the type ToType. This routine checks for ambiguous
10327 /// or virtual or inaccessible base-to-derived member pointer conversions for
10328 /// which IsMemberPointerConversion has already returned true. It produces a
10329 // diagnostic if there was an error.
10330 MemberPointerConversionResult CheckMemberPointerConversion(
10331 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
10332 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
10333 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction);
10334
10335 /// IsQualificationConversion - Determines whether the conversion from
10336 /// an rvalue of type FromType to ToType is a qualification conversion
10337 /// (C++ 4.4).
10338 ///
10339 /// \param ObjCLifetimeConversion Output parameter that will be set to
10340 /// indicate when the qualification conversion involves a change in the
10341 /// Objective-C object lifetime.
10342 bool IsQualificationConversion(QualType FromType, QualType ToType,
10343 bool CStyle, bool &ObjCLifetimeConversion);
10344
10345 /// Determine whether the conversion from FromType to ToType is a valid
10346 /// conversion of ExtInfo/ExtProtoInfo on the nested function type.
10347 /// More precisely, this method checks whether FromType can be transformed
10348 /// into an exact match for ToType, by transforming its extended function
10349 /// type information in legal manner (e.g. by strictly stripping "noreturn"
10350 /// or "noexcept", or by stripping "noescape" for arguments).
10351 bool IsFunctionConversion(QualType FromType, QualType ToType) const;
10352
10353 /// Same as `IsFunctionConversion`, but if this would return true, it sets
10354 /// `ResultTy` to `ToType`.
10355 bool TryFunctionConversion(QualType FromType, QualType ToType,
10356 QualType &ResultTy) const;
10357
10358 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
10359 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
10360 DeclarationName Name,
10361 OverloadCandidateSet &CandidateSet,
10362 FunctionDecl *Fn, MultiExprArg Args,
10363 bool IsMember = false);
10364
10365 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
10366 FunctionDecl *Fun);
10367 ExprResult PerformImplicitObjectArgumentInitialization(
10368 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
10369 CXXMethodDecl *Method);
10370
10371 /// PerformContextuallyConvertToBool - Perform a contextual conversion
10372 /// of the expression From to bool (C++0x [conv]p3).
10373 ExprResult PerformContextuallyConvertToBool(Expr *From);
10374
10375 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
10376 /// conversion of the expression From to an Objective-C pointer type.
10377 /// Returns a valid but null ExprResult if no conversion sequence exists.
10378 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
10379
10380 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T,
10381 CCEKind CCE,
10382 NamedDecl *Dest = nullptr);
10383
10384 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10385 llvm::APSInt &Value, CCEKind CCE);
10386 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
10387 APValue &Value, CCEKind CCE,
10388 NamedDecl *Dest = nullptr);
10389
10390 /// EvaluateConvertedConstantExpression - Evaluate an Expression
10391 /// That is a converted constant expression
10392 /// (which was built with BuildConvertedConstantExpression)
10393 ExprResult
10394 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
10395 CCEKind CCE, bool RequireInt,
10396 const APValue &PreNarrowingValue);
10397
10398 /// Abstract base class used to perform a contextual implicit
10399 /// conversion from an expression to any type passing a filter.
10400 class ContextualImplicitConverter {
10401 public:
10402 bool Suppress;
10403 bool SuppressConversion;
10404
10405 ContextualImplicitConverter(bool Suppress = false,
10406 bool SuppressConversion = false)
10407 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
10408
10409 /// Determine whether the specified type is a valid destination type
10410 /// for this conversion.
10411 virtual bool match(QualType T) = 0;
10412
10413 /// Emits a diagnostic complaining that the expression does not have
10414 /// integral or enumeration type.
10415 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10416 QualType T) = 0;
10417
10418 /// Emits a diagnostic when the expression has incomplete class type.
10419 virtual SemaDiagnosticBuilder
10420 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
10421
10422 /// Emits a diagnostic when the only matching conversion function
10423 /// is explicit.
10424 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S,
10425 SourceLocation Loc,
10426 QualType T,
10427 QualType ConvTy) = 0;
10428
10429 /// Emits a note for the explicit conversion function.
10430 virtual SemaDiagnosticBuilder
10431 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10432
10433 /// Emits a diagnostic when there are multiple possible conversion
10434 /// functions.
10435 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10436 QualType T) = 0;
10437
10438 /// Emits a note for one of the candidate conversions.
10439 virtual SemaDiagnosticBuilder
10440 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
10441
10442 /// Emits a diagnostic when we picked a conversion function
10443 /// (for cases when we are not allowed to pick a conversion function).
10444 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S,
10445 SourceLocation Loc,
10446 QualType T,
10447 QualType ConvTy) = 0;
10448
10449 virtual ~ContextualImplicitConverter() {}
10450 };
10451
10452 class ICEConvertDiagnoser : public ContextualImplicitConverter {
10453 bool AllowScopedEnumerations;
10454
10455 public:
10456 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress,
10457 bool SuppressConversion)
10458 : ContextualImplicitConverter(Suppress, SuppressConversion),
10459 AllowScopedEnumerations(AllowScopedEnumerations) {}
10460
10461 /// Match an integral or (possibly scoped) enumeration type.
10462 bool match(QualType T) override;
10463
10464 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
10465 QualType T) override {
10466 return diagnoseNotInt(S, Loc, T);
10467 }
10468
10469 /// Emits a diagnostic complaining that the expression does not have
10470 /// integral or enumeration type.
10471 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10472 QualType T) = 0;
10473 };
10474
10475 /// Perform a contextual implicit conversion.
10476 ExprResult
10477 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE,
10478 ContextualImplicitConverter &Converter);
10479
10480 /// ReferenceCompareResult - Expresses the result of comparing two
10481 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
10482 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
10483 enum ReferenceCompareResult {
10484 /// Ref_Incompatible - The two types are incompatible, so direct
10485 /// reference binding is not possible.
10486 Ref_Incompatible = 0,
10487 /// Ref_Related - The two types are reference-related, which means
10488 /// that their unqualified forms (T1 and T2) are either the same
10489 /// or T1 is a base class of T2.
10490 Ref_Related,
10491 /// Ref_Compatible - The two types are reference-compatible.
10492 Ref_Compatible
10493 };
10494
10495 // Fake up a scoped enumeration that still contextually converts to bool.
10496 struct ReferenceConversionsScope {
10497 /// The conversions that would be performed on an lvalue of type T2 when
10498 /// binding a reference of type T1 to it, as determined when evaluating
10499 /// whether T1 is reference-compatible with T2.
10500 enum ReferenceConversions {
10501 Qualification = 0x1,
10502 NestedQualification = 0x2,
10503 Function = 0x4,
10504 DerivedToBase = 0x8,
10505 ObjC = 0x10,
10506 ObjCLifetime = 0x20,
10507
10508 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
10509 };
10510 };
10511 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
10512
10513 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
10514 /// determine whether they are reference-compatible,
10515 /// reference-related, or incompatible, for use in C++ initialization by
10516 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
10517 /// type, and the first type (T1) is the pointee type of the reference
10518 /// type being initialized.
10519 ReferenceCompareResult
10520 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
10521 ReferenceConversions *Conv = nullptr);
10522
10523 /// AddOverloadCandidate - Adds the given function to the set of
10524 /// candidate functions, using the given function call arguments. If
10525 /// @p SuppressUserConversions, then don't allow user-defined
10526 /// conversions via constructors or conversion operators.
10527 ///
10528 /// \param PartialOverloading true if we are performing "partial" overloading
10529 /// based on an incomplete set of function arguments. This feature is used by
10530 /// code completion.
10531 void AddOverloadCandidate(
10532 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
10533 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10534 bool PartialOverloading = false, bool AllowExplicit = true,
10535 bool AllowExplicitConversion = false,
10536 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10537 ConversionSequenceList EarlyConversions = {},
10538 OverloadCandidateParamOrder PO = {},
10539 bool AggregateCandidateDeduction = false, bool StrictPackMatch = false);
10540
10541 /// Add all of the function declarations in the given function set to
10542 /// the overload candidate set.
10543 void AddFunctionCandidates(
10544 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10545 OverloadCandidateSet &CandidateSet,
10546 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
10547 bool SuppressUserConversions = false, bool PartialOverloading = false,
10548 bool FirstArgumentIsBase = false);
10549
10550 /// AddMethodCandidate - Adds a named decl (which is some kind of
10551 /// method) as a method candidate to the given overload set.
10552 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
10553 Expr::Classification ObjectClassification,
10554 ArrayRef<Expr *> Args,
10555 OverloadCandidateSet &CandidateSet,
10556 bool SuppressUserConversion = false,
10557 OverloadCandidateParamOrder PO = {});
10558
10559 /// AddMethodCandidate - Adds the given C++ member function to the set
10560 /// of candidate functions, using the given function call arguments
10561 /// and the object argument (@c Object). For example, in a call
10562 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
10563 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
10564 /// allow user-defined conversions via constructors or conversion
10565 /// operators.
10566 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
10567 CXXRecordDecl *ActingContext, QualType ObjectType,
10568 Expr::Classification ObjectClassification,
10569 ArrayRef<Expr *> Args,
10570 OverloadCandidateSet &CandidateSet,
10571 bool SuppressUserConversions = false,
10572 bool PartialOverloading = false,
10573 ConversionSequenceList EarlyConversions = {},
10574 OverloadCandidateParamOrder PO = {},
10575 bool StrictPackMatch = false);
10576
10577 /// Add a C++ member function template as a candidate to the candidate
10578 /// set, using template argument deduction to produce an appropriate member
10579 /// function template specialization.
10580 void AddMethodTemplateCandidate(
10581 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
10582 CXXRecordDecl *ActingContext,
10583 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
10584 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
10585 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10586 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {});
10587
10588 /// Add a C++ function template specialization as a candidate
10589 /// in the candidate set, using template argument deduction to produce
10590 /// an appropriate function template specialization.
10591 void AddTemplateOverloadCandidate(
10592 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10593 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
10594 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
10595 bool PartialOverloading = false, bool AllowExplicit = true,
10596 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
10597 OverloadCandidateParamOrder PO = {},
10598 bool AggregateCandidateDeduction = false);
10599
10600 struct CheckNonDependentConversionsFlag {
10601 /// Do not consider any user-defined conversions when constructing the
10602 /// initializing sequence.
10603 bool SuppressUserConversions;
10604
10605 /// Before constructing the initializing sequence, we check whether the
10606 /// parameter type and argument type contain any user defined conversions.
10607 /// If so, do not initialize them. This effectively bypasses some undesired
10608 /// instantiation before checking constaints, which might otherwise result
10609 /// in non-SFINAE errors e.g. recursive constraints.
10610 bool OnlyInitializeNonUserDefinedConversions;
10611
10612 CheckNonDependentConversionsFlag(
10613 bool SuppressUserConversions,
10614 bool OnlyInitializeNonUserDefinedConversions)
10615 : SuppressUserConversions(SuppressUserConversions),
10616 OnlyInitializeNonUserDefinedConversions(
10617 OnlyInitializeNonUserDefinedConversions) {}
10618 };
10619
10620 /// Check that implicit conversion sequences can be formed for each argument
10621 /// whose corresponding parameter has a non-dependent type, per DR1391's
10622 /// [temp.deduct.call]p10.
10623 bool CheckNonDependentConversions(
10624 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
10625 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
10626 ConversionSequenceList &Conversions,
10627 CheckNonDependentConversionsFlag UserConversionFlag,
10628 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
10629 Expr::Classification ObjectClassification = {},
10630 OverloadCandidateParamOrder PO = {});
10631
10632 /// AddConversionCandidate - Add a C++ conversion function as a
10633 /// candidate in the candidate set (C++ [over.match.conv],
10634 /// C++ [over.match.copy]). From is the expression we're converting from,
10635 /// and ToType is the type that we're eventually trying to convert to
10636 /// (which may or may not be the same type as the type that the
10637 /// conversion function produces).
10638 void AddConversionCandidate(
10639 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
10640 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10641 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10642 bool AllowExplicit, bool AllowResultConversion = true,
10643 bool StrictPackMatch = false);
10644
10645 /// Adds a conversion function template specialization
10646 /// candidate to the overload set, using template argument deduction
10647 /// to deduce the template arguments of the conversion function
10648 /// template from the type that we are converting to (C++
10649 /// [temp.deduct.conv]).
10650 void AddTemplateConversionCandidate(
10651 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
10652 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
10653 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
10654 bool AllowExplicit, bool AllowResultConversion = true);
10655
10656 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
10657 /// converts the given @c Object to a function pointer via the
10658 /// conversion function @c Conversion, and then attempts to call it
10659 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
10660 /// the type of function that we'll eventually be calling.
10661 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
10662 DeclAccessPair FoundDecl,
10663 CXXRecordDecl *ActingContext,
10664 const FunctionProtoType *Proto, Expr *Object,
10665 ArrayRef<Expr *> Args,
10666 OverloadCandidateSet &CandidateSet);
10667
10668 /// Add all of the non-member operator function declarations in the given
10669 /// function set to the overload candidate set.
10670 void AddNonMemberOperatorCandidates(
10671 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
10672 OverloadCandidateSet &CandidateSet,
10673 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
10674
10675 /// Add overload candidates for overloaded operators that are
10676 /// member functions.
10677 ///
10678 /// Add the overloaded operator candidates that are member functions
10679 /// for the operator Op that was used in an operator expression such
10680 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
10681 /// CandidateSet will store the added overload candidates. (C++
10682 /// [over.match.oper]).
10683 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
10684 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10685 OverloadCandidateSet &CandidateSet,
10686 OverloadCandidateParamOrder PO = {});
10687
10688 /// AddBuiltinCandidate - Add a candidate for a built-in
10689 /// operator. ResultTy and ParamTys are the result and parameter types
10690 /// of the built-in candidate, respectively. Args and NumArgs are the
10691 /// arguments being passed to the candidate. IsAssignmentOperator
10692 /// should be true when this built-in candidate is an assignment
10693 /// operator. NumContextualBoolArguments is the number of arguments
10694 /// (at the beginning of the argument list) that will be contextually
10695 /// converted to bool.
10696 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
10697 OverloadCandidateSet &CandidateSet,
10698 bool IsAssignmentOperator = false,
10699 unsigned NumContextualBoolArguments = 0);
10700
10701 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
10702 /// operator overloads to the candidate set (C++ [over.built]), based
10703 /// on the operator @p Op and the arguments given. For example, if the
10704 /// operator is a binary '+', this routine might add "int
10705 /// operator+(int, int)" to cover integer addition.
10706 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10707 SourceLocation OpLoc, ArrayRef<Expr *> Args,
10708 OverloadCandidateSet &CandidateSet);
10709
10710 /// Add function candidates found via argument-dependent lookup
10711 /// to the set of overloading candidates.
10712 ///
10713 /// This routine performs argument-dependent name lookup based on the
10714 /// given function name (which may also be an operator name) and adds
10715 /// all of the overload candidates found by ADL to the overload
10716 /// candidate set (C++ [basic.lookup.argdep]).
10717 void AddArgumentDependentLookupCandidates(
10718 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args,
10719 TemplateArgumentListInfo *ExplicitTemplateArgs,
10720 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false);
10721
10722 /// Check the enable_if expressions on the given function. Returns the first
10723 /// failing attribute, or NULL if they were all successful.
10724 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
10725 ArrayRef<Expr *> Args,
10726 bool MissingImplicitThis = false);
10727
10728 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10729 /// non-ArgDependent DiagnoseIfAttrs.
10730 ///
10731 /// Argument-dependent diagnose_if attributes should be checked each time a
10732 /// function is used as a direct callee of a function call.
10733 ///
10734 /// Returns true if any errors were emitted.
10735 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
10736 const Expr *ThisArg,
10737 ArrayRef<const Expr *> Args,
10738 SourceLocation Loc);
10739
10740 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
10741 /// ArgDependent DiagnoseIfAttrs.
10742 ///
10743 /// Argument-independent diagnose_if attributes should be checked on every use
10744 /// of a function.
10745 ///
10746 /// Returns true if any errors were emitted.
10747 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
10748 SourceLocation Loc);
10749
10750 /// Determine if \p A and \p B are equivalent internal linkage declarations
10751 /// from different modules, and thus an ambiguity error can be downgraded to
10752 /// an extension warning.
10753 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10754 const NamedDecl *B);
10755 void diagnoseEquivalentInternalLinkageDeclarations(
10756 SourceLocation Loc, const NamedDecl *D,
10757 ArrayRef<const NamedDecl *> Equiv);
10758
10759 // Emit as a 'note' the specific overload candidate
10760 void NoteOverloadCandidate(
10761 const NamedDecl *Found, const FunctionDecl *Fn,
10762 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
10763 QualType DestType = QualType(), bool TakingAddress = false);
10764
10765 // Emit as a series of 'note's all template and non-templates identified by
10766 // the expression Expr
10767 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
10768 bool TakingAddress = false);
10769
10770 /// Returns whether the given function's address can be taken or not,
10771 /// optionally emitting a diagnostic if the address can't be taken.
10772 ///
10773 /// Returns false if taking the address of the function is illegal.
10774 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10775 bool Complain = false,
10776 SourceLocation Loc = SourceLocation());
10777
10778 // [PossiblyAFunctionType] --> [Return]
10779 // NonFunctionType --> NonFunctionType
10780 // R (A) --> R(A)
10781 // R (*)(A) --> R (A)
10782 // R (&)(A) --> R (A)
10783 // R (S::*)(A) --> R (A)
10784 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
10785
10786 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10787 /// an overloaded function (C++ [over.over]), where @p From is an
10788 /// expression with overloaded function type and @p ToType is the type
10789 /// we're trying to resolve to. For example:
10790 ///
10791 /// @code
10792 /// int f(double);
10793 /// int f(int);
10794 ///
10795 /// int (*pfd)(double) = f; // selects f(double)
10796 /// @endcode
10797 ///
10798 /// This routine returns the resulting FunctionDecl if it could be
10799 /// resolved, and NULL otherwise. When @p Complain is true, this
10800 /// routine will emit diagnostics if there is an error.
10801 FunctionDecl *
10802 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
10803 bool Complain, DeclAccessPair &Found,
10804 bool *pHadMultipleCandidates = nullptr);
10805
10806 /// Given an expression that refers to an overloaded function, try to
10807 /// resolve that function to a single function that can have its address
10808 /// taken. This will modify `Pair` iff it returns non-null.
10809 ///
10810 /// This routine can only succeed if from all of the candidates in the
10811 /// overload set for SrcExpr that can have their addresses taken, there is one
10812 /// candidate that is more constrained than the rest.
10813 FunctionDecl *
10814 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
10815
10816 /// Given an overloaded function, tries to turn it into a non-overloaded
10817 /// function reference using resolveAddressOfSingleOverloadCandidate. This
10818 /// will perform access checks, diagnose the use of the resultant decl, and,
10819 /// if requested, potentially perform a function-to-pointer decay.
10820 ///
10821 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
10822 /// Otherwise, returns true. This may emit diagnostics and return true.
10823 bool resolveAndFixAddressOfSingleOverloadCandidate(
10824 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
10825
10826 /// Given an expression that refers to an overloaded function, try to
10827 /// resolve that overloaded function expression down to a single function.
10828 ///
10829 /// This routine can only resolve template-ids that refer to a single function
10830 /// template, where that template-id refers to a single template whose
10831 /// template arguments are either provided by the template-id or have
10832 /// defaults, as described in C++0x [temp.arg.explicit]p3.
10833 ///
10834 /// If no template-ids are found, no diagnostics are emitted and NULL is
10835 /// returned.
10836 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(
10837 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr,
10838 TemplateSpecCandidateSet *FailedTSC = nullptr,
10839 bool ForTypeDeduction = false);
10840
10841 // Resolve and fix an overloaded expression that can be resolved
10842 // because it identifies a single function template specialization.
10843 //
10844 // Last three arguments should only be supplied if Complain = true
10845 //
10846 // Return true if it was logically possible to so resolve the
10847 // expression, regardless of whether or not it succeeded. Always
10848 // returns true if 'complain' is set.
10849 bool ResolveAndFixSingleFunctionTemplateSpecialization(
10850 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false,
10851 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(),
10852 QualType DestTypeForComplaining = QualType(),
10853 unsigned DiagIDForComplaining = 0);
10854
10855 /// Add the overload candidates named by callee and/or found by argument
10856 /// dependent lookup to the given overload set.
10857 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10858 ArrayRef<Expr *> Args,
10859 OverloadCandidateSet &CandidateSet,
10860 bool PartialOverloading = false);
10861
10862 /// Add the call candidates from the given set of lookup results to the given
10863 /// overload set. Non-function lookup results are ignored.
10864 void AddOverloadedCallCandidates(
10865 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
10866 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
10867
10868 // An enum used to represent the different possible results of building a
10869 // range-based for loop.
10870 enum ForRangeStatus {
10871 FRS_Success,
10872 FRS_NoViableFunction,
10873 FRS_DiagnosticIssued
10874 };
10875
10876 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
10877 /// given LookupResult is non-empty, it is assumed to describe a member which
10878 /// will be invoked. Otherwise, the function will be found via argument
10879 /// dependent lookup.
10880 /// CallExpr is set to a valid expression and FRS_Success returned on success,
10881 /// otherwise CallExpr is set to ExprError() and some non-success value
10882 /// is returned.
10883 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
10884 SourceLocation RangeLoc,
10885 const DeclarationNameInfo &NameInfo,
10886 LookupResult &MemberLookup,
10887 OverloadCandidateSet *CandidateSet,
10888 Expr *Range, ExprResult *CallExpr);
10889
10890 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10891 /// (which eventually refers to the declaration Func) and the call
10892 /// arguments Args/NumArgs, attempt to resolve the function call down
10893 /// to a specific function. If overload resolution succeeds, returns
10894 /// the call expression produced by overload resolution.
10895 /// Otherwise, emits diagnostics and returns ExprError.
10896 ExprResult BuildOverloadedCallExpr(
10897 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc,
10898 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig,
10899 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false);
10900
10901 /// Constructs and populates an OverloadedCandidateSet from
10902 /// the given function.
10903 /// \returns true when an the ExprResult output parameter has been set.
10904 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
10905 MultiExprArg Args, SourceLocation RParenLoc,
10906 OverloadCandidateSet *CandidateSet,
10907 ExprResult *Result);
10908
10909 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
10910 NestedNameSpecifierLoc NNSLoc,
10911 DeclarationNameInfo DNI,
10912 const UnresolvedSetImpl &Fns,
10913 bool PerformADL = true);
10914
10915 /// Create a unary operation that may resolve to an overloaded
10916 /// operator.
10917 ///
10918 /// \param OpLoc The location of the operator itself (e.g., '*').
10919 ///
10920 /// \param Opc The UnaryOperatorKind that describes this operator.
10921 ///
10922 /// \param Fns The set of non-member functions that will be
10923 /// considered by overload resolution. The caller needs to build this
10924 /// set based on the context using, e.g.,
10925 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10926 /// set should not contain any member functions; those will be added
10927 /// by CreateOverloadedUnaryOp().
10928 ///
10929 /// \param Input The input argument.
10930 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
10931 UnaryOperatorKind Opc,
10932 const UnresolvedSetImpl &Fns, Expr *input,
10933 bool RequiresADL = true);
10934
10935 /// Perform lookup for an overloaded binary operator.
10936 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
10937 OverloadedOperatorKind Op,
10938 const UnresolvedSetImpl &Fns,
10939 ArrayRef<Expr *> Args, bool RequiresADL = true);
10940
10941 /// Create a binary operation that may resolve to an overloaded
10942 /// operator.
10943 ///
10944 /// \param OpLoc The location of the operator itself (e.g., '+').
10945 ///
10946 /// \param Opc The BinaryOperatorKind that describes this operator.
10947 ///
10948 /// \param Fns The set of non-member functions that will be
10949 /// considered by overload resolution. The caller needs to build this
10950 /// set based on the context using, e.g.,
10951 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10952 /// set should not contain any member functions; those will be added
10953 /// by CreateOverloadedBinOp().
10954 ///
10955 /// \param LHS Left-hand argument.
10956 /// \param RHS Right-hand argument.
10957 /// \param PerformADL Whether to consider operator candidates found by ADL.
10958 /// \param AllowRewrittenCandidates Whether to consider candidates found by
10959 /// C++20 operator rewrites.
10960 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
10961 /// the function in question. Such a function is never a candidate in
10962 /// our overload resolution. This also enables synthesizing a three-way
10963 /// comparison from < and == as described in C++20 [class.spaceship]p1.
10964 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
10965 const UnresolvedSetImpl &Fns, Expr *LHS,
10966 Expr *RHS, bool RequiresADL = true,
10967 bool AllowRewrittenCandidates = true,
10968 FunctionDecl *DefaultedFn = nullptr);
10969 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
10970 const UnresolvedSetImpl &Fns,
10971 Expr *LHS, Expr *RHS,
10972 FunctionDecl *DefaultedFn);
10973
10974 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10975 SourceLocation RLoc, Expr *Base,
10976 MultiExprArg Args);
10977
10978 /// BuildCallToMemberFunction - Build a call to a member
10979 /// function. MemExpr is the expression that refers to the member
10980 /// function (and includes the object parameter), Args/NumArgs are the
10981 /// arguments to the function call (not including the object
10982 /// parameter). The caller needs to validate that the member
10983 /// expression refers to a non-static member function or an overloaded
10984 /// member function.
10985 ExprResult BuildCallToMemberFunction(
10986 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args,
10987 SourceLocation RParenLoc, Expr *ExecConfig = nullptr,
10988 bool IsExecConfig = false, bool AllowRecovery = false);
10989
10990 /// BuildCallToObjectOfClassType - Build a call to an object of class
10991 /// type (C++ [over.call.object]), which can end up invoking an
10992 /// overloaded function call operator (@c operator()) or performing a
10993 /// user-defined conversion on the object argument.
10994 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object,
10995 SourceLocation LParenLoc,
10996 MultiExprArg Args,
10997 SourceLocation RParenLoc);
10998
10999 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11000 /// (if one exists), where @c Base is an expression of class type and
11001 /// @c Member is the name of the member we're trying to find.
11002 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
11003 SourceLocation OpLoc,
11004 bool *NoArrowOperatorFound = nullptr);
11005
11006 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
11007 CXXConversionDecl *Method,
11008 bool HadMultipleCandidates);
11009
11010 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call
11011 /// to a literal operator described by the provided lookup results.
11012 ExprResult BuildLiteralOperatorCall(
11013 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args,
11014 SourceLocation LitEndLoc,
11015 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
11016
11017 /// FixOverloadedFunctionReference - E is an expression that refers to
11018 /// a C++ overloaded function (possibly with some parentheses and
11019 /// perhaps a '&' around it). We have resolved the overloaded function
11020 /// to the function declaration Fn, so patch up the expression E to
11021 /// refer (possibly indirectly) to Fn. Returns the new expr.
11022 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl,
11023 FunctionDecl *Fn);
11024 ExprResult FixOverloadedFunctionReference(ExprResult,
11025 DeclAccessPair FoundDecl,
11026 FunctionDecl *Fn);
11027
11028 /// - Returns a selector which best matches given argument list or
11029 /// nullptr if none could be found
11030 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
11031 bool IsInstance,
11032 SmallVectorImpl<ObjCMethodDecl *> &Methods);
11033
11034 ///@}
11035
11036 //
11037 //
11038 // -------------------------------------------------------------------------
11039 //
11040 //
11041
11042 /// \name Statements
11043 /// Implementations are in SemaStmt.cpp
11044 ///@{
11045
11046public:
11047 /// Stack of active SEH __finally scopes. Can be empty.
11048 SmallVector<Scope *, 2> CurrentSEHFinally;
11049
11050 /// Stack of '_Defer' statements that are currently being parsed, as well
11051 /// as the locations of their '_Defer' keywords. Can be empty.
11052 SmallVector<std::pair<Scope *, SourceLocation>, 2> CurrentDefer;
11053
11054 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
11055 StmtResult ActOnExprStmtError();
11056
11057 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
11058 bool HasLeadingEmptyMacro = false);
11059
11060 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc,
11061 SourceLocation EndLoc);
11062 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
11063
11064 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
11065 /// whose result is unused, warn.
11066 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
11067
11068 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
11069 void ActOnAfterCompoundStatementLeadingPragmas();
11070 void ActOnFinishOfCompoundStmt();
11071 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
11072 ArrayRef<Stmt *> Elts, bool isStmtExpr);
11073
11074 sema::CompoundScopeInfo &getCurCompoundScope() const;
11075
11076 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
11077 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
11078 SourceLocation DotDotDotLoc, ExprResult RHS,
11079 SourceLocation ColonLoc);
11080
11081 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
11082 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
11083
11084 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
11085 SourceLocation ColonLoc, Stmt *SubStmt,
11086 Scope *CurScope);
11087 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
11088 SourceLocation ColonLoc, Stmt *SubStmt);
11089
11090 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
11091 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
11092 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
11093 Stmt *SubStmt);
11094
11095 /// Check whether the given statement can have musttail applied to it,
11096 /// issuing a diagnostic and returning false if not. In the success case,
11097 /// the statement is rewritten to remove implicit nodes from the return
11098 /// value.
11099 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11100
11101 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11102 SourceLocation LParenLoc, Stmt *InitStmt,
11103 ConditionResult Cond, SourceLocation RParenLoc,
11104 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11105 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
11106 SourceLocation LParenLoc, Stmt *InitStmt,
11107 ConditionResult Cond, SourceLocation RParenLoc,
11108 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
11109
11110 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
11111
11112 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
11113 SourceLocation LParenLoc, Stmt *InitStmt,
11114 ConditionResult Cond,
11115 SourceLocation RParenLoc);
11116 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
11117 Stmt *Body);
11118
11119 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11120 /// integer not in the range of enum values.
11121 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11122 Expr *SrcExpr);
11123
11124 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
11125 ConditionResult Cond, SourceLocation RParenLoc,
11126 Stmt *Body);
11127 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
11128 SourceLocation WhileLoc, SourceLocation CondLParen,
11129 Expr *Cond, SourceLocation CondRParen);
11130
11131 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
11132 Stmt *First, ConditionResult Second,
11133 FullExprArg Third, SourceLocation RParenLoc,
11134 Stmt *Body);
11135
11136 /// In an Objective C collection iteration statement:
11137 /// for (x in y)
11138 /// x can be an arbitrary l-value expression. Bind it up as a
11139 /// full-expression.
11140 StmtResult ActOnForEachLValueExpr(Expr *E);
11141
11142 enum BuildForRangeKind {
11143 /// Initial building of a for-range statement.
11144 BFRK_Build,
11145 /// Instantiation or recovery rebuild of a for-range statement. Don't
11146 /// attempt any typo-correction.
11147 BFRK_Rebuild,
11148 /// Determining whether a for-range statement could be built. Avoid any
11149 /// unnecessary or irreversible actions.
11150 BFRK_Check
11151 };
11152
11153 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
11154 ///
11155 /// C++11 [stmt.ranged]:
11156 /// A range-based for statement is equivalent to
11157 ///
11158 /// {
11159 /// auto && __range = range-init;
11160 /// for ( auto __begin = begin-expr,
11161 /// __end = end-expr;
11162 /// __begin != __end;
11163 /// ++__begin ) {
11164 /// for-range-declaration = *__begin;
11165 /// statement
11166 /// }
11167 /// }
11168 ///
11169 /// The body of the loop is not available yet, since it cannot be analysed
11170 /// until we have determined the type of the for-range-declaration.
11171 StmtResult ActOnCXXForRangeStmt(
11172 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc,
11173 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection,
11174 SourceLocation RParenLoc, BuildForRangeKind Kind,
11175 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11176
11177 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
11178 StmtResult BuildCXXForRangeStmt(
11179 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
11180 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
11181 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
11182 BuildForRangeKind Kind,
11183 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {});
11184
11185 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
11186 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
11187 /// body cannot be performed until after the type of the range variable is
11188 /// determined.
11189 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
11190
11191 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
11192 LabelDecl *TheDecl);
11193 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
11194 SourceLocation StarLoc, Expr *DestExp);
11195 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope,
11196 LabelDecl *Label, SourceLocation LabelLoc);
11197 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope,
11198 LabelDecl *Label, SourceLocation LabelLoc);
11199
11200 void ActOnStartOfDeferStmt(SourceLocation DeferLoc, Scope *CurScope);
11201 void ActOnDeferStmtError(Scope *CurScope);
11202 StmtResult ActOnEndOfDeferStmt(Stmt *Body, Scope *CurScope);
11203
11204 struct NamedReturnInfo {
11205 const VarDecl *Candidate;
11206
11207 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
11208 Status S;
11209
11210 bool isMoveEligible() const { return S != None; };
11211 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
11212 };
11213 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
11214
11215 /// Determine whether the given expression might be move-eligible or
11216 /// copy-elidable in either a (co_)return statement or throw expression,
11217 /// without considering function return type, if applicable.
11218 ///
11219 /// \param E The expression being returned from the function or block,
11220 /// being thrown, or being co_returned from a coroutine. This expression
11221 /// might be modified by the implementation.
11222 ///
11223 /// \param Mode Overrides detection of current language mode
11224 /// and uses the rules for C++23.
11225 ///
11226 /// \returns An aggregate which contains the Candidate and isMoveEligible
11227 /// and isCopyElidable methods. If Candidate is non-null, it means
11228 /// isMoveEligible() would be true under the most permissive language
11229 /// standard.
11230 NamedReturnInfo getNamedReturnInfo(
11231 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
11232
11233 /// Determine whether the given NRVO candidate variable is move-eligible or
11234 /// copy-elidable, without considering function return type.
11235 ///
11236 /// \param VD The NRVO candidate variable.
11237 ///
11238 /// \returns An aggregate which contains the Candidate and isMoveEligible
11239 /// and isCopyElidable methods. If Candidate is non-null, it means
11240 /// isMoveEligible() would be true under the most permissive language
11241 /// standard.
11242 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
11243
11244 /// Updates given NamedReturnInfo's move-eligible and
11245 /// copy-elidable statuses, considering the function
11246 /// return type criteria as applicable to return statements.
11247 ///
11248 /// \param Info The NamedReturnInfo object to update.
11249 ///
11250 /// \param ReturnType This is the return type of the function.
11251 /// \returns The copy elision candidate, in case the initial return expression
11252 /// was copy elidable, or nullptr otherwise.
11253 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
11254 QualType ReturnType);
11255
11256 /// Perform the initialization of a potentially-movable value, which
11257 /// is the result of return value.
11258 ///
11259 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
11260 /// treat returned lvalues as rvalues in certain cases (to prefer move
11261 /// construction), then falls back to treating them as lvalues if that failed.
11262 ExprResult
11263 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
11264 const NamedReturnInfo &NRInfo, Expr *Value,
11265 bool SupressSimplerImplicitMoves = false);
11266
11267 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
11268
11269 /// Deduce the return type for a function from a returned expression, per
11270 /// C++1y [dcl.spec.auto]p6.
11271 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
11272 SourceLocation ReturnLoc, Expr *RetExpr,
11273 const AutoType *AT);
11274
11275 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11276 Scope *CurScope);
11277 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11278 bool AllowRecovery = false);
11279
11280 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
11281 /// for capturing scopes.
11282 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
11283 NamedReturnInfo &NRInfo,
11284 bool SupressSimplerImplicitMoves);
11285
11286 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
11287 /// and creates a proper catch handler from them.
11288 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
11289 Stmt *HandlerBlock);
11290
11291 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
11292 /// handlers and creates a try statement from them.
11293 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
11294 ArrayRef<Stmt *> Handlers);
11295
11296 void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry);
11297
11298 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
11299 SourceLocation TryLoc, Stmt *TryBlock,
11300 Stmt *Handler);
11301 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
11302 Stmt *Block);
11303 void ActOnStartSEHFinallyBlock();
11304 void ActOnAbortSEHFinallyBlock();
11305 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
11306 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
11307
11308 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
11309 bool IsIfExists,
11310 NestedNameSpecifierLoc QualifierLoc,
11311 DeclarationNameInfo NameInfo,
11312 Stmt *Nested);
11313 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
11314 bool IsIfExists, CXXScopeSpec &SS,
11315 UnqualifiedId &Name, Stmt *Nested);
11316
11317 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11318 CapturedRegionKind Kind, unsigned NumParams);
11319 typedef std::pair<StringRef, QualType> CapturedParamNameType;
11320 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
11321 CapturedRegionKind Kind,
11322 ArrayRef<CapturedParamNameType> Params,
11323 unsigned OpenMPCaptureLevel = 0);
11324 StmtResult ActOnCapturedRegionEnd(Stmt *S);
11325 void ActOnCapturedRegionError();
11326 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
11327 SourceLocation Loc,
11328 unsigned NumParams);
11329
11330private:
11331 /// Check whether the given statement can have musttail applied to it,
11332 /// issuing a diagnostic and returning false if not.
11333 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11334
11335 ///@}
11336
11337 //
11338 //
11339 // -------------------------------------------------------------------------
11340 //
11341 //
11342
11343 /// \name `inline asm` Statement
11344 /// Implementations are in SemaStmtAsm.cpp
11345 ///@{
11346
11347public:
11348 ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel);
11349 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
11350 bool IsVolatile, unsigned NumOutputs,
11351 unsigned NumInputs, IdentifierInfo **Names,
11352 MultiExprArg Constraints, MultiExprArg Exprs,
11353 Expr *AsmString, MultiExprArg Clobbers,
11354 unsigned NumLabels, SourceLocation RParenLoc);
11355
11356 void FillInlineAsmIdentifierInfo(Expr *Res,
11357 llvm::InlineAsmIdentifierInfo &Info);
11358 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
11359 SourceLocation TemplateKWLoc,
11360 UnqualifiedId &Id,
11361 bool IsUnevaluatedContext);
11362 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset,
11363 SourceLocation AsmLoc);
11364 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
11365 SourceLocation AsmLoc);
11366 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
11367 ArrayRef<Token> AsmToks, StringRef AsmString,
11368 unsigned NumOutputs, unsigned NumInputs,
11369 ArrayRef<StringRef> Constraints,
11370 ArrayRef<StringRef> Clobbers,
11371 ArrayRef<Expr *> Exprs, SourceLocation EndLoc);
11372 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
11373 SourceLocation Location, bool AlwaysCreate);
11374
11375 ///@}
11376
11377 //
11378 //
11379 // -------------------------------------------------------------------------
11380 //
11381 //
11382
11383 /// \name Statement Attribute Handling
11384 /// Implementations are in SemaStmtAttr.cpp
11385 ///@{
11386
11387public:
11388 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11389 const AttributeCommonInfo &A);
11390 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt,
11391 const AttributeCommonInfo &A);
11392
11393 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E);
11394 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs);
11395
11396 /// Process the attributes before creating an attributed statement. Returns
11397 /// the semantic attributes that have been processed.
11398 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
11399 SmallVectorImpl<const Attr *> &OutAttrs);
11400
11401 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A,
11402 SourceRange Range);
11403 ExprResult BuildCXXAssumeExpr(Expr *Assumption,
11404 const IdentifierInfo *AttrName,
11405 SourceRange Range);
11406
11407 ///@}
11408
11409 //
11410 //
11411 // -------------------------------------------------------------------------
11412 //
11413 //
11414
11415 /// \name C++ Templates
11416 /// Implementations are in SemaTemplate.cpp
11417 ///@{
11418
11419public:
11420 // Saves the current floating-point pragma stack and clear it in this Sema.
11421 class FpPragmaStackSaveRAII {
11422 public:
11423 FpPragmaStackSaveRAII(Sema &S)
11424 : S(S), SavedStack(std::move(S.FpPragmaStack)) {
11425 S.FpPragmaStack.Stack.clear();
11426 }
11427 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); }
11428 FpPragmaStackSaveRAII(const FpPragmaStackSaveRAII &) = delete;
11429 FpPragmaStackSaveRAII &operator=(const FpPragmaStackSaveRAII &) = delete;
11430
11431 private:
11432 Sema &S;
11433 PragmaStack<FPOptionsOverride> SavedStack;
11434 };
11435
11436 void resetFPOptions(FPOptions FPO) {
11437 CurFPFeatures = FPO;
11438 FpPragmaStack.CurrentValue = FPO.getChangesFrom(Base: FPOptions(LangOpts));
11439 }
11440
11441 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
11442 return llvm::ArrayRef(InventedParameterInfos.begin() +
11443 InventedParameterInfosStart,
11444 InventedParameterInfos.end());
11445 }
11446
11447 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const {
11448 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
11449 FunctionScopes.end());
11450 }
11451
11452 typedef llvm::MapVector<const FunctionDecl *,
11453 std::unique_ptr<LateParsedTemplate>>
11454 LateParsedTemplateMapT;
11455 LateParsedTemplateMapT LateParsedTemplateMap;
11456
11457 /// Determine the number of levels of enclosing template parameters. This is
11458 /// only usable while parsing. Note that this does not include dependent
11459 /// contexts in which no template parameters have yet been declared, such as
11460 /// in a terse function template or generic lambda before the first 'auto' is
11461 /// encountered.
11462 unsigned getTemplateDepth(Scope *S) const;
11463
11464 void FilterAcceptableTemplateNames(LookupResult &R,
11465 bool AllowFunctionTemplates = true,
11466 bool AllowDependent = true);
11467 bool hasAnyAcceptableTemplateNames(LookupResult &R,
11468 bool AllowFunctionTemplates = true,
11469 bool AllowDependent = true,
11470 bool AllowNonTemplateFunctions = false);
11471 /// Try to interpret the lookup result D as a template-name.
11472 ///
11473 /// \param D A declaration found by name lookup.
11474 /// \param AllowFunctionTemplates Whether function templates should be
11475 /// considered valid results.
11476 /// \param AllowDependent Whether unresolved using declarations (that might
11477 /// name templates) should be considered valid results.
11478 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
11479 bool AllowFunctionTemplates = true,
11480 bool AllowDependent = true);
11481
11482 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
11483 /// Whether and why a template name is required in this lookup.
11484 class RequiredTemplateKind {
11485 public:
11486 /// Template name is required if TemplateKWLoc is valid.
11487 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
11488 : TemplateKW(TemplateKWLoc) {}
11489 /// Template name is unconditionally required.
11490 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
11491
11492 SourceLocation getTemplateKeywordLoc() const {
11493 return TemplateKW.value_or(u: SourceLocation());
11494 }
11495 bool hasTemplateKeyword() const {
11496 return getTemplateKeywordLoc().isValid();
11497 }
11498 bool isRequired() const { return TemplateKW != SourceLocation(); }
11499 explicit operator bool() const { return isRequired(); }
11500
11501 private:
11502 std::optional<SourceLocation> TemplateKW;
11503 };
11504
11505 enum class AssumedTemplateKind {
11506 /// This is not assumed to be a template name.
11507 None,
11508 /// This is assumed to be a template name because lookup found nothing.
11509 FoundNothing,
11510 /// This is assumed to be a template name because lookup found one or more
11511 /// functions (but no function templates).
11512 FoundFunctions,
11513 };
11514
11515 bool
11516 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
11517 QualType ObjectType, bool EnteringContext,
11518 RequiredTemplateKind RequiredTemplate = SourceLocation(),
11519 AssumedTemplateKind *ATK = nullptr,
11520 bool AllowTypoCorrection = true);
11521
11522 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS,
11523 bool hasTemplateKeyword,
11524 const UnqualifiedId &Name,
11525 ParsedType ObjectType, bool EnteringContext,
11526 TemplateTy &Template,
11527 bool &MemberOfUnknownSpecialization,
11528 bool Disambiguation = false);
11529
11530 /// Try to resolve an undeclared template name as a type template.
11531 ///
11532 /// Sets II to the identifier corresponding to the template name, and updates
11533 /// Name to a corresponding (typo-corrected) type template name and TNK to
11534 /// the corresponding kind, if possible.
11535 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
11536 TemplateNameKind &TNK,
11537 SourceLocation NameLoc,
11538 IdentifierInfo *&II);
11539
11540 /// Determine whether a particular identifier might be the name in a C++1z
11541 /// deduction-guide declaration.
11542 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
11543 SourceLocation NameLoc, CXXScopeSpec &SS,
11544 ParsedTemplateTy *Template = nullptr);
11545
11546 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
11547 SourceLocation IILoc, Scope *S,
11548 const CXXScopeSpec *SS,
11549 TemplateTy &SuggestedTemplate,
11550 TemplateNameKind &SuggestedKind);
11551
11552 /// Determine whether we would be unable to instantiate this template (because
11553 /// it either has no definition, or is in the process of being instantiated).
11554 bool DiagnoseUninstantiableTemplate(
11555 SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
11556 bool InstantiatedFromMember, const NamedDecl *Pattern,
11557 const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
11558 bool Complain = true, bool *Unreachable = nullptr);
11559
11560 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
11561 /// that the template parameter 'PrevDecl' is being shadowed by a new
11562 /// declaration at location Loc. Returns true to indicate that this is
11563 /// an error, and false otherwise.
11564 ///
11565 /// \param Loc The location of the declaration that shadows a template
11566 /// parameter.
11567 ///
11568 /// \param PrevDecl The template parameter that the declaration shadows.
11569 ///
11570 /// \param SupportedForCompatibility Whether to issue the diagnostic as
11571 /// a warning for compatibility with older versions of clang.
11572 /// Ignored when MSVC compatibility is enabled.
11573 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
11574 bool SupportedForCompatibility = false);
11575
11576 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
11577 /// the parameter D to reference the templated declaration and return a
11578 /// pointer to the template declaration. Otherwise, do nothing to D and return
11579 /// null.
11580 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
11581
11582 /// ActOnTypeParameter - Called when a C++ template type parameter
11583 /// (e.g., "typename T") has been parsed. Typename specifies whether
11584 /// the keyword "typename" was used to declare the type parameter
11585 /// (otherwise, "class" was used), and KeyLoc is the location of the
11586 /// "class" or "typename" keyword. ParamName is the name of the
11587 /// parameter (NULL indicates an unnamed template parameter) and
11588 /// ParamNameLoc is the location of the parameter name (if any).
11589 /// If the type parameter has a default argument, it will be added
11590 /// later via ActOnTypeParameterDefault.
11591 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
11592 SourceLocation EllipsisLoc,
11593 SourceLocation KeyLoc,
11594 IdentifierInfo *ParamName,
11595 SourceLocation ParamNameLoc, unsigned Depth,
11596 unsigned Position, SourceLocation EqualLoc,
11597 ParsedType DefaultArg, bool HasTypeConstraint);
11598
11599 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint);
11600
11601 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
11602 TemplateIdAnnotation *TypeConstraint,
11603 TemplateTypeParmDecl *ConstrainedParameter,
11604 SourceLocation EllipsisLoc);
11605 bool BuildTypeConstraint(const CXXScopeSpec &SS,
11606 TemplateIdAnnotation *TypeConstraint,
11607 TemplateTypeParmDecl *ConstrainedParameter,
11608 SourceLocation EllipsisLoc,
11609 bool AllowUnexpandedPack);
11610
11611 /// Attach a type-constraint to a template parameter.
11612 /// \returns true if an error occurred. This can happen if the
11613 /// immediately-declared constraint could not be formed (e.g. incorrect number
11614 /// of arguments for the named concept).
11615 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
11616 DeclarationNameInfo NameInfo,
11617 TemplateDecl *NamedConcept, NamedDecl *FoundDecl,
11618 const TemplateArgumentListInfo *TemplateArgs,
11619 TemplateTypeParmDecl *ConstrainedParameter,
11620 SourceLocation EllipsisLoc);
11621
11622 bool AttachTypeConstraint(AutoTypeLoc TL,
11623 NonTypeTemplateParmDecl *NewConstrainedParm,
11624 NonTypeTemplateParmDecl *OrigConstrainedParm,
11625 SourceLocation EllipsisLoc);
11626
11627 /// Require the given type to be a structural type, and diagnose if it is not.
11628 ///
11629 /// \return \c true if an error was produced.
11630 bool RequireStructuralType(QualType T, SourceLocation Loc);
11631
11632 /// Check that the type of a non-type template parameter is
11633 /// well-formed.
11634 ///
11635 /// \returns the (possibly-promoted) parameter type if valid;
11636 /// otherwise, produces a diagnostic and returns a NULL type.
11637 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
11638 SourceLocation Loc);
11639 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
11640
11641 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
11642 unsigned Depth, unsigned Position,
11643 SourceLocation EqualLoc,
11644 Expr *DefaultArg);
11645
11646 /// ActOnTemplateTemplateParameter - Called when a C++ template template
11647 /// parameter (e.g. T in template <template \<typename> class T> class array)
11648 /// has been parsed. S is the current scope.
11649 NamedDecl *ActOnTemplateTemplateParameter(
11650 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind,
11651 bool TypenameKeyword, TemplateParameterList *Params,
11652 SourceLocation EllipsisLoc, IdentifierInfo *ParamName,
11653 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position,
11654 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg);
11655
11656 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
11657 /// constrained by RequiresClause, that contains the template parameters in
11658 /// Params.
11659 TemplateParameterList *ActOnTemplateParameterList(
11660 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc,
11661 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params,
11662 SourceLocation RAngleLoc, Expr *RequiresClause);
11663
11664 /// The context in which we are checking a template parameter list.
11665 enum TemplateParamListContext {
11666 // For this context, Class, Variable, TypeAlias, and non-pack Template
11667 // Template Parameters are treated uniformly.
11668 TPC_Other,
11669
11670 TPC_FunctionTemplate,
11671 TPC_ClassTemplateMember,
11672 TPC_FriendClassTemplate,
11673 TPC_FriendFunctionTemplate,
11674 TPC_FriendFunctionTemplateDefinition,
11675 TPC_TemplateTemplateParameterPack,
11676 };
11677
11678 /// Checks the validity of a template parameter list, possibly
11679 /// considering the template parameter list from a previous
11680 /// declaration.
11681 ///
11682 /// If an "old" template parameter list is provided, it must be
11683 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
11684 /// template parameter list.
11685 ///
11686 /// \param NewParams Template parameter list for a new template
11687 /// declaration. This template parameter list will be updated with any
11688 /// default arguments that are carried through from the previous
11689 /// template parameter list.
11690 ///
11691 /// \param OldParams If provided, template parameter list from a
11692 /// previous declaration of the same template. Default template
11693 /// arguments will be merged from the old template parameter list to
11694 /// the new template parameter list.
11695 ///
11696 /// \param TPC Describes the context in which we are checking the given
11697 /// template parameter list.
11698 ///
11699 /// \param SkipBody If we might have already made a prior merged definition
11700 /// of this template visible, the corresponding body-skipping information.
11701 /// Default argument redefinition is not an error when skipping such a body,
11702 /// because (under the ODR) we can assume the default arguments are the same
11703 /// as the prior merged definition.
11704 ///
11705 /// \returns true if an error occurred, false otherwise.
11706 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
11707 TemplateParameterList *OldParams,
11708 TemplateParamListContext TPC,
11709 SkipBodyInfo *SkipBody = nullptr);
11710
11711 /// Match the given template parameter lists to the given scope
11712 /// specifier, returning the template parameter list that applies to the
11713 /// name.
11714 ///
11715 /// \param DeclStartLoc the start of the declaration that has a scope
11716 /// specifier or a template parameter list.
11717 ///
11718 /// \param DeclLoc The location of the declaration itself.
11719 ///
11720 /// \param SS the scope specifier that will be matched to the given template
11721 /// parameter lists. This scope specifier precedes a qualified name that is
11722 /// being declared.
11723 ///
11724 /// \param TemplateId The template-id following the scope specifier, if there
11725 /// is one. Used to check for a missing 'template<>'.
11726 ///
11727 /// \param ParamLists the template parameter lists, from the outermost to the
11728 /// innermost template parameter lists.
11729 ///
11730 /// \param IsFriend Whether to apply the slightly different rules for
11731 /// matching template parameters to scope specifiers in friend
11732 /// declarations.
11733 ///
11734 /// \param IsMemberSpecialization will be set true if the scope specifier
11735 /// denotes a fully-specialized type, and therefore this is a declaration of
11736 /// a member specialization.
11737 ///
11738 /// \returns the template parameter list, if any, that corresponds to the
11739 /// name that is preceded by the scope specifier @p SS. This template
11740 /// parameter list may have template parameters (if we're declaring a
11741 /// template) or may have no template parameters (if we're declaring a
11742 /// template specialization), or may be NULL (if what we're declaring isn't
11743 /// itself a template).
11744 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
11745 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
11746 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
11747 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
11748 bool &IsMemberSpecialization, bool &Invalid,
11749 bool SuppressDiagnostic = false);
11750
11751 /// Returns the template parameter list with all default template argument
11752 /// information.
11753 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD);
11754
11755 DeclResult CheckClassTemplate(
11756 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11757 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
11758 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
11759 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
11760 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
11761 TemplateParameterList **OuterTemplateParamLists,
11762 bool IsMemberSpecialization, SkipBodyInfo *SkipBody = nullptr);
11763
11764 /// Translates template arguments as provided by the parser
11765 /// into template arguments used by semantic analysis.
11766 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
11767 TemplateArgumentListInfo &Out);
11768
11769 /// Convert a parsed type into a parsed template argument. This is mostly
11770 /// trivial, except that we may have parsed a C++17 deduced class template
11771 /// specialization type, in which case we should form a template template
11772 /// argument instead of a type template argument.
11773 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
11774
11775 void NoteAllFoundTemplates(TemplateName Name);
11776
11777 QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
11778 TemplateName Template,
11779 SourceLocation TemplateLoc,
11780 TemplateArgumentListInfo &TemplateArgs,
11781 Scope *Scope, bool ForNestedNameSpecifier);
11782
11783 TypeResult
11784 ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
11785 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
11786 SourceLocation TemplateKWLoc, TemplateTy Template,
11787 const IdentifierInfo *TemplateII,
11788 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11789 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
11790 bool IsCtorOrDtorName = false, bool IsClassName = false,
11791 ImplicitTypenameContext AllowImplicitTypename =
11792 ImplicitTypenameContext::No);
11793
11794 /// Parsed an elaborated-type-specifier that refers to a template-id,
11795 /// such as \c class T::template apply<U>.
11796 TypeResult ActOnTagTemplateIdType(
11797 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc,
11798 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD,
11799 SourceLocation TemplateLoc, SourceLocation LAngleLoc,
11800 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc);
11801
11802 DeclResult ActOnVarTemplateSpecialization(
11803 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
11804 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
11805 StorageClass SC, bool IsPartialSpecialization);
11806
11807 /// Get the specialization of the given variable template corresponding to
11808 /// the specified argument list, or a null-but-valid result if the arguments
11809 /// are dependent.
11810 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
11811 SourceLocation TemplateLoc,
11812 SourceLocation TemplateNameLoc,
11813 const TemplateArgumentListInfo &TemplateArgs,
11814 bool SetWrittenArgs);
11815
11816 /// Form a reference to the specialization of the given variable template
11817 /// corresponding to the specified argument list, or a null-but-valid result
11818 /// if the arguments are dependent.
11819 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
11820 const DeclarationNameInfo &NameInfo,
11821 VarTemplateDecl *Template, NamedDecl *FoundD,
11822 SourceLocation TemplateLoc,
11823 const TemplateArgumentListInfo *TemplateArgs);
11824
11825 ExprResult CheckVarOrConceptTemplateTemplateId(
11826 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
11827 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
11828 const TemplateArgumentListInfo *TemplateArgs);
11829
11830 ExprResult
11831 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11832 const DeclarationNameInfo &ConceptNameInfo,
11833 NamedDecl *FoundDecl, TemplateDecl *NamedConcept,
11834 const TemplateArgumentListInfo *TemplateArgs,
11835 bool DoCheckConstraintSatisfaction = true);
11836
11837 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
11838 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
11839 bool TemplateKeyword, TemplateDecl *TD,
11840 SourceLocation Loc);
11841
11842 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
11843 SourceLocation TemplateKWLoc, LookupResult &R,
11844 bool RequiresADL,
11845 const TemplateArgumentListInfo *TemplateArgs);
11846
11847 // We actually only call this from template instantiation.
11848 ExprResult
11849 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11850 const DeclarationNameInfo &NameInfo,
11851 const TemplateArgumentListInfo *TemplateArgs,
11852 bool IsAddressOfOperand);
11853
11854 UnsignedOrNone getPackIndex(TemplateArgument Pack) const {
11855 return Pack.pack_size() - 1 - *ArgPackSubstIndex;
11856 }
11857
11858 TemplateArgument
11859 getPackSubstitutedTemplateArgument(TemplateArgument Arg) const {
11860 Arg = Arg.pack_elements()[*ArgPackSubstIndex];
11861 if (Arg.isPackExpansion())
11862 Arg = Arg.getPackExpansionPattern();
11863 return Arg;
11864 }
11865
11866 ExprResult
11867 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
11868 QualType ParamType, SourceLocation loc,
11869 TemplateArgument Replacement,
11870 UnsignedOrNone PackIndex, bool Final);
11871
11872 /// Form a template name from a name that is syntactically required to name a
11873 /// template, either due to use of the 'template' keyword or because a name in
11874 /// this syntactic context is assumed to name a template (C++
11875 /// [temp.names]p2-4).
11876 ///
11877 /// This action forms a template name given the name of the template and its
11878 /// optional scope specifier. This is used when the 'template' keyword is used
11879 /// or when the parsing context unambiguously treats a following '<' as
11880 /// introducing a template argument list. Note that this may produce a
11881 /// non-dependent template name if we can perform the lookup now and identify
11882 /// the named template.
11883 ///
11884 /// For example, given "x.MetaFun::template apply", the scope specifier
11885 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
11886 /// of the "template" keyword, and "apply" is the \p Name.
11887 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS,
11888 SourceLocation TemplateKWLoc,
11889 const UnqualifiedId &Name,
11890 ParsedType ObjectType,
11891 bool EnteringContext, TemplateTy &Template,
11892 bool AllowInjectedClassName = false);
11893
11894 DeclResult ActOnClassTemplateSpecialization(
11895 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
11896 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
11897 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
11898 MultiTemplateParamsArg TemplateParameterLists,
11899 SkipBodyInfo *SkipBody = nullptr);
11900
11901 /// Check the non-type template arguments of a class template
11902 /// partial specialization according to C++ [temp.class.spec]p9.
11903 ///
11904 /// \param TemplateNameLoc the location of the template name.
11905 /// \param PrimaryTemplate the template parameters of the primary class
11906 /// template.
11907 /// \param NumExplicit the number of explicitly-specified template arguments.
11908 /// \param TemplateArgs the template arguments of the class template
11909 /// partial specialization.
11910 ///
11911 /// \returns \c true if there was an error, \c false otherwise.
11912 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
11913 TemplateDecl *PrimaryTemplate,
11914 unsigned NumExplicitArgs,
11915 ArrayRef<TemplateArgument> Args);
11916 void CheckTemplatePartialSpecialization(
11917 ClassTemplatePartialSpecializationDecl *Partial);
11918 void CheckTemplatePartialSpecialization(
11919 VarTemplatePartialSpecializationDecl *Partial);
11920
11921 Decl *ActOnTemplateDeclarator(Scope *S,
11922 MultiTemplateParamsArg TemplateParameterLists,
11923 Declarator &D);
11924
11925 /// Diagnose cases where we have an explicit template specialization
11926 /// before/after an explicit template instantiation, producing diagnostics
11927 /// for those cases where they are required and determining whether the
11928 /// new specialization/instantiation will have any effect.
11929 ///
11930 /// \param NewLoc the location of the new explicit specialization or
11931 /// instantiation.
11932 ///
11933 /// \param NewTSK the kind of the new explicit specialization or
11934 /// instantiation.
11935 ///
11936 /// \param PrevDecl the previous declaration of the entity.
11937 ///
11938 /// \param PrevTSK the kind of the old explicit specialization or
11939 /// instantiatin.
11940 ///
11941 /// \param PrevPointOfInstantiation if valid, indicates where the previous
11942 /// declaration was instantiated (either implicitly or explicitly).
11943 ///
11944 /// \param HasNoEffect will be set to true to indicate that the new
11945 /// specialization or instantiation has no effect and should be ignored.
11946 ///
11947 /// \returns true if there was an error that should prevent the introduction
11948 /// of the new declaration into the AST, false otherwise.
11949 bool CheckSpecializationInstantiationRedecl(
11950 SourceLocation NewLoc,
11951 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK,
11952 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK,
11953 SourceLocation PrevPtOfInstantiation, bool &SuppressNew);
11954
11955 /// Perform semantic analysis for the given dependent function
11956 /// template specialization.
11957 ///
11958 /// The only possible way to get a dependent function template specialization
11959 /// is with a friend declaration, like so:
11960 ///
11961 /// \code
11962 /// template \<class T> void foo(T);
11963 /// template \<class T> class A {
11964 /// friend void foo<>(T);
11965 /// };
11966 /// \endcode
11967 ///
11968 /// There really isn't any useful analysis we can do here, so we
11969 /// just store the information.
11970 bool CheckDependentFunctionTemplateSpecialization(
11971 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
11972 LookupResult &Previous);
11973
11974 /// Perform semantic analysis for the given function template
11975 /// specialization.
11976 ///
11977 /// This routine performs all of the semantic analysis required for an
11978 /// explicit function template specialization. On successful completion,
11979 /// the function declaration \p FD will become a function template
11980 /// specialization.
11981 ///
11982 /// \param FD the function declaration, which will be updated to become a
11983 /// function template specialization.
11984 ///
11985 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
11986 /// if any. Note that this may be valid info even when 0 arguments are
11987 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
11988 /// as it anyway contains info on the angle brackets locations.
11989 ///
11990 /// \param Previous the set of declarations that may be specialized by
11991 /// this function specialization.
11992 ///
11993 /// \param QualifiedFriend whether this is a lookup for a qualified friend
11994 /// declaration with no explicit template argument list that might be
11995 /// befriending a function template specialization.
11996 bool CheckFunctionTemplateSpecialization(
11997 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
11998 LookupResult &Previous, bool QualifiedFriend = false);
11999
12000 /// Perform semantic analysis for the given non-template member
12001 /// specialization.
12002 ///
12003 /// This routine performs all of the semantic analysis required for an
12004 /// explicit member function specialization. On successful completion,
12005 /// the function declaration \p FD will become a member function
12006 /// specialization.
12007 ///
12008 /// \param Member the member declaration, which will be updated to become a
12009 /// specialization.
12010 ///
12011 /// \param Previous the set of declarations, one of which may be specialized
12012 /// by this function specialization; the set will be modified to contain the
12013 /// redeclared member.
12014 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12015 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
12016
12017 // Explicit instantiation of a class template specialization
12018 DeclResult ActOnExplicitInstantiation(
12019 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
12020 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
12021 TemplateTy Template, SourceLocation TemplateNameLoc,
12022 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
12023 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
12024
12025 // Explicit instantiation of a member class of a class template.
12026 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12027 SourceLocation TemplateLoc,
12028 unsigned TagSpec, SourceLocation KWLoc,
12029 CXXScopeSpec &SS, IdentifierInfo *Name,
12030 SourceLocation NameLoc,
12031 const ParsedAttributesView &Attr);
12032
12033 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
12034 SourceLocation TemplateLoc,
12035 Declarator &D);
12036
12037 /// If the given template parameter has a default template
12038 /// argument, substitute into that default template argument and
12039 /// return the corresponding template argument.
12040 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(
12041 TemplateDecl *Template, SourceLocation TemplateKWLoc,
12042 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
12043 ArrayRef<TemplateArgument> SugaredConverted,
12044 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg);
12045
12046 /// Returns the top most location responsible for the definition of \p N.
12047 /// If \p N is a a template specialization, this is the location
12048 /// of the top of the instantiation stack.
12049 /// Otherwise, the location of \p N is returned.
12050 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const;
12051
12052 /// Specifies the context in which a particular template
12053 /// argument is being checked.
12054 enum CheckTemplateArgumentKind {
12055 /// The template argument was specified in the code or was
12056 /// instantiated with some deduced template arguments.
12057 CTAK_Specified,
12058
12059 /// The template argument was deduced via template argument
12060 /// deduction.
12061 CTAK_Deduced,
12062
12063 /// The template argument was deduced from an array bound
12064 /// via template argument deduction.
12065 CTAK_DeducedFromArrayBound
12066 };
12067
12068 struct CheckTemplateArgumentInfo {
12069 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
12070 bool MatchingTTP = false)
12071 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
12072 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
12073 CheckTemplateArgumentInfo &
12074 operator=(const CheckTemplateArgumentInfo &) = delete;
12075
12076 /// The checked, converted argument will be added to the
12077 /// end of these vectors.
12078 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
12079
12080 /// The check is being performed in the context of partial ordering.
12081 bool PartialOrdering;
12082
12083 /// If true, assume these template arguments are
12084 /// the injected template arguments for a template template parameter.
12085 /// This will relax the requirement that all its possible uses are valid:
12086 /// TTP checking is loose, and assumes that invalid uses will be diagnosed
12087 /// during instantiation.
12088 bool MatchingTTP;
12089
12090 /// Is set to true when, in the context of TTP matching, a pack parameter
12091 /// matches non-pack arguments.
12092 bool StrictPackMatch = false;
12093 };
12094
12095 /// Check that the given template argument corresponds to the given
12096 /// template parameter.
12097 ///
12098 /// \param Param The template parameter against which the argument will be
12099 /// checked.
12100 ///
12101 /// \param Arg The template argument, which may be updated due to conversions.
12102 ///
12103 /// \param Template The template in which the template argument resides.
12104 ///
12105 /// \param TemplateLoc The location of the template name for the template
12106 /// whose argument list we're matching.
12107 ///
12108 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
12109 /// the template argument list.
12110 ///
12111 /// \param ArgumentPackIndex The index into the argument pack where this
12112 /// argument will be placed. Only valid if the parameter is a parameter pack.
12113 ///
12114 /// \param CTAK Describes how we arrived at this particular template argument:
12115 /// explicitly written, deduced, etc.
12116 ///
12117 /// \returns true on error, false otherwise.
12118 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
12119 NamedDecl *Template, SourceLocation TemplateLoc,
12120 SourceLocation RAngleLoc,
12121 unsigned ArgumentPackIndex,
12122 CheckTemplateArgumentInfo &CTAI,
12123 CheckTemplateArgumentKind CTAK);
12124
12125 /// Check that the given template arguments can be provided to
12126 /// the given template, converting the arguments along the way.
12127 ///
12128 /// \param Template The template to which the template arguments are being
12129 /// provided.
12130 ///
12131 /// \param TemplateLoc The location of the template name in the source.
12132 ///
12133 /// \param TemplateArgs The list of template arguments. If the template is
12134 /// a template template parameter, this function may extend the set of
12135 /// template arguments to also include substituted, defaulted template
12136 /// arguments.
12137 ///
12138 /// \param PartialTemplateArgs True if the list of template arguments is
12139 /// intentionally partial, e.g., because we're checking just the initial
12140 /// set of template arguments.
12141 ///
12142 /// \param Converted Will receive the converted, canonicalized template
12143 /// arguments.
12144 ///
12145 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
12146 /// contain the converted forms of the template arguments as written.
12147 /// Otherwise, \p TemplateArgs will not be modified.
12148 ///
12149 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
12150 /// receive true if the cause for the error is the associated constraints of
12151 /// the template not being satisfied by the template arguments.
12152 ///
12153 /// \param DefaultArgs any default arguments from template specialization
12154 /// deduction.
12155 ///
12156 /// \returns true if an error occurred, false otherwise.
12157 bool CheckTemplateArgumentList(TemplateDecl *Template,
12158 SourceLocation TemplateLoc,
12159 TemplateArgumentListInfo &TemplateArgs,
12160 const DefaultArguments &DefaultArgs,
12161 bool PartialTemplateArgs,
12162 CheckTemplateArgumentInfo &CTAI,
12163 bool UpdateArgsWithConversions = true,
12164 bool *ConstraintsNotSatisfied = nullptr);
12165
12166 bool CheckTemplateArgumentList(
12167 TemplateDecl *Template, TemplateParameterList *Params,
12168 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
12169 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
12170 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions = true,
12171 bool *ConstraintsNotSatisfied = nullptr);
12172
12173 bool CheckTemplateTypeArgument(
12174 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
12175 SmallVectorImpl<TemplateArgument> &SugaredConverted,
12176 SmallVectorImpl<TemplateArgument> &CanonicalConverted);
12177
12178 /// Check a template argument against its corresponding
12179 /// template type parameter.
12180 ///
12181 /// This routine implements the semantics of C++ [temp.arg.type]. It
12182 /// returns true if an error occurred, and false otherwise.
12183 bool CheckTemplateArgument(TypeSourceInfo *Arg);
12184
12185 /// Check a template argument against its corresponding
12186 /// non-type template parameter.
12187 ///
12188 /// This routine implements the semantics of C++ [temp.arg.nontype].
12189 /// If an error occurred, it returns ExprError(); otherwise, it
12190 /// returns the converted template argument. \p ParamType is the
12191 /// type of the non-type template parameter after it has been instantiated.
12192 ExprResult CheckTemplateArgument(NamedDecl *Param,
12193 QualType InstantiatedParamType, Expr *Arg,
12194 TemplateArgument &SugaredConverted,
12195 TemplateArgument &CanonicalConverted,
12196 bool StrictCheck,
12197 CheckTemplateArgumentKind CTAK);
12198
12199 /// Check a template argument against its corresponding
12200 /// template template parameter.
12201 ///
12202 /// This routine implements the semantics of C++ [temp.arg.template].
12203 /// It returns true if an error occurred, and false otherwise.
12204 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
12205 TemplateParameterList *Params,
12206 TemplateArgumentLoc &Arg,
12207 bool PartialOrdering,
12208 bool *StrictPackMatch);
12209
12210 bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template,
12211 TemplateTemplateParmDecl *Param,
12212 const TemplateArgumentLoc &Arg);
12213
12214 void NoteTemplateLocation(const NamedDecl &Decl,
12215 std::optional<SourceRange> ParamRange = {});
12216 void NoteTemplateParameterLocation(const NamedDecl &Decl);
12217
12218 /// Given a non-type template argument that refers to a
12219 /// declaration and the type of its corresponding non-type template
12220 /// parameter, produce an expression that properly refers to that
12221 /// declaration.
12222 /// FIXME: This is used in some contexts where the resulting expression
12223 /// doesn't need to live too long. It would be useful if this function
12224 /// could return a temporary expression.
12225 ExprResult BuildExpressionFromDeclTemplateArgument(
12226 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc);
12227 ExprResult
12228 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
12229 SourceLocation Loc);
12230
12231 /// Enumeration describing how template parameter lists are compared
12232 /// for equality.
12233 enum TemplateParameterListEqualKind {
12234 /// We are matching the template parameter lists of two templates
12235 /// that might be redeclarations.
12236 ///
12237 /// \code
12238 /// template<typename T> struct X;
12239 /// template<typename T> struct X;
12240 /// \endcode
12241 TPL_TemplateMatch,
12242
12243 /// We are matching the template parameter lists of two template
12244 /// template parameters as part of matching the template parameter lists
12245 /// of two templates that might be redeclarations.
12246 ///
12247 /// \code
12248 /// template<template<int I> class TT> struct X;
12249 /// template<template<int Value> class Other> struct X;
12250 /// \endcode
12251 TPL_TemplateTemplateParmMatch,
12252
12253 /// We are determining whether the template-parameters are equivalent
12254 /// according to C++ [temp.over.link]/6. This comparison does not consider
12255 /// constraints.
12256 ///
12257 /// \code
12258 /// template<C1 T> void f(T);
12259 /// template<C2 T> void f(T);
12260 /// \endcode
12261 TPL_TemplateParamsEquivalent,
12262 };
12263
12264 // A struct to represent the 'new' declaration, which is either itself just
12265 // the named decl, or the important information we need about it in order to
12266 // do constraint comparisons.
12267 class TemplateCompareNewDeclInfo {
12268 const NamedDecl *ND = nullptr;
12269 const DeclContext *DC = nullptr;
12270 const DeclContext *LexicalDC = nullptr;
12271 SourceLocation Loc;
12272
12273 public:
12274 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {}
12275 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx,
12276 const DeclContext *LexicalDeclCtx,
12277 SourceLocation Loc)
12278
12279 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) {
12280 assert(DC && LexicalDC &&
12281 "Constructor only for cases where we have the information to put "
12282 "in here");
12283 }
12284
12285 // If this was constructed with no information, we cannot do substitution
12286 // for constraint comparison, so make sure we can check that.
12287 bool isInvalid() const { return !ND && !DC; }
12288
12289 const NamedDecl *getDecl() const { return ND; }
12290
12291 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; }
12292
12293 const DeclContext *getLexicalDeclContext() const {
12294 return ND ? ND->getLexicalDeclContext() : LexicalDC;
12295 }
12296
12297 const DeclContext *getDeclContext() const {
12298 return ND ? ND->getDeclContext() : DC;
12299 }
12300
12301 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; }
12302 };
12303
12304 /// Determine whether the given template parameter lists are
12305 /// equivalent.
12306 ///
12307 /// \param New The new template parameter list, typically written in the
12308 /// source code as part of a new template declaration.
12309 ///
12310 /// \param Old The old template parameter list, typically found via
12311 /// name lookup of the template declared with this template parameter
12312 /// list.
12313 ///
12314 /// \param Complain If true, this routine will produce a diagnostic if
12315 /// the template parameter lists are not equivalent.
12316 ///
12317 /// \param Kind describes how we are to match the template parameter lists.
12318 ///
12319 /// \param TemplateArgLoc If this source location is valid, then we
12320 /// are actually checking the template parameter list of a template
12321 /// argument (New) against the template parameter list of its
12322 /// corresponding template template parameter (Old). We produce
12323 /// slightly different diagnostics in this scenario.
12324 ///
12325 /// \returns True if the template parameter lists are equal, false
12326 /// otherwise.
12327 bool TemplateParameterListsAreEqual(
12328 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
12329 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
12330 TemplateParameterListEqualKind Kind,
12331 SourceLocation TemplateArgLoc = SourceLocation());
12332
12333 bool TemplateParameterListsAreEqual(
12334 TemplateParameterList *New, TemplateParameterList *Old, bool Complain,
12335 TemplateParameterListEqualKind Kind,
12336 SourceLocation TemplateArgLoc = SourceLocation()) {
12337 return TemplateParameterListsAreEqual(NewInstFrom: nullptr, New, OldInstFrom: nullptr, Old, Complain,
12338 Kind, TemplateArgLoc);
12339 }
12340
12341 /// Check whether a template can be declared within this scope.
12342 ///
12343 /// If the template declaration is valid in this scope, returns
12344 /// false. Otherwise, issues a diagnostic and returns true.
12345 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
12346
12347 /// Called when the parser has parsed a C++ typename
12348 /// specifier, e.g., "typename T::type".
12349 ///
12350 /// \param S The scope in which this typename type occurs.
12351 /// \param TypenameLoc the location of the 'typename' keyword
12352 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12353 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
12354 /// \param IdLoc the location of the identifier.
12355 /// \param IsImplicitTypename context where T::type refers to a type.
12356 TypeResult ActOnTypenameType(
12357 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS,
12358 const IdentifierInfo &II, SourceLocation IdLoc,
12359 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No);
12360
12361 /// Called when the parser has parsed a C++ typename
12362 /// specifier that ends in a template-id, e.g.,
12363 /// "typename MetaFun::template apply<T1, T2>".
12364 ///
12365 /// \param S The scope in which this typename type occurs.
12366 /// \param TypenameLoc the location of the 'typename' keyword
12367 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
12368 /// \param TemplateLoc the location of the 'template' keyword, if any.
12369 /// \param TemplateName The template name.
12370 /// \param TemplateII The identifier used to name the template.
12371 /// \param TemplateIILoc The location of the template name.
12372 /// \param LAngleLoc The location of the opening angle bracket ('<').
12373 /// \param TemplateArgs The template arguments.
12374 /// \param RAngleLoc The location of the closing angle bracket ('>').
12375 TypeResult
12376 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
12377 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
12378 TemplateTy TemplateName, const IdentifierInfo *TemplateII,
12379 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
12380 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc);
12381
12382 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12383 SourceLocation KeywordLoc,
12384 NestedNameSpecifierLoc QualifierLoc,
12385 const IdentifierInfo &II, SourceLocation IILoc,
12386 TypeSourceInfo **TSI, bool DeducedTSTContext);
12387
12388 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
12389 SourceLocation KeywordLoc,
12390 NestedNameSpecifierLoc QualifierLoc,
12391 const IdentifierInfo &II, SourceLocation IILoc,
12392 bool DeducedTSTContext = true);
12393
12394 /// Rebuilds a type within the context of the current instantiation.
12395 ///
12396 /// The type \p T is part of the type of an out-of-line member definition of
12397 /// a class template (or class template partial specialization) that was
12398 /// parsed and constructed before we entered the scope of the class template
12399 /// (or partial specialization thereof). This routine will rebuild that type
12400 /// now that we have entered the declarator's scope, which may produce
12401 /// different canonical types, e.g.,
12402 ///
12403 /// \code
12404 /// template<typename T>
12405 /// struct X {
12406 /// typedef T* pointer;
12407 /// pointer data();
12408 /// };
12409 ///
12410 /// template<typename T>
12411 /// typename X<T>::pointer X<T>::data() { ... }
12412 /// \endcode
12413 ///
12414 /// Here, the type "typename X<T>::pointer" will be created as a
12415 /// DependentNameType, since we do not know that we can look into X<T> when we
12416 /// parsed the type. This function will rebuild the type, performing the
12417 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose
12418 /// canonical type is the same as the canonical type of T*, allowing the
12419 /// return types of the out-of-line definition and the declaration to match.
12420 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
12421 SourceLocation Loc,
12422 DeclarationName Name);
12423 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
12424
12425 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
12426
12427 /// Rebuild the template parameters now that we know we're in a current
12428 /// instantiation.
12429 bool
12430 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params);
12431
12432 /// Produces a formatted string that describes the binding of
12433 /// template parameters to template arguments.
12434 std::string
12435 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12436 const TemplateArgumentList &Args);
12437
12438 std::string
12439 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12440 const TemplateArgument *Args,
12441 unsigned NumArgs);
12442
12443 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
12444 SourceLocation Less,
12445 SourceLocation Greater);
12446
12447 /// ActOnDependentIdExpression - Handle a dependent id-expression that
12448 /// was just parsed. This is only possible with an explicit scope
12449 /// specifier naming a dependent type.
12450 ExprResult ActOnDependentIdExpression(
12451 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
12452 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand,
12453 const TemplateArgumentListInfo *TemplateArgs);
12454
12455 ExprResult
12456 BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
12457 SourceLocation TemplateKWLoc,
12458 const DeclarationNameInfo &NameInfo,
12459 const TemplateArgumentListInfo *TemplateArgs);
12460
12461 // Calculates whether the expression Constraint depends on an enclosing
12462 // template, for the purposes of [temp.friend] p9.
12463 // TemplateDepth is the 'depth' of the friend function, which is used to
12464 // compare whether a declaration reference is referring to a containing
12465 // template, or just the current friend function. A 'lower' TemplateDepth in
12466 // the AST refers to a 'containing' template. As the constraint is
12467 // uninstantiated, this is relative to the 'top' of the TU.
12468 bool
12469 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
12470 unsigned TemplateDepth,
12471 const Expr *Constraint);
12472
12473 /// Find the failed Boolean condition within a given Boolean
12474 /// constant expression, and describe it with a string.
12475 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
12476
12477 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
12478
12479 ConceptDecl *ActOnStartConceptDefinition(
12480 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
12481 const IdentifierInfo *Name, SourceLocation NameLoc);
12482
12483 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
12484 Expr *ConstraintExpr,
12485 const ParsedAttributesView &Attrs);
12486
12487 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous,
12488 bool &AddToScope);
12489 bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc);
12490
12491 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12492 const CXXScopeSpec &SS,
12493 const IdentifierInfo *Name,
12494 SourceLocation TagLoc, SourceLocation NameLoc);
12495
12496 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12497 CachedTokens &Toks);
12498 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
12499 bool IsInsideALocalClassWithinATemplateFunction();
12500
12501 /// We've found a use of a templated declaration that would trigger an
12502 /// implicit instantiation. Check that any relevant explicit specializations
12503 /// and partial specializations are visible/reachable, and diagnose if not.
12504 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
12505 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
12506
12507 ///@}
12508
12509 //
12510 //
12511 // -------------------------------------------------------------------------
12512 //
12513 //
12514
12515 /// \name C++ Template Argument Deduction
12516 /// Implementations are in SemaTemplateDeduction.cpp
12517 ///@{
12518
12519public:
12520 class SFINAETrap;
12521
12522 struct SFINAEContextBase {
12523 SFINAEContextBase(Sema &S, SFINAETrap *Cur)
12524 : S(S), Prev(std::exchange(obj&: S.CurrentSFINAEContext, new_val&: Cur)) {}
12525
12526 protected:
12527 Sema &S;
12528 ~SFINAEContextBase() { S.CurrentSFINAEContext = Prev; }
12529 SFINAEContextBase(const SFINAEContextBase &) = delete;
12530 SFINAEContextBase &operator=(const SFINAEContextBase &) = delete;
12531
12532 private:
12533 SFINAETrap *Prev;
12534 };
12535
12536 struct NonSFINAEContext : SFINAEContextBase {
12537 NonSFINAEContext(Sema &S) : SFINAEContextBase(S, nullptr) {}
12538 };
12539
12540 /// RAII class used to determine whether SFINAE has
12541 /// trapped any errors that occur during template argument
12542 /// deduction.
12543 class SFINAETrap : SFINAEContextBase {
12544 bool HasErrorOcurred = false;
12545 bool WithAccessChecking = false;
12546 bool PrevLastDiagnosticIgnored =
12547 S.getDiagnostics().isLastDiagnosticIgnored();
12548 sema::TemplateDeductionInfo *DeductionInfo = nullptr;
12549
12550 SFINAETrap(Sema &S, sema::TemplateDeductionInfo *Info,
12551 bool WithAccessChecking)
12552 : SFINAEContextBase(S, this), WithAccessChecking(WithAccessChecking),
12553 DeductionInfo(Info) {}
12554
12555 public:
12556 /// \param WithAccessChecking If true, discard all diagnostics (from the
12557 /// immediate context) instead of adding them to the currently active
12558 /// \ref TemplateDeductionInfo.
12559 explicit SFINAETrap(Sema &S, bool WithAccessChecking = false)
12560 : SFINAETrap(S, /*Info=*/nullptr, WithAccessChecking) {}
12561
12562 SFINAETrap(Sema &S, sema::TemplateDeductionInfo &Info)
12563 : SFINAETrap(S, &Info, /*WithAccessChecking=*/false) {}
12564
12565 ~SFINAETrap() {
12566 S.getDiagnostics().setLastDiagnosticIgnored(PrevLastDiagnosticIgnored);
12567 }
12568
12569 SFINAETrap(const SFINAETrap &) = delete;
12570 SFINAETrap &operator=(const SFINAETrap &) = delete;
12571
12572 sema::TemplateDeductionInfo *getDeductionInfo() const {
12573 return DeductionInfo;
12574 }
12575
12576 /// Determine whether any SFINAE errors have been trapped.
12577 bool hasErrorOccurred() const { return HasErrorOcurred; }
12578 void setErrorOccurred() { HasErrorOcurred = true; }
12579
12580 bool withAccessChecking() const { return WithAccessChecking; }
12581 };
12582
12583 /// RAII class used to indicate that we are performing provisional
12584 /// semantic analysis to determine the validity of a construct, so
12585 /// typo-correction and diagnostics in the immediate context (not within
12586 /// implicitly-instantiated templates) should be suppressed.
12587 class TentativeAnalysisScope {
12588 Sema &SemaRef;
12589 // FIXME: Using a SFINAETrap for this is a hack.
12590 SFINAETrap Trap;
12591 bool PrevDisableTypoCorrection;
12592
12593 public:
12594 explicit TentativeAnalysisScope(Sema &SemaRef)
12595 : SemaRef(SemaRef), Trap(SemaRef, /*ForValidityCheck=*/true),
12596 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
12597 SemaRef.DisableTypoCorrection = true;
12598 }
12599 ~TentativeAnalysisScope() {
12600 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
12601 }
12602
12603 TentativeAnalysisScope(const TentativeAnalysisScope &) = delete;
12604 TentativeAnalysisScope &operator=(const TentativeAnalysisScope &) = delete;
12605 };
12606
12607 /// For each declaration that involved template argument deduction, the
12608 /// set of diagnostics that were suppressed during that template argument
12609 /// deduction.
12610 ///
12611 /// FIXME: Serialize this structure to the AST file.
12612 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>>
12613 SuppressedDiagnosticsMap;
12614 SuppressedDiagnosticsMap SuppressedDiagnostics;
12615
12616 /// Compare types for equality with respect to possibly compatible
12617 /// function types (noreturn adjustment, implicit calling conventions). If any
12618 /// of parameter and argument is not a function, just perform type comparison.
12619 ///
12620 /// \param P the template parameter type.
12621 ///
12622 /// \param A the argument type.
12623 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
12624
12625 /// Allocate a TemplateArgumentLoc where all locations have
12626 /// been initialized to the given location.
12627 ///
12628 /// \param Arg The template argument we are producing template argument
12629 /// location information for.
12630 ///
12631 /// \param NTTPType For a declaration template argument, the type of
12632 /// the non-type template parameter that corresponds to this template
12633 /// argument. Can be null if no type sugar is available to add to the
12634 /// type from the template argument.
12635 ///
12636 /// \param Loc The source location to use for the resulting template
12637 /// argument.
12638 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
12639 QualType NTTPType,
12640 SourceLocation Loc);
12641
12642 /// Get a template argument mapping the given template parameter to itself,
12643 /// e.g. for X in \c template<int X>, this would return an expression template
12644 /// argument referencing X.
12645 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
12646 SourceLocation Location);
12647
12648 /// Adjust the type \p ArgFunctionType to match the calling convention,
12649 /// noreturn, and optionally the exception specification of \p FunctionType.
12650 /// Deduction often wants to ignore these properties when matching function
12651 /// types.
12652 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
12653 bool AdjustExceptionSpec = false);
12654
12655 TemplateDeductionResult
12656 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
12657 ArrayRef<TemplateArgument> TemplateArgs,
12658 sema::TemplateDeductionInfo &Info);
12659
12660 TemplateDeductionResult
12661 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
12662 ArrayRef<TemplateArgument> TemplateArgs,
12663 sema::TemplateDeductionInfo &Info);
12664
12665 /// Deduce the template arguments of the given template from \p FromType.
12666 /// Used to implement the IsDeducible constraint for alias CTAD per C++
12667 /// [over.match.class.deduct]p4.
12668 ///
12669 /// It only supports class or type alias templates.
12670 TemplateDeductionResult
12671 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
12672 sema::TemplateDeductionInfo &Info);
12673
12674 TemplateDeductionResult DeduceTemplateArguments(
12675 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
12676 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
12677 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12678 bool NumberOfArgumentsMustMatch);
12679
12680 /// Substitute the explicitly-provided template arguments into the
12681 /// given function template according to C++ [temp.arg.explicit].
12682 ///
12683 /// \param FunctionTemplate the function template into which the explicit
12684 /// template arguments will be substituted.
12685 ///
12686 /// \param ExplicitTemplateArgs the explicitly-specified template
12687 /// arguments.
12688 ///
12689 /// \param Deduced the deduced template arguments, which will be populated
12690 /// with the converted and checked explicit template arguments.
12691 ///
12692 /// \param ParamTypes will be populated with the instantiated function
12693 /// parameters.
12694 ///
12695 /// \param FunctionType if non-NULL, the result type of the function template
12696 /// will also be instantiated and the pointed-to value will be updated with
12697 /// the instantiated function type.
12698 ///
12699 /// \param Info if substitution fails for any reason, this object will be
12700 /// populated with more information about the failure.
12701 ///
12702 /// \returns TemplateDeductionResult::Success if substitution was successful,
12703 /// or some failure condition.
12704 TemplateDeductionResult SubstituteExplicitTemplateArguments(
12705 FunctionTemplateDecl *FunctionTemplate,
12706 TemplateArgumentListInfo &ExplicitTemplateArgs,
12707 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12708 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
12709 sema::TemplateDeductionInfo &Info);
12710
12711 /// brief A function argument from which we performed template argument
12712 // deduction for a call.
12713 struct OriginalCallArg {
12714 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
12715 unsigned ArgIdx, QualType OriginalArgType)
12716 : OriginalParamType(OriginalParamType),
12717 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
12718 OriginalArgType(OriginalArgType) {}
12719
12720 QualType OriginalParamType;
12721 bool DecomposedParam;
12722 unsigned ArgIdx;
12723 QualType OriginalArgType;
12724 };
12725
12726 /// Finish template argument deduction for a function template,
12727 /// checking the deduced template arguments for completeness and forming
12728 /// the function template specialization.
12729 ///
12730 /// \param OriginalCallArgs If non-NULL, the original call arguments against
12731 /// which the deduced argument types should be compared.
12732 /// \param CheckNonDependent Callback before substituting into the declaration
12733 /// with the deduced template arguments.
12734 /// \param OnlyInitializeNonUserDefinedConversions is used as a workaround for
12735 /// some breakages introduced by CWG2369, where non-user-defined conversions
12736 /// are checked first before the constraints.
12737 TemplateDeductionResult FinishTemplateArgumentDeduction(
12738 FunctionTemplateDecl *FunctionTemplate,
12739 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12740 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
12741 sema::TemplateDeductionInfo &Info,
12742 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
12743 bool PartialOverloading, bool PartialOrdering,
12744 bool ForOverloadSetAddressResolution,
12745 llvm::function_ref<bool(bool)> CheckNonDependent =
12746 [](bool /*OnlyInitializeNonUserDefinedConversions*/) {
12747 return false;
12748 });
12749
12750 /// Perform template argument deduction from a function call
12751 /// (C++ [temp.deduct.call]).
12752 ///
12753 /// \param FunctionTemplate the function template for which we are performing
12754 /// template argument deduction.
12755 ///
12756 /// \param ExplicitTemplateArgs the explicit template arguments provided
12757 /// for this call.
12758 ///
12759 /// \param Args the function call arguments
12760 ///
12761 /// \param Specialization if template argument deduction was successful,
12762 /// this will be set to the function template specialization produced by
12763 /// template argument deduction.
12764 ///
12765 /// \param Info the argument will be updated to provide additional information
12766 /// about template argument deduction.
12767 ///
12768 /// \param CheckNonDependent A callback to invoke to check conversions for
12769 /// non-dependent parameters, between deduction and substitution, per DR1391.
12770 /// If this returns true, substitution will be skipped and we return
12771 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is
12772 /// passed the parameter types (after substituting explicit template
12773 /// arguments).
12774 ///
12775 /// \returns the result of template argument deduction.
12776 TemplateDeductionResult DeduceTemplateArguments(
12777 FunctionTemplateDecl *FunctionTemplate,
12778 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
12779 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12780 bool PartialOverloading, bool AggregateDeductionCandidate,
12781 bool PartialOrdering, QualType ObjectType,
12782 Expr::Classification ObjectClassification,
12783 bool ForOverloadSetAddressResolution,
12784 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent);
12785
12786 /// Deduce template arguments when taking the address of a function
12787 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
12788 /// a template.
12789 ///
12790 /// \param FunctionTemplate the function template for which we are performing
12791 /// template argument deduction.
12792 ///
12793 /// \param ExplicitTemplateArgs the explicitly-specified template
12794 /// arguments.
12795 ///
12796 /// \param ArgFunctionType the function type that will be used as the
12797 /// "argument" type (A) when performing template argument deduction from the
12798 /// function template's function type. This type may be NULL, if there is no
12799 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
12800 ///
12801 /// \param Specialization if template argument deduction was successful,
12802 /// this will be set to the function template specialization produced by
12803 /// template argument deduction.
12804 ///
12805 /// \param Info the argument will be updated to provide additional information
12806 /// about template argument deduction.
12807 ///
12808 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12809 /// the address of a function template per [temp.deduct.funcaddr] and
12810 /// [over.over]. If \c false, we are looking up a function template
12811 /// specialization based on its signature, per [temp.deduct.decl].
12812 ///
12813 /// \returns the result of template argument deduction.
12814 TemplateDeductionResult DeduceTemplateArguments(
12815 FunctionTemplateDecl *FunctionTemplate,
12816 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
12817 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
12818 bool IsAddressOfFunction = false);
12819
12820 /// Deduce template arguments for a templated conversion
12821 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
12822 /// conversion function template specialization.
12823 TemplateDeductionResult DeduceTemplateArguments(
12824 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType,
12825 Expr::Classification ObjectClassification, QualType ToType,
12826 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info);
12827
12828 /// Deduce template arguments for a function template when there is
12829 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
12830 ///
12831 /// \param FunctionTemplate the function template for which we are performing
12832 /// template argument deduction.
12833 ///
12834 /// \param ExplicitTemplateArgs the explicitly-specified template
12835 /// arguments.
12836 ///
12837 /// \param Specialization if template argument deduction was successful,
12838 /// this will be set to the function template specialization produced by
12839 /// template argument deduction.
12840 ///
12841 /// \param Info the argument will be updated to provide additional information
12842 /// about template argument deduction.
12843 ///
12844 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
12845 /// the address of a function template in a context where we do not have a
12846 /// target type, per [over.over]. If \c false, we are looking up a function
12847 /// template specialization based on its signature, which only happens when
12848 /// deducing a function parameter type from an argument that is a template-id
12849 /// naming a function template specialization.
12850 ///
12851 /// \returns the result of template argument deduction.
12852 TemplateDeductionResult
12853 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
12854 TemplateArgumentListInfo *ExplicitTemplateArgs,
12855 FunctionDecl *&Specialization,
12856 sema::TemplateDeductionInfo &Info,
12857 bool IsAddressOfFunction = false);
12858
12859 /// Substitute Replacement for \p auto in \p TypeWithAuto
12860 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
12861 /// Substitute Replacement for auto in TypeWithAuto
12862 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12863 QualType Replacement);
12864
12865 // Substitute auto in TypeWithAuto for a Dependent auto type
12866 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
12867
12868 // Substitute auto in TypeWithAuto for a Dependent auto type
12869 TypeSourceInfo *
12870 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
12871
12872 /// Completely replace the \c auto in \p TypeWithAuto by
12873 /// \p Replacement. This does not retain any \c auto type sugar.
12874 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
12875 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
12876 QualType Replacement);
12877
12878 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
12879 ///
12880 /// Note that this is done even if the initializer is dependent. (This is
12881 /// necessary to support partial ordering of templates using 'auto'.)
12882 /// A dependent type will be produced when deducing from a dependent type.
12883 ///
12884 /// \param Type the type pattern using the auto type-specifier.
12885 /// \param Init the initializer for the variable whose type is to be deduced.
12886 /// \param Result if type deduction was successful, this will be set to the
12887 /// deduced type.
12888 /// \param Info the argument will be updated to provide additional information
12889 /// about template argument deduction.
12890 /// \param DependentDeduction Set if we should permit deduction in
12891 /// dependent cases. This is necessary for template partial ordering
12892 /// with 'auto' template parameters. The template parameter depth to be
12893 /// used should be specified in the 'Info' parameter.
12894 /// \param IgnoreConstraints Set if we should not fail if the deduced type
12895 /// does not satisfy the type-constraint in the auto
12896 /// type.
12897 TemplateDeductionResult
12898 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result,
12899 sema::TemplateDeductionInfo &Info,
12900 bool DependentDeduction = false,
12901 bool IgnoreConstraints = false,
12902 TemplateSpecCandidateSet *FailedTSC = nullptr);
12903 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init);
12904 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
12905 bool Diagnose = true);
12906
12907 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
12908 SourceLocation Loc);
12909
12910 /// Returns the more specialized class template partial specialization
12911 /// according to the rules of partial ordering of class template partial
12912 /// specializations (C++ [temp.class.order]).
12913 ///
12914 /// \param PS1 the first class template partial specialization
12915 ///
12916 /// \param PS2 the second class template partial specialization
12917 ///
12918 /// \returns the more specialized class template partial specialization. If
12919 /// neither partial specialization is more specialized, returns NULL.
12920 ClassTemplatePartialSpecializationDecl *
12921 getMoreSpecializedPartialSpecialization(
12922 ClassTemplatePartialSpecializationDecl *PS1,
12923 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12924
12925 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
12926 sema::TemplateDeductionInfo &Info);
12927
12928 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
12929 VarTemplatePartialSpecializationDecl *PS1,
12930 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
12931
12932 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
12933 sema::TemplateDeductionInfo &Info);
12934
12935 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
12936 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
12937 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
12938 bool PartialOrdering, bool *StrictPackMatch);
12939
12940 /// Mark which template parameters are used in a given expression.
12941 ///
12942 /// \param E the expression from which template parameters will be deduced.
12943 ///
12944 /// \param Used a bit vector whose elements will be set to \c true
12945 /// to indicate when the corresponding template parameter will be
12946 /// deduced.
12947 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
12948 unsigned Depth, llvm::SmallBitVector &Used);
12949
12950 /// Mark which template parameters are named in a given expression.
12951 ///
12952 /// Unlike MarkUsedTemplateParameters, this excludes parameter that
12953 /// are used but not directly named by an expression - i.e. it excludes
12954 /// any template parameter that denotes the type of a referenced NTTP.
12955 ///
12956 /// \param Used a bit vector whose elements will be set to \c true
12957 /// to indicate when the corresponding template parameter will be
12958 /// deduced.
12959 void MarkUsedTemplateParametersForSubsumptionParameterMapping(
12960 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used);
12961
12962 /// Mark which template parameters can be deduced from a given
12963 /// template argument list.
12964 ///
12965 /// \param TemplateArgs the template argument list from which template
12966 /// parameters will be deduced.
12967 ///
12968 /// \param Used a bit vector whose elements will be set to \c true
12969 /// to indicate when the corresponding template parameter will be
12970 /// deduced.
12971 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
12972 bool OnlyDeduced, unsigned Depth,
12973 llvm::SmallBitVector &Used);
12974
12975 void MarkUsedTemplateParameters(ArrayRef<TemplateArgument> TemplateArgs,
12976 unsigned Depth, llvm::SmallBitVector &Used);
12977
12978 void MarkUsedTemplateParameters(ArrayRef<TemplateArgumentLoc> TemplateArgs,
12979 unsigned Depth, llvm::SmallBitVector &Used);
12980
12981 void
12982 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate,
12983 llvm::SmallBitVector &Deduced) {
12984 return MarkDeducedTemplateParameters(Ctx&: Context, FunctionTemplate, Deduced);
12985 }
12986
12987 /// Marks all of the template parameters that will be deduced by a
12988 /// call to the given function template.
12989 static void
12990 MarkDeducedTemplateParameters(ASTContext &Ctx,
12991 const FunctionTemplateDecl *FunctionTemplate,
12992 llvm::SmallBitVector &Deduced);
12993
12994 /// Returns the more specialized function template according
12995 /// to the rules of function template partial ordering (C++
12996 /// [temp.func.order]).
12997 ///
12998 /// \param FT1 the first function template
12999 ///
13000 /// \param FT2 the second function template
13001 ///
13002 /// \param TPOC the context in which we are performing partial ordering of
13003 /// function templates.
13004 ///
13005 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
13006 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument
13007 /// when calling a member function.
13008 ///
13009 /// \param RawObj1Ty The type of the object parameter of FT1 if a member
13010 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function
13011 /// template from a member function
13012 ///
13013 /// \param RawObj2Ty The type of the object parameter of FT2 if a member
13014 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function
13015 /// template from a member function
13016 ///
13017 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
13018 /// candidate with a reversed parameter order. In this case, the corresponding
13019 /// P/A pairs between FT1 and FT2 are reversed.
13020 ///
13021 /// \returns the more specialized function template. If neither
13022 /// template is more specialized, returns NULL.
13023 FunctionTemplateDecl *getMoreSpecializedTemplate(
13024 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
13025 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
13026 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false,
13027 bool PartialOverloading = false);
13028
13029 /// Retrieve the most specialized of the given function template
13030 /// specializations.
13031 ///
13032 /// \param SpecBegin the start iterator of the function template
13033 /// specializations that we will be comparing.
13034 ///
13035 /// \param SpecEnd the end iterator of the function template
13036 /// specializations, paired with \p SpecBegin.
13037 ///
13038 /// \param Loc the location where the ambiguity or no-specializations
13039 /// diagnostic should occur.
13040 ///
13041 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
13042 /// no matching candidates.
13043 ///
13044 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
13045 /// occurs.
13046 ///
13047 /// \param CandidateDiag partial diagnostic used for each function template
13048 /// specialization that is a candidate in the ambiguous ordering. One
13049 /// parameter in this diagnostic should be unbound, which will correspond to
13050 /// the string describing the template arguments for the function template
13051 /// specialization.
13052 ///
13053 /// \returns the most specialized function template specialization, if
13054 /// found. Otherwise, returns SpecEnd.
13055 UnresolvedSetIterator
13056 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
13057 TemplateSpecCandidateSet &FailedCandidates,
13058 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
13059 const PartialDiagnostic &AmbigDiag,
13060 const PartialDiagnostic &CandidateDiag,
13061 bool Complain = true, QualType TargetType = QualType());
13062
13063 /// Returns the more constrained function according to the rules of
13064 /// partial ordering by constraints (C++ [temp.constr.order]).
13065 ///
13066 /// \param FD1 the first function
13067 ///
13068 /// \param FD2 the second function
13069 ///
13070 /// \returns the more constrained function. If neither function is
13071 /// more constrained, returns NULL.
13072 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1,
13073 FunctionDecl *FD2);
13074
13075 ///@}
13076
13077 //
13078 //
13079 // -------------------------------------------------------------------------
13080 //
13081 //
13082
13083 /// \name C++ Template Deduction Guide
13084 /// Implementations are in SemaTemplateDeductionGuide.cpp
13085 ///@{
13086
13087 /// Declare implicit deduction guides for a class template if we've
13088 /// not already done so.
13089 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
13090 SourceLocation Loc);
13091
13092 CXXDeductionGuideDecl *DeclareAggregateDeductionGuideFromInitList(
13093 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
13094 SourceLocation Loc);
13095
13096 ///@}
13097
13098 //
13099 //
13100 // -------------------------------------------------------------------------
13101 //
13102 //
13103
13104 /// \name C++ Template Instantiation
13105 /// Implementations are in SemaTemplateInstantiate.cpp
13106 ///@{
13107
13108public:
13109 /// A helper class for building up ExtParameterInfos.
13110 class ExtParameterInfoBuilder {
13111 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
13112 bool HasInteresting = false;
13113
13114 public:
13115 /// Set the ExtParameterInfo for the parameter at the given index,
13116 ///
13117 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
13118 assert(Infos.size() <= index);
13119 Infos.resize(N: index);
13120 Infos.push_back(Elt: info);
13121
13122 if (!HasInteresting)
13123 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
13124 }
13125
13126 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
13127 /// ExtParameterInfo array we've built up.
13128 const FunctionProtoType::ExtParameterInfo *
13129 getPointerOrNull(unsigned numParams) {
13130 if (!HasInteresting)
13131 return nullptr;
13132 Infos.resize(N: numParams);
13133 return Infos.data();
13134 }
13135 };
13136
13137 /// The current instantiation scope used to store local
13138 /// variables.
13139 LocalInstantiationScope *CurrentInstantiationScope;
13140
13141 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
13142 UnparsedDefaultArgInstantiationsMap;
13143
13144 /// A mapping from parameters with unparsed default arguments to the
13145 /// set of instantiations of each parameter.
13146 ///
13147 /// This mapping is a temporary data structure used when parsing
13148 /// nested class templates or nested classes of class templates,
13149 /// where we might end up instantiating an inner class before the
13150 /// default arguments of its methods have been parsed.
13151 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
13152
13153 using InstantiatingSpecializationsKey = llvm::PointerIntPair<Decl *, 2>;
13154
13155 struct RecursiveInstGuard {
13156 enum class Kind {
13157 Template,
13158 DefaultArgument,
13159 ExceptionSpec,
13160 };
13161
13162 RecursiveInstGuard(Sema &S, Decl *D, Kind Kind)
13163 : S(S), Key(D->getCanonicalDecl(), unsigned(Kind)) {
13164 auto [_, Created] = S.InstantiatingSpecializations.insert(V: Key);
13165 if (!Created)
13166 Key = {};
13167 }
13168
13169 ~RecursiveInstGuard() {
13170 if (Key.getOpaqueValue()) {
13171 [[maybe_unused]] bool Erased =
13172 S.InstantiatingSpecializations.erase(V: Key);
13173 assert(Erased);
13174 }
13175 }
13176
13177 RecursiveInstGuard(const RecursiveInstGuard &) = delete;
13178 RecursiveInstGuard &operator=(const RecursiveInstGuard &) = delete;
13179
13180 operator bool() const { return Key.getOpaqueValue() == nullptr; }
13181
13182 private:
13183 Sema &S;
13184 Sema::InstantiatingSpecializationsKey Key;
13185 };
13186
13187 /// A context in which code is being synthesized (where a source location
13188 /// alone is not sufficient to identify the context). This covers template
13189 /// instantiation and various forms of implicitly-generated functions.
13190 struct CodeSynthesisContext {
13191 /// The kind of template instantiation we are performing
13192 enum SynthesisKind {
13193 /// We are instantiating a template declaration. The entity is
13194 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
13195 TemplateInstantiation,
13196
13197 /// We are instantiating a default argument for a template
13198 /// parameter. The Entity is the template parameter whose argument is
13199 /// being instantiated, the Template is the template, and the
13200 /// TemplateArgs/NumTemplateArguments provide the template arguments as
13201 /// specified.
13202 DefaultTemplateArgumentInstantiation,
13203
13204 /// We are instantiating a default argument for a function.
13205 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
13206 /// provides the template arguments as specified.
13207 DefaultFunctionArgumentInstantiation,
13208
13209 /// We are substituting explicit template arguments provided for
13210 /// a function template. The entity is a FunctionTemplateDecl.
13211 ExplicitTemplateArgumentSubstitution,
13212
13213 /// We are substituting template argument determined as part of
13214 /// template argument deduction for either a class template
13215 /// partial specialization or a function template. The
13216 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
13217 /// a TemplateDecl.
13218 DeducedTemplateArgumentSubstitution,
13219
13220 /// We are substituting into a lambda expression.
13221 LambdaExpressionSubstitution,
13222
13223 /// We are substituting prior template arguments into a new
13224 /// template parameter. The template parameter itself is either a
13225 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
13226 PriorTemplateArgumentSubstitution,
13227
13228 /// We are checking the validity of a default template argument that
13229 /// has been used when naming a template-id.
13230 DefaultTemplateArgumentChecking,
13231
13232 /// We are computing the exception specification for a defaulted special
13233 /// member function.
13234 ExceptionSpecEvaluation,
13235
13236 /// We are instantiating the exception specification for a function
13237 /// template which was deferred until it was needed.
13238 ExceptionSpecInstantiation,
13239
13240 /// We are instantiating a requirement of a requires expression.
13241 RequirementInstantiation,
13242
13243 /// We are checking the satisfaction of a nested requirement of a requires
13244 /// expression.
13245 NestedRequirementConstraintsCheck,
13246
13247 /// We are declaring an implicit special member function.
13248 DeclaringSpecialMember,
13249
13250 /// We are declaring an implicit 'operator==' for a defaulted
13251 /// 'operator<=>'.
13252 DeclaringImplicitEqualityComparison,
13253
13254 /// We are defining a synthesized function (such as a defaulted special
13255 /// member).
13256 DefiningSynthesizedFunction,
13257
13258 // We are checking the constraints associated with a constrained entity or
13259 // the constraint expression of a concept. This includes the checks that
13260 // atomic constraints have the type 'bool' and that they can be constant
13261 // evaluated.
13262 ConstraintsCheck,
13263
13264 // We are substituting template arguments into a constraint expression.
13265 ConstraintSubstitution,
13266
13267 // Instantiating a Requires Expression parameter clause.
13268 RequirementParameterInstantiation,
13269
13270 // We are substituting into the parameter mapping of an atomic constraint
13271 // during normalization.
13272 ParameterMappingSubstitution,
13273
13274 /// We are rewriting a comparison operator in terms of an operator<=>.
13275 RewritingOperatorAsSpaceship,
13276
13277 /// We are initializing a structured binding.
13278 InitializingStructuredBinding,
13279
13280 /// We are marking a class as __dllexport.
13281 MarkingClassDllexported,
13282
13283 /// We are building an implied call from __builtin_dump_struct. The
13284 /// arguments are in CallArgs.
13285 BuildingBuiltinDumpStructCall,
13286
13287 /// Added for Template instantiation observation.
13288 /// Memoization means we are _not_ instantiating a template because
13289 /// it is already instantiated (but we entered a context where we
13290 /// would have had to if it was not already instantiated).
13291 Memoization,
13292
13293 /// We are building deduction guides for a class.
13294 BuildingDeductionGuides,
13295
13296 /// We are instantiating a type alias template declaration.
13297 TypeAliasTemplateInstantiation,
13298
13299 /// We are performing partial ordering for template template parameters.
13300 PartialOrderingTTP,
13301
13302 /// We are performing name lookup for a function template or variable
13303 /// template named 'sycl_kernel_launch'.
13304 SYCLKernelLaunchLookup,
13305
13306 /// We are performing overload resolution for a call to a function
13307 /// template or variable template named 'sycl_kernel_launch'.
13308 SYCLKernelLaunchOverloadResolution,
13309 } Kind;
13310
13311 /// Whether we're substituting into constraints.
13312 bool InConstraintSubstitution;
13313
13314 /// Whether we're substituting into the parameter mapping of a constraint.
13315 bool InParameterMappingSubstitution;
13316
13317 /// The point of instantiation or synthesis within the source code.
13318 SourceLocation PointOfInstantiation;
13319
13320 /// The entity that is being synthesized.
13321 Decl *Entity;
13322
13323 /// The template (or partial specialization) in which we are
13324 /// performing the instantiation, for substitutions of prior template
13325 /// arguments.
13326 NamedDecl *Template;
13327
13328 union {
13329 /// The list of template arguments we are substituting, if they
13330 /// are not part of the entity.
13331 const TemplateArgument *TemplateArgs;
13332
13333 /// The list of argument expressions in a synthesized call.
13334 const Expr *const *CallArgs;
13335 };
13336
13337 // FIXME: Wrap this union around more members, or perhaps store the
13338 // kind-specific members in the RAII object owning the context.
13339 union {
13340 /// The number of template arguments in TemplateArgs.
13341 unsigned NumTemplateArgs;
13342
13343 /// The number of expressions in CallArgs.
13344 unsigned NumCallArgs;
13345
13346 /// The special member being declared or defined.
13347 CXXSpecialMemberKind SpecialMember;
13348 };
13349
13350 ArrayRef<TemplateArgument> template_arguments() const {
13351 assert(Kind != DeclaringSpecialMember);
13352 return {TemplateArgs, NumTemplateArgs};
13353 }
13354
13355 /// The source range that covers the construct that cause
13356 /// the instantiation, e.g., the template-id that causes a class
13357 /// template instantiation.
13358 SourceRange InstantiationRange;
13359
13360 CodeSynthesisContext()
13361 : Kind(TemplateInstantiation), InConstraintSubstitution(false),
13362 InParameterMappingSubstitution(false), Entity(nullptr),
13363 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0) {}
13364
13365 /// Determines whether this template is an actual instantiation
13366 /// that should be counted toward the maximum instantiation depth.
13367 bool isInstantiationRecord() const;
13368 };
13369
13370 /// A stack object to be created when performing template
13371 /// instantiation.
13372 ///
13373 /// Construction of an object of type \c InstantiatingTemplate
13374 /// pushes the current instantiation onto the stack of active
13375 /// instantiations. If the size of this stack exceeds the maximum
13376 /// number of recursive template instantiations, construction
13377 /// produces an error and evaluates true.
13378 ///
13379 /// Destruction of this object will pop the named instantiation off
13380 /// the stack.
13381 struct InstantiatingTemplate {
13382 /// Note that we are instantiating a class template,
13383 /// function template, variable template, alias template,
13384 /// or a member thereof.
13385 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13386 Decl *Entity,
13387 SourceRange InstantiationRange = SourceRange());
13388
13389 struct ExceptionSpecification {};
13390 /// Note that we are instantiating an exception specification
13391 /// of a function template.
13392 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13393 FunctionDecl *Entity, ExceptionSpecification,
13394 SourceRange InstantiationRange = SourceRange());
13395
13396 /// Note that we are instantiating a type alias template declaration.
13397 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13398 TypeAliasTemplateDecl *Entity,
13399 ArrayRef<TemplateArgument> TemplateArgs,
13400 SourceRange InstantiationRange = SourceRange());
13401
13402 /// Note that we are instantiating a default argument in a
13403 /// template-id.
13404 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13405 TemplateParameter Param, TemplateDecl *Template,
13406 ArrayRef<TemplateArgument> TemplateArgs,
13407 SourceRange InstantiationRange = SourceRange());
13408
13409 /// Note that we are substituting either explicitly-specified or
13410 /// deduced template arguments during function template argument deduction.
13411 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13412 FunctionTemplateDecl *FunctionTemplate,
13413 ArrayRef<TemplateArgument> TemplateArgs,
13414 CodeSynthesisContext::SynthesisKind Kind,
13415 SourceRange InstantiationRange = SourceRange());
13416
13417 /// Note that we are instantiating as part of template
13418 /// argument deduction for a class template declaration.
13419 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13420 TemplateDecl *Template,
13421 ArrayRef<TemplateArgument> TemplateArgs,
13422 SourceRange InstantiationRange = SourceRange());
13423
13424 /// Note that we are instantiating as part of template
13425 /// argument deduction for a class template partial
13426 /// specialization.
13427 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13428 ClassTemplatePartialSpecializationDecl *PartialSpec,
13429 ArrayRef<TemplateArgument> TemplateArgs,
13430 SourceRange InstantiationRange = SourceRange());
13431
13432 /// Note that we are instantiating as part of template
13433 /// argument deduction for a variable template partial
13434 /// specialization.
13435 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13436 VarTemplatePartialSpecializationDecl *PartialSpec,
13437 ArrayRef<TemplateArgument> TemplateArgs,
13438 SourceRange InstantiationRange = SourceRange());
13439
13440 /// Note that we are instantiating a default argument for a function
13441 /// parameter.
13442 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13443 ParmVarDecl *Param,
13444 ArrayRef<TemplateArgument> TemplateArgs,
13445 SourceRange InstantiationRange = SourceRange());
13446
13447 /// Note that we are substituting prior template arguments into a
13448 /// non-type parameter.
13449 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13450 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
13451 ArrayRef<TemplateArgument> TemplateArgs,
13452 SourceRange InstantiationRange);
13453
13454 /// Note that we are substituting prior template arguments into a
13455 /// template template parameter.
13456 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13457 NamedDecl *Template, TemplateTemplateParmDecl *Param,
13458 ArrayRef<TemplateArgument> TemplateArgs,
13459 SourceRange InstantiationRange);
13460
13461 /// Note that we are checking the default template argument
13462 /// against the template parameter for a given template-id.
13463 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13464 TemplateDecl *Template, NamedDecl *Param,
13465 ArrayRef<TemplateArgument> TemplateArgs,
13466 SourceRange InstantiationRange);
13467
13468 struct ConstraintsCheck {};
13469 /// \brief Note that we are checking the constraints associated with some
13470 /// constrained entity (a concept declaration or a template with associated
13471 /// constraints).
13472 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13473 ConstraintsCheck, NamedDecl *Template,
13474 ArrayRef<TemplateArgument> TemplateArgs,
13475 SourceRange InstantiationRange);
13476
13477 struct ConstraintSubstitution {};
13478 /// \brief Note that we are checking a constraint expression associated
13479 /// with a template declaration or as part of the satisfaction check of a
13480 /// concept.
13481 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13482 ConstraintSubstitution, NamedDecl *Template,
13483 SourceRange InstantiationRange);
13484
13485 struct ParameterMappingSubstitution {};
13486 /// \brief Note that we are subtituting into the parameter mapping of an
13487 /// atomic constraint during constraint normalization.
13488 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13489 ParameterMappingSubstitution, NamedDecl *Template,
13490 SourceRange InstantiationRange);
13491
13492 /// \brief Note that we are substituting template arguments into a part of
13493 /// a requirement of a requires expression.
13494 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13495 concepts::Requirement *Req,
13496 SourceRange InstantiationRange = SourceRange());
13497
13498 /// \brief Note that we are checking the satisfaction of the constraint
13499 /// expression inside of a nested requirement.
13500 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13501 concepts::NestedRequirement *Req, ConstraintsCheck,
13502 SourceRange InstantiationRange = SourceRange());
13503
13504 /// \brief Note that we are checking a requires clause.
13505 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13506 const RequiresExpr *E,
13507 SourceRange InstantiationRange);
13508
13509 struct BuildingDeductionGuidesTag {};
13510 /// \brief Note that we are building deduction guides.
13511 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
13512 TemplateDecl *Entity, BuildingDeductionGuidesTag,
13513 SourceRange InstantiationRange = SourceRange());
13514
13515 struct PartialOrderingTTP {};
13516 /// \brief Note that we are partial ordering template template parameters.
13517 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc,
13518 PartialOrderingTTP, TemplateDecl *PArg,
13519 SourceRange InstantiationRange = SourceRange());
13520
13521 /// Note that we have finished instantiating this template.
13522 void Clear();
13523
13524 ~InstantiatingTemplate() { Clear(); }
13525
13526 /// Determines whether we have exceeded the maximum
13527 /// recursive template instantiations.
13528 bool isInvalid() const { return Invalid; }
13529
13530 private:
13531 Sema &SemaRef;
13532 bool Invalid;
13533
13534 InstantiatingTemplate(Sema &SemaRef,
13535 CodeSynthesisContext::SynthesisKind Kind,
13536 SourceLocation PointOfInstantiation,
13537 SourceRange InstantiationRange, Decl *Entity,
13538 NamedDecl *Template = nullptr,
13539 ArrayRef<TemplateArgument> TemplateArgs = {});
13540
13541 InstantiatingTemplate(const InstantiatingTemplate &) = delete;
13542
13543 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete;
13544 };
13545
13546 bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
13547 const MultiLevelTemplateArgumentList &TemplateArgs,
13548 TemplateArgumentLoc &Output,
13549 SourceLocation Loc = {},
13550 const DeclarationName &Entity = {});
13551 bool
13552 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
13553 const MultiLevelTemplateArgumentList &TemplateArgs,
13554 TemplateArgumentListInfo &Outputs);
13555
13556 /// Substitute concept template arguments in the constraint expression
13557 /// of a concept-id. This is used to implement [temp.constr.normal].
13558 ExprResult
13559 SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE,
13560 const Expr *ConstraintExpr,
13561 const MultiLevelTemplateArgumentList &MLTAL);
13562
13563 bool SubstTemplateArgumentsInParameterMapping(
13564 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
13565 const MultiLevelTemplateArgumentList &TemplateArgs,
13566 TemplateArgumentListInfo &Out);
13567
13568 /// Retrieve the template argument list(s) that should be used to
13569 /// instantiate the definition of the given declaration.
13570 ///
13571 /// \param ND the declaration for which we are computing template
13572 /// instantiation arguments.
13573 ///
13574 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
13575 /// the decl context where it will be created. In this case, the `Innermost`
13576 /// should likely be provided. If ND is non-null, this is ignored.
13577 ///
13578 /// \param Innermost if non-NULL, specifies a template argument list for the
13579 /// template declaration passed as ND.
13580 ///
13581 /// \param RelativeToPrimary true if we should get the template
13582 /// arguments relative to the primary template, even when we're
13583 /// dealing with a specialization. This is only relevant for function
13584 /// template specializations.
13585 ///
13586 /// \param Pattern If non-NULL, indicates the pattern from which we will be
13587 /// instantiating the definition of the given declaration, \p ND. This is
13588 /// used to determine the proper set of template instantiation arguments for
13589 /// friend function template specializations.
13590 ///
13591 /// \param ForConstraintInstantiation when collecting arguments,
13592 /// ForConstraintInstantiation indicates we should continue looking when
13593 /// encountering a lambda generic call operator, and continue looking for
13594 /// arguments on an enclosing class template.
13595 ///
13596 /// \param SkipForSpecialization when specified, any template specializations
13597 /// in a traversal would be ignored.
13598 ///
13599 /// \param ForDefaultArgumentSubstitution indicates we should continue looking
13600 /// when encountering a specialized member function template, rather than
13601 /// returning immediately.
13602 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
13603 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false,
13604 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt,
13605 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr,
13606 bool ForConstraintInstantiation = false,
13607 bool SkipForSpecialization = false,
13608 bool ForDefaultArgumentSubstitution = false);
13609
13610 /// RAII object to handle the state changes required to synthesize
13611 /// a function body.
13612 class SynthesizedFunctionScope {
13613 Sema &S;
13614 Sema::ContextRAII SavedContext;
13615 bool PushedCodeSynthesisContext = false;
13616
13617 public:
13618 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
13619 : S(S), SavedContext(S, DC) {
13620 auto *FD = dyn_cast<FunctionDecl>(Val: DC);
13621 S.PushFunctionScope();
13622 S.PushExpressionEvaluationContextForFunction(
13623 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD);
13624 if (FD)
13625 FD->setWillHaveBody(true);
13626 else
13627 assert(isa<ObjCMethodDecl>(DC));
13628 }
13629
13630 void addContextNote(SourceLocation UseLoc) {
13631 assert(!PushedCodeSynthesisContext);
13632
13633 Sema::CodeSynthesisContext Ctx;
13634 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
13635 Ctx.PointOfInstantiation = UseLoc;
13636 Ctx.Entity = cast<Decl>(Val: S.CurContext);
13637 S.pushCodeSynthesisContext(Ctx);
13638
13639 PushedCodeSynthesisContext = true;
13640 }
13641
13642 ~SynthesizedFunctionScope() {
13643 if (PushedCodeSynthesisContext)
13644 S.popCodeSynthesisContext();
13645 if (auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext)) {
13646 FD->setWillHaveBody(false);
13647 S.CheckImmediateEscalatingFunctionDefinition(FD, FSI: S.getCurFunction());
13648 }
13649 S.PopExpressionEvaluationContext();
13650 S.PopFunctionScopeInfo();
13651 }
13652
13653 SynthesizedFunctionScope(const SynthesizedFunctionScope &) = delete;
13654 SynthesizedFunctionScope &
13655 operator=(const SynthesizedFunctionScope &) = delete;
13656 };
13657
13658 /// RAII object to ensure that a code synthesis context is popped on scope
13659 /// exit.
13660 class ScopedCodeSynthesisContext {
13661 Sema &S;
13662
13663 public:
13664 ScopedCodeSynthesisContext(Sema &S, const CodeSynthesisContext &Ctx)
13665 : S(S) {
13666 S.pushCodeSynthesisContext(Ctx);
13667 }
13668
13669 ~ScopedCodeSynthesisContext() { S.popCodeSynthesisContext(); }
13670 ScopedCodeSynthesisContext(const ScopedCodeSynthesisContext &) = delete;
13671 ScopedCodeSynthesisContext &
13672 operator=(const ScopedCodeSynthesisContext &) = delete;
13673 };
13674
13675 /// List of active code synthesis contexts.
13676 ///
13677 /// This vector is treated as a stack. As synthesis of one entity requires
13678 /// synthesis of another, additional contexts are pushed onto the stack.
13679 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
13680
13681 /// Specializations whose definitions are currently being instantiated.
13682 llvm::DenseSet<InstantiatingSpecializationsKey> InstantiatingSpecializations;
13683
13684 /// Non-dependent types used in templates that have already been instantiated
13685 /// by some template instantiation.
13686 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
13687
13688 /// Extra modules inspected when performing a lookup during a template
13689 /// instantiation. Computed lazily.
13690 SmallVector<Module *, 16> CodeSynthesisContextLookupModules;
13691
13692 /// Cache of additional modules that should be used for name lookup
13693 /// within the current template instantiation. Computed lazily; use
13694 /// getLookupModules() to get a complete set.
13695 llvm::DenseSet<Module *> LookupModulesCache;
13696
13697 /// Map from the most recent declaration of a namespace to the most
13698 /// recent visible declaration of that namespace.
13699 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache;
13700
13701 SFINAETrap *CurrentSFINAEContext = nullptr;
13702
13703 /// The number of \p CodeSynthesisContexts that are not template
13704 /// instantiations and, therefore, should not be counted as part of the
13705 /// instantiation depth.
13706 ///
13707 /// When the instantiation depth reaches the user-configurable limit
13708 /// \p LangOptions::InstantiationDepth we will abort instantiation.
13709 // FIXME: Should we have a similar limit for other forms of synthesis?
13710 unsigned NonInstantiationEntries;
13711
13712 /// The depth of the context stack at the point when the most recent
13713 /// error or warning was produced.
13714 ///
13715 /// This value is used to suppress printing of redundant context stacks
13716 /// when there are multiple errors or warnings in the same instantiation.
13717 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
13718 unsigned LastEmittedCodeSynthesisContextDepth = 0;
13719
13720 /// The template instantiation callbacks to trace or track
13721 /// instantiations (objects can be chained).
13722 ///
13723 /// This callbacks is used to print, trace or track template
13724 /// instantiations as they are being constructed.
13725 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
13726 TemplateInstCallbacks;
13727
13728 /// The current index into pack expansion arguments that will be
13729 /// used for substitution of parameter packs.
13730 ///
13731 /// The pack expansion index will be none to indicate that parameter packs
13732 /// should be instantiated as themselves. Otherwise, the index specifies
13733 /// which argument within the parameter pack will be used for substitution.
13734 UnsignedOrNone ArgPackSubstIndex;
13735
13736 /// RAII object used to change the argument pack substitution index
13737 /// within a \c Sema object.
13738 ///
13739 /// See \c ArgPackSubstIndex for more information.
13740 class ArgPackSubstIndexRAII {
13741 Sema &Self;
13742 UnsignedOrNone OldSubstIndex;
13743
13744 public:
13745 ArgPackSubstIndexRAII(Sema &Self, UnsignedOrNone NewSubstIndex)
13746 : Self(Self),
13747 OldSubstIndex(std::exchange(obj&: Self.ArgPackSubstIndex, new_val&: NewSubstIndex)) {}
13748
13749 ~ArgPackSubstIndexRAII() { Self.ArgPackSubstIndex = OldSubstIndex; }
13750 ArgPackSubstIndexRAII(const ArgPackSubstIndexRAII &) = delete;
13751 ArgPackSubstIndexRAII &operator=(const ArgPackSubstIndexRAII &) = delete;
13752 };
13753
13754 bool pushCodeSynthesisContext(CodeSynthesisContext Ctx);
13755 void popCodeSynthesisContext();
13756
13757 void PrintContextStack(InstantiationContextDiagFuncRef DiagFunc) {
13758 if (!CodeSynthesisContexts.empty() &&
13759 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
13760 PrintInstantiationStack(DiagFunc);
13761 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
13762 }
13763 if (PragmaAttributeCurrentTargetDecl)
13764 PrintPragmaAttributeInstantiationPoint(DiagFunc);
13765 }
13766 void PrintContextStack() { PrintContextStack(DiagFunc: getDefaultDiagFunc()); }
13767 /// Prints the current instantiation stack through a series of
13768 /// notes.
13769 void PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc);
13770 void PrintInstantiationStack() {
13771 PrintInstantiationStack(DiagFunc: getDefaultDiagFunc());
13772 }
13773
13774 /// Returns a pointer to the current SFINAE context, if any.
13775 [[nodiscard]] SFINAETrap *getSFINAEContext() const {
13776 return CurrentSFINAEContext;
13777 }
13778 [[nodiscard]] bool isSFINAEContext() const {
13779 return CurrentSFINAEContext != nullptr;
13780 }
13781
13782 /// Perform substitution on the type T with a given set of template
13783 /// arguments.
13784 ///
13785 /// This routine substitutes the given template arguments into the
13786 /// type T and produces the instantiated type.
13787 ///
13788 /// \param T the type into which the template arguments will be
13789 /// substituted. If this type is not dependent, it will be returned
13790 /// immediately.
13791 ///
13792 /// \param Args the template arguments that will be
13793 /// substituted for the top-level template parameters within T.
13794 ///
13795 /// \param Loc the location in the source code where this substitution
13796 /// is being performed. It will typically be the location of the
13797 /// declarator (if we're instantiating the type of some declaration)
13798 /// or the location of the type in the source code (if, e.g., we're
13799 /// instantiating the type of a cast expression).
13800 ///
13801 /// \param Entity the name of the entity associated with a declaration
13802 /// being instantiated (if any). May be empty to indicate that there
13803 /// is no such entity (if, e.g., this is a type that occurs as part of
13804 /// a cast expression) or that the entity has no name (e.g., an
13805 /// unnamed function parameter).
13806 ///
13807 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
13808 /// acceptable as the top level type of the result.
13809 ///
13810 /// \param IsIncompleteSubstitution If provided, the pointee will be set
13811 /// whenever substitution would perform a replacement with a null or
13812 /// non-existent template argument.
13813 ///
13814 /// \returns If the instantiation succeeds, the instantiated
13815 /// type. Otherwise, produces diagnostics and returns a NULL type.
13816 TypeSourceInfo *SubstType(TypeSourceInfo *T,
13817 const MultiLevelTemplateArgumentList &TemplateArgs,
13818 SourceLocation Loc, DeclarationName Entity,
13819 bool AllowDeducedTST = false);
13820
13821 QualType SubstType(QualType T,
13822 const MultiLevelTemplateArgumentList &TemplateArgs,
13823 SourceLocation Loc, DeclarationName Entity,
13824 bool *IsIncompleteSubstitution = nullptr);
13825
13826 TypeSourceInfo *SubstType(TypeLoc TL,
13827 const MultiLevelTemplateArgumentList &TemplateArgs,
13828 SourceLocation Loc, DeclarationName Entity);
13829
13830 /// A form of SubstType intended specifically for instantiating the
13831 /// type of a FunctionDecl. Its purpose is solely to force the
13832 /// instantiation of default-argument expressions and to avoid
13833 /// instantiating an exception-specification.
13834 TypeSourceInfo *SubstFunctionDeclType(
13835 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs,
13836 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
13837 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true);
13838 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
13839 const MultiLevelTemplateArgumentList &Args);
13840 bool SubstExceptionSpec(SourceLocation Loc,
13841 FunctionProtoType::ExceptionSpecInfo &ESI,
13842 SmallVectorImpl<QualType> &ExceptionStorage,
13843 const MultiLevelTemplateArgumentList &Args);
13844 ParmVarDecl *
13845 SubstParmVarDecl(ParmVarDecl *D,
13846 const MultiLevelTemplateArgumentList &TemplateArgs,
13847 int indexAdjustment, UnsignedOrNone NumExpansions,
13848 bool ExpectParameterPack, bool EvaluateConstraints = true);
13849
13850 /// Substitute the given template arguments into the given set of
13851 /// parameters, producing the set of parameter types that would be generated
13852 /// from such a substitution.
13853 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
13854 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
13855 const MultiLevelTemplateArgumentList &TemplateArgs,
13856 SmallVectorImpl<QualType> &ParamTypes,
13857 SmallVectorImpl<ParmVarDecl *> *OutParams,
13858 ExtParameterInfoBuilder &ParamInfos);
13859
13860 /// Substitute the given template arguments into the default argument.
13861 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
13862 const MultiLevelTemplateArgumentList &TemplateArgs,
13863 bool ForCallExpr = false);
13864 ExprResult SubstExpr(Expr *E,
13865 const MultiLevelTemplateArgumentList &TemplateArgs);
13866 /// Substitute an expression as if it is a address-of-operand, which makes it
13867 /// act like a CXXIdExpression rather than an attempt to call.
13868 ExprResult SubstCXXIdExpr(Expr *E,
13869 const MultiLevelTemplateArgumentList &TemplateArgs);
13870
13871 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator
13872 // to disable constraint evaluation, then restore the state.
13873 template <typename InstTy> struct ConstraintEvalRAII {
13874 InstTy &TI;
13875 bool OldValue;
13876
13877 ConstraintEvalRAII(InstTy &TI)
13878 : TI(TI), OldValue(TI.getEvaluateConstraints()) {
13879 TI.setEvaluateConstraints(false);
13880 }
13881 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); }
13882 ConstraintEvalRAII(const ConstraintEvalRAII &) = delete;
13883 ConstraintEvalRAII &operator=(const ConstraintEvalRAII &) = delete;
13884 };
13885
13886 // Must be used instead of SubstExpr at 'constraint checking' time.
13887 ExprResult
13888 SubstConstraintExpr(Expr *E,
13889 const MultiLevelTemplateArgumentList &TemplateArgs);
13890 // Unlike the above, this does not evaluate constraints.
13891 ExprResult SubstConstraintExprWithoutSatisfaction(
13892 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs);
13893
13894 /// Substitute the given template arguments into a list of
13895 /// expressions, expanding pack expansions if required.
13896 ///
13897 /// \param Exprs The list of expressions to substitute into.
13898 ///
13899 /// \param IsCall Whether this is some form of call, in which case
13900 /// default arguments will be dropped.
13901 ///
13902 /// \param TemplateArgs The set of template arguments to substitute.
13903 ///
13904 /// \param Outputs Will receive all of the substituted arguments.
13905 ///
13906 /// \returns true if an error occurred, false otherwise.
13907 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
13908 const MultiLevelTemplateArgumentList &TemplateArgs,
13909 SmallVectorImpl<Expr *> &Outputs);
13910
13911 StmtResult SubstStmt(Stmt *S,
13912 const MultiLevelTemplateArgumentList &TemplateArgs);
13913
13914 ExprResult
13915 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs,
13916 bool CXXDirectInit);
13917
13918 /// Perform substitution on the base class specifiers of the
13919 /// given class template specialization.
13920 ///
13921 /// Produces a diagnostic and returns true on error, returns false and
13922 /// attaches the instantiated base classes to the class template
13923 /// specialization if successful.
13924 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13925 const MultiLevelTemplateArgumentList &TemplateArgs);
13926
13927 /// Instantiate the definition of a class from a given pattern.
13928 ///
13929 /// \param PointOfInstantiation The point of instantiation within the
13930 /// source code.
13931 ///
13932 /// \param Instantiation is the declaration whose definition is being
13933 /// instantiated. This will be either a class template specialization
13934 /// or a member class of a class template specialization.
13935 ///
13936 /// \param Pattern is the pattern from which the instantiation
13937 /// occurs. This will be either the declaration of a class template or
13938 /// the declaration of a member class of a class template.
13939 ///
13940 /// \param TemplateArgs The template arguments to be substituted into
13941 /// the pattern.
13942 ///
13943 /// \param TSK the kind of implicit or explicit instantiation to perform.
13944 ///
13945 /// \param Complain whether to complain if the class cannot be instantiated
13946 /// due to the lack of a definition.
13947 ///
13948 /// \returns true if an error occurred, false otherwise.
13949 bool InstantiateClass(SourceLocation PointOfInstantiation,
13950 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
13951 const MultiLevelTemplateArgumentList &TemplateArgs,
13952 TemplateSpecializationKind TSK, bool Complain = true);
13953
13954private:
13955 bool InstantiateClassImpl(SourceLocation PointOfInstantiation,
13956 CXXRecordDecl *Instantiation,
13957 CXXRecordDecl *Pattern,
13958 const MultiLevelTemplateArgumentList &TemplateArgs,
13959 TemplateSpecializationKind TSK, bool Complain);
13960
13961public:
13962 /// Instantiate the definition of an enum from a given pattern.
13963 ///
13964 /// \param PointOfInstantiation The point of instantiation within the
13965 /// source code.
13966 /// \param Instantiation is the declaration whose definition is being
13967 /// instantiated. This will be a member enumeration of a class
13968 /// temploid specialization, or a local enumeration within a
13969 /// function temploid specialization.
13970 /// \param Pattern The templated declaration from which the instantiation
13971 /// occurs.
13972 /// \param TemplateArgs The template arguments to be substituted into
13973 /// the pattern.
13974 /// \param TSK The kind of implicit or explicit instantiation to perform.
13975 ///
13976 /// \return \c true if an error occurred, \c false otherwise.
13977 bool InstantiateEnum(SourceLocation PointOfInstantiation,
13978 EnumDecl *Instantiation, EnumDecl *Pattern,
13979 const MultiLevelTemplateArgumentList &TemplateArgs,
13980 TemplateSpecializationKind TSK);
13981
13982 /// Instantiate the definition of a field from the given pattern.
13983 ///
13984 /// \param PointOfInstantiation The point of instantiation within the
13985 /// source code.
13986 /// \param Instantiation is the declaration whose definition is being
13987 /// instantiated. This will be a class of a class temploid
13988 /// specialization, or a local enumeration within a function temploid
13989 /// specialization.
13990 /// \param Pattern The templated declaration from which the instantiation
13991 /// occurs.
13992 /// \param TemplateArgs The template arguments to be substituted into
13993 /// the pattern.
13994 ///
13995 /// \return \c true if an error occurred, \c false otherwise.
13996 bool InstantiateInClassInitializer(
13997 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
13998 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
13999
14000 bool usesPartialOrExplicitSpecialization(
14001 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
14002
14003 bool InstantiateClassTemplateSpecialization(
14004 SourceLocation PointOfInstantiation,
14005 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14006 TemplateSpecializationKind TSK, bool Complain,
14007 bool PrimaryStrictPackMatch);
14008
14009 /// Instantiates the definitions of all of the member
14010 /// of the given class, which is an instantiation of a class template
14011 /// or a member class of a template.
14012 void
14013 InstantiateClassMembers(SourceLocation PointOfInstantiation,
14014 CXXRecordDecl *Instantiation,
14015 const MultiLevelTemplateArgumentList &TemplateArgs,
14016 TemplateSpecializationKind TSK);
14017
14018 /// Instantiate the definitions of all of the members of the
14019 /// given class template specialization, which was named as part of an
14020 /// explicit instantiation.
14021 void InstantiateClassTemplateSpecializationMembers(
14022 SourceLocation PointOfInstantiation,
14023 ClassTemplateSpecializationDecl *ClassTemplateSpec,
14024 TemplateSpecializationKind TSK);
14025
14026 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(
14027 NestedNameSpecifierLoc NNS,
14028 const MultiLevelTemplateArgumentList &TemplateArgs);
14029
14030 /// Do template substitution on declaration name info.
14031 DeclarationNameInfo
14032 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
14033 const MultiLevelTemplateArgumentList &TemplateArgs);
14034 TemplateName
14035 SubstTemplateName(SourceLocation TemplateKWLoc,
14036 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
14037 SourceLocation NameLoc,
14038 const MultiLevelTemplateArgumentList &TemplateArgs);
14039
14040 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
14041 const MultiLevelTemplateArgumentList &TemplateArgs,
14042 bool EvaluateConstraint);
14043
14044 /// Determine whether we are currently performing template instantiation.
14045 bool inTemplateInstantiation() const {
14046 return CodeSynthesisContexts.size() > NonInstantiationEntries;
14047 }
14048
14049 /// Determine whether we are currently performing constraint substitution.
14050 bool inConstraintSubstitution() const {
14051 return !CodeSynthesisContexts.empty() &&
14052 CodeSynthesisContexts.back().InConstraintSubstitution;
14053 }
14054
14055 bool inParameterMappingSubstitution() const {
14056 return !CodeSynthesisContexts.empty() &&
14057 CodeSynthesisContexts.back().InParameterMappingSubstitution &&
14058 !inConstraintSubstitution();
14059 }
14060
14061 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>;
14062
14063 /// \brief create a Requirement::SubstitutionDiagnostic with only a
14064 /// SubstitutedEntity and DiagLoc using ASTContext's allocator.
14065 concepts::Requirement::SubstitutionDiagnostic *
14066 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer);
14067
14068 ///@}
14069
14070 //
14071 //
14072 // -------------------------------------------------------------------------
14073 //
14074 //
14075
14076 /// \name C++ Template Declaration Instantiation
14077 /// Implementations are in SemaTemplateInstantiateDecl.cpp
14078 ///@{
14079
14080public:
14081 /// An entity for which implicit template instantiation is required.
14082 ///
14083 /// The source location associated with the declaration is the first place in
14084 /// the source code where the declaration was "used". It is not necessarily
14085 /// the point of instantiation (which will be either before or after the
14086 /// namespace-scope declaration that triggered this implicit instantiation),
14087 /// However, it is the location that diagnostics should generally refer to,
14088 /// because users will need to know what code triggered the instantiation.
14089 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
14090
14091 /// The queue of implicit template instantiations that are required
14092 /// but have not yet been performed.
14093 std::deque<PendingImplicitInstantiation> PendingInstantiations;
14094
14095 /// Queue of implicit template instantiations that cannot be performed
14096 /// eagerly.
14097 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
14098
14099 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses;
14100 SmallVector<std::deque<PendingImplicitInstantiation>, 8>
14101 SavedPendingInstantiations;
14102
14103 /// The queue of implicit template instantiations that are required
14104 /// and must be performed within the current local scope.
14105 ///
14106 /// This queue is only used for member functions of local classes in
14107 /// templates, which must be instantiated in the same scope as their
14108 /// enclosing function, so that they can reference function-local
14109 /// types, static variables, enumerators, etc.
14110 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
14111
14112 class LocalEagerInstantiationScope {
14113 public:
14114 LocalEagerInstantiationScope(Sema &S, bool AtEndOfTU)
14115 : S(S), AtEndOfTU(AtEndOfTU) {
14116 SavedPendingLocalImplicitInstantiations.swap(
14117 x&: S.PendingLocalImplicitInstantiations);
14118 }
14119
14120 void perform() {
14121 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: true,
14122 /*AtEndOfTU=*/AtEndOfTU);
14123 }
14124
14125 ~LocalEagerInstantiationScope() {
14126 assert(S.PendingLocalImplicitInstantiations.empty() &&
14127 "there shouldn't be any pending local implicit instantiations");
14128 SavedPendingLocalImplicitInstantiations.swap(
14129 x&: S.PendingLocalImplicitInstantiations);
14130 }
14131
14132 LocalEagerInstantiationScope(const LocalEagerInstantiationScope &) = delete;
14133 LocalEagerInstantiationScope &
14134 operator=(const LocalEagerInstantiationScope &) = delete;
14135
14136 private:
14137 Sema &S;
14138 bool AtEndOfTU;
14139 std::deque<PendingImplicitInstantiation>
14140 SavedPendingLocalImplicitInstantiations;
14141 };
14142
14143 /// Records and restores the CurFPFeatures state on entry/exit of compound
14144 /// statements.
14145 class FPFeaturesStateRAII {
14146 public:
14147 FPFeaturesStateRAII(Sema &S);
14148 ~FPFeaturesStateRAII();
14149 FPFeaturesStateRAII(const FPFeaturesStateRAII &) = delete;
14150 FPFeaturesStateRAII &operator=(const FPFeaturesStateRAII &) = delete;
14151 FPOptionsOverride getOverrides() { return OldOverrides; }
14152
14153 private:
14154 Sema &S;
14155 FPOptions OldFPFeaturesState;
14156 FPOptionsOverride OldOverrides;
14157 LangOptions::FPEvalMethodKind OldEvalMethod;
14158 SourceLocation OldFPPragmaLocation;
14159 };
14160
14161 class GlobalEagerInstantiationScope {
14162 public:
14163 GlobalEagerInstantiationScope(Sema &S, bool Enabled, bool AtEndOfTU)
14164 : S(S), Enabled(Enabled), AtEndOfTU(AtEndOfTU) {
14165 if (!Enabled)
14166 return;
14167
14168 S.SavedPendingInstantiations.emplace_back();
14169 S.SavedPendingInstantiations.back().swap(x&: S.PendingInstantiations);
14170
14171 S.SavedVTableUses.emplace_back();
14172 S.SavedVTableUses.back().swap(RHS&: S.VTableUses);
14173 }
14174
14175 void perform() {
14176 if (Enabled) {
14177 S.DefineUsedVTables();
14178 S.PerformPendingInstantiations(/*LocalOnly=*/LocalOnly: false,
14179 /*AtEndOfTU=*/AtEndOfTU);
14180 }
14181 }
14182
14183 ~GlobalEagerInstantiationScope() {
14184 if (!Enabled)
14185 return;
14186
14187 // Restore the set of pending vtables.
14188 assert(S.VTableUses.empty() &&
14189 "VTableUses should be empty before it is discarded.");
14190 S.VTableUses.swap(RHS&: S.SavedVTableUses.back());
14191 S.SavedVTableUses.pop_back();
14192
14193 // Restore the set of pending implicit instantiations.
14194 if ((S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) &&
14195 AtEndOfTU) {
14196 assert(S.PendingInstantiations.empty() &&
14197 "PendingInstantiations should be empty before it is discarded.");
14198 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14199 S.SavedPendingInstantiations.pop_back();
14200 } else {
14201 // Template instantiations in the PCH may be delayed until the TU.
14202 S.PendingInstantiations.swap(x&: S.SavedPendingInstantiations.back());
14203 S.PendingInstantiations.insert(
14204 position: S.PendingInstantiations.end(),
14205 first: S.SavedPendingInstantiations.back().begin(),
14206 last: S.SavedPendingInstantiations.back().end());
14207 S.SavedPendingInstantiations.pop_back();
14208 }
14209 }
14210
14211 GlobalEagerInstantiationScope(const GlobalEagerInstantiationScope &) =
14212 delete;
14213 GlobalEagerInstantiationScope &
14214 operator=(const GlobalEagerInstantiationScope &) = delete;
14215
14216 private:
14217 Sema &S;
14218 bool Enabled;
14219 bool AtEndOfTU;
14220 };
14221
14222 ExplicitSpecifier instantiateExplicitSpecifier(
14223 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES);
14224
14225 struct LateInstantiatedAttribute {
14226 const Attr *TmplAttr;
14227 LocalInstantiationScope *Scope;
14228 Decl *NewDecl;
14229
14230 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
14231 Decl *D)
14232 : TmplAttr(A), Scope(S), NewDecl(D) {}
14233 };
14234 typedef SmallVector<LateInstantiatedAttribute, 1> LateInstantiatedAttrVec;
14235
14236 /// Recheck instantiated thread-safety attributes that could not be validated
14237 /// on the dependent pattern declaration.
14238 bool checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A);
14239
14240 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
14241 const Decl *Pattern, Decl *Inst,
14242 LateInstantiatedAttrVec *LateAttrs = nullptr,
14243 LocalInstantiationScope *OuterMostScope = nullptr);
14244
14245 /// Update instantiation attributes after template was late parsed.
14246 ///
14247 /// Some attributes are evaluated based on the body of template. If it is
14248 /// late parsed, such attributes cannot be evaluated when declaration is
14249 /// instantiated. This function is used to update instantiation attributes
14250 /// when template definition is ready.
14251 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst);
14252
14253 void
14254 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
14255 const Decl *Pattern, Decl *Inst,
14256 LateInstantiatedAttrVec *LateAttrs = nullptr,
14257 LocalInstantiationScope *OuterMostScope = nullptr);
14258
14259 /// In the MS ABI, we need to instantiate default arguments of dllexported
14260 /// default constructors along with the constructor definition. This allows IR
14261 /// gen to emit a constructor closure which calls the default constructor with
14262 /// its default arguments.
14263 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
14264
14265 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
14266 ParmVarDecl *Param);
14267 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
14268 FunctionDecl *Function);
14269
14270 /// Instantiate (or find existing instantiation of) a function template with a
14271 /// given set of template arguments.
14272 ///
14273 /// Usually this should not be used, and template argument deduction should be
14274 /// used in its place.
14275 FunctionDecl *InstantiateFunctionDeclaration(
14276 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args,
14277 SourceLocation Loc,
14278 CodeSynthesisContext::SynthesisKind CSC =
14279 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution);
14280
14281 /// Instantiate the definition of the given function from its
14282 /// template.
14283 ///
14284 /// \param PointOfInstantiation the point at which the instantiation was
14285 /// required. Note that this is not precisely a "point of instantiation"
14286 /// for the function, but it's close.
14287 ///
14288 /// \param Function the already-instantiated declaration of a
14289 /// function template specialization or member function of a class template
14290 /// specialization.
14291 ///
14292 /// \param Recursive if true, recursively instantiates any functions that
14293 /// are required by this instantiation.
14294 ///
14295 /// \param DefinitionRequired if true, then we are performing an explicit
14296 /// instantiation where the body of the function is required. Complain if
14297 /// there is no such body.
14298 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
14299 FunctionDecl *Function,
14300 bool Recursive = false,
14301 bool DefinitionRequired = false,
14302 bool AtEndOfTU = false);
14303 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
14304 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
14305 const TemplateArgumentList *PartialSpecArgs,
14306 SmallVectorImpl<TemplateArgument> &Converted,
14307 SourceLocation PointOfInstantiation,
14308 LateInstantiatedAttrVec *LateAttrs = nullptr,
14309 LocalInstantiationScope *StartingScope = nullptr);
14310
14311 /// Instantiates a variable template specialization by completing it
14312 /// with appropriate type information and initializer.
14313 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
14314 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
14315 const MultiLevelTemplateArgumentList &TemplateArgs);
14316
14317 /// BuildVariableInstantiation - Used after a new variable has been created.
14318 /// Sets basic variable data and decides whether to postpone the
14319 /// variable instantiation.
14320 void
14321 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
14322 const MultiLevelTemplateArgumentList &TemplateArgs,
14323 LateInstantiatedAttrVec *LateAttrs,
14324 DeclContext *Owner,
14325 LocalInstantiationScope *StartingScope,
14326 bool InstantiatingVarTemplate = false,
14327 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
14328
14329 /// Instantiate the initializer of a variable.
14330 void InstantiateVariableInitializer(
14331 VarDecl *Var, VarDecl *OldVar,
14332 const MultiLevelTemplateArgumentList &TemplateArgs);
14333
14334 /// Instantiate the definition of the given variable from its
14335 /// template.
14336 ///
14337 /// \param PointOfInstantiation the point at which the instantiation was
14338 /// required. Note that this is not precisely a "point of instantiation"
14339 /// for the variable, but it's close.
14340 ///
14341 /// \param Var the already-instantiated declaration of a templated variable.
14342 ///
14343 /// \param Recursive if true, recursively instantiates any functions that
14344 /// are required by this instantiation.
14345 ///
14346 /// \param DefinitionRequired if true, then we are performing an explicit
14347 /// instantiation where a definition of the variable is required. Complain
14348 /// if there is no such definition.
14349 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
14350 VarDecl *Var, bool Recursive = false,
14351 bool DefinitionRequired = false,
14352 bool AtEndOfTU = false);
14353
14354 void InstantiateMemInitializers(
14355 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl,
14356 const MultiLevelTemplateArgumentList &TemplateArgs);
14357
14358 /// Find the instantiation of the given declaration within the
14359 /// current instantiation.
14360 ///
14361 /// This routine is intended to be used when \p D is a declaration
14362 /// referenced from within a template, that needs to mapped into the
14363 /// corresponding declaration within an instantiation. For example,
14364 /// given:
14365 ///
14366 /// \code
14367 /// template<typename T>
14368 /// struct X {
14369 /// enum Kind {
14370 /// KnownValue = sizeof(T)
14371 /// };
14372 ///
14373 /// bool getKind() const { return KnownValue; }
14374 /// };
14375 ///
14376 /// template struct X<int>;
14377 /// \endcode
14378 ///
14379 /// In the instantiation of X<int>::getKind(), we need to map the \p
14380 /// EnumConstantDecl for \p KnownValue (which refers to
14381 /// X<T>::<Kind>::KnownValue) to its instantiation
14382 /// (X<int>::<Kind>::KnownValue).
14383 /// \p FindInstantiatedDecl performs this mapping from within the
14384 /// instantiation of X<int>.
14385 NamedDecl *
14386 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
14387 const MultiLevelTemplateArgumentList &TemplateArgs,
14388 bool FindingInstantiatedContext = false);
14389
14390 /// Finds the instantiation of the given declaration context
14391 /// within the current instantiation.
14392 ///
14393 /// \returns NULL if there was an error
14394 DeclContext *
14395 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
14396 const MultiLevelTemplateArgumentList &TemplateArgs);
14397
14398 Decl *SubstDecl(Decl *D, DeclContext *Owner,
14399 const MultiLevelTemplateArgumentList &TemplateArgs);
14400
14401 /// Substitute the name and return type of a defaulted 'operator<=>' to form
14402 /// an implicit 'operator=='.
14403 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
14404 FunctionDecl *Spaceship);
14405
14406 /// Performs template instantiation for all implicit template
14407 /// instantiations we have seen until this point.
14408 void PerformPendingInstantiations(bool LocalOnly = false,
14409 bool AtEndOfTU = true);
14410
14411 TemplateParameterList *
14412 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
14413 const MultiLevelTemplateArgumentList &TemplateArgs,
14414 bool EvaluateConstraints = true);
14415
14416 void PerformDependentDiagnostics(
14417 const DeclContext *Pattern,
14418 const MultiLevelTemplateArgumentList &TemplateArgs);
14419
14420private:
14421 /// Introduce the instantiated local variables into the local
14422 /// instantiation scope.
14423 void addInstantiatedLocalVarsToScope(FunctionDecl *Function,
14424 const FunctionDecl *PatternDecl,
14425 LocalInstantiationScope &Scope);
14426 /// Introduce the instantiated function parameters into the local
14427 /// instantiation scope, and set the parameter names to those used
14428 /// in the template.
14429 bool addInstantiatedParametersToScope(
14430 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14431 LocalInstantiationScope &Scope,
14432 const MultiLevelTemplateArgumentList &TemplateArgs);
14433
14434 /// Introduce the instantiated captures of the lambda into the local
14435 /// instantiation scope.
14436 bool addInstantiatedCapturesToScope(
14437 FunctionDecl *Function, const FunctionDecl *PatternDecl,
14438 LocalInstantiationScope &Scope,
14439 const MultiLevelTemplateArgumentList &TemplateArgs);
14440
14441 int ParsingClassDepth = 0;
14442
14443 class SavePendingParsedClassStateRAII {
14444 public:
14445 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
14446
14447 ~SavePendingParsedClassStateRAII() {
14448 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
14449 "there shouldn't be any pending delayed exception spec checks");
14450 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
14451 "there shouldn't be any pending delayed exception spec checks");
14452 swapSavedState();
14453 }
14454
14455 SavePendingParsedClassStateRAII(const SavePendingParsedClassStateRAII &) =
14456 delete;
14457 SavePendingParsedClassStateRAII &
14458 operator=(const SavePendingParsedClassStateRAII &) = delete;
14459
14460 private:
14461 Sema &S;
14462 decltype(DelayedOverridingExceptionSpecChecks)
14463 SavedOverridingExceptionSpecChecks;
14464 decltype(DelayedEquivalentExceptionSpecChecks)
14465 SavedEquivalentExceptionSpecChecks;
14466
14467 void swapSavedState() {
14468 SavedOverridingExceptionSpecChecks.swap(
14469 RHS&: S.DelayedOverridingExceptionSpecChecks);
14470 SavedEquivalentExceptionSpecChecks.swap(
14471 RHS&: S.DelayedEquivalentExceptionSpecChecks);
14472 }
14473 };
14474
14475 ///@}
14476
14477 //
14478 //
14479 // -------------------------------------------------------------------------
14480 //
14481 //
14482
14483 /// \name C++ Variadic Templates
14484 /// Implementations are in SemaTemplateVariadic.cpp
14485 ///@{
14486
14487public:
14488 /// Determine whether an unexpanded parameter pack might be permitted in this
14489 /// location. Useful for error recovery.
14490 bool isUnexpandedParameterPackPermitted();
14491
14492 /// The context in which an unexpanded parameter pack is
14493 /// being diagnosed.
14494 ///
14495 /// Note that the values of this enumeration line up with the first
14496 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
14497 enum UnexpandedParameterPackContext {
14498 /// An arbitrary expression.
14499 UPPC_Expression = 0,
14500
14501 /// The base type of a class type.
14502 UPPC_BaseType,
14503
14504 /// The type of an arbitrary declaration.
14505 UPPC_DeclarationType,
14506
14507 /// The type of a data member.
14508 UPPC_DataMemberType,
14509
14510 /// The size of a bit-field.
14511 UPPC_BitFieldWidth,
14512
14513 /// The expression in a static assertion.
14514 UPPC_StaticAssertExpression,
14515
14516 /// The fixed underlying type of an enumeration.
14517 UPPC_FixedUnderlyingType,
14518
14519 /// The enumerator value.
14520 UPPC_EnumeratorValue,
14521
14522 /// A using declaration.
14523 UPPC_UsingDeclaration,
14524
14525 /// A friend declaration.
14526 UPPC_FriendDeclaration,
14527
14528 /// A declaration qualifier.
14529 UPPC_DeclarationQualifier,
14530
14531 /// An initializer.
14532 UPPC_Initializer,
14533
14534 /// A default argument.
14535 UPPC_DefaultArgument,
14536
14537 /// The type of a non-type template parameter.
14538 UPPC_NonTypeTemplateParameterType,
14539
14540 /// The type of an exception.
14541 UPPC_ExceptionType,
14542
14543 /// Explicit specialization.
14544 UPPC_ExplicitSpecialization,
14545
14546 /// Partial specialization.
14547 UPPC_PartialSpecialization,
14548
14549 /// Microsoft __if_exists.
14550 UPPC_IfExists,
14551
14552 /// Microsoft __if_not_exists.
14553 UPPC_IfNotExists,
14554
14555 /// Lambda expression.
14556 UPPC_Lambda,
14557
14558 /// Block expression.
14559 UPPC_Block,
14560
14561 /// A type constraint.
14562 UPPC_TypeConstraint,
14563
14564 // A requirement in a requires-expression.
14565 UPPC_Requirement,
14566
14567 // A requires-clause.
14568 UPPC_RequiresClause,
14569 };
14570
14571 /// Diagnose unexpanded parameter packs.
14572 ///
14573 /// \param Loc The location at which we should emit the diagnostic.
14574 ///
14575 /// \param UPPC The context in which we are diagnosing unexpanded
14576 /// parameter packs.
14577 ///
14578 /// \param Unexpanded the set of unexpanded parameter packs.
14579 ///
14580 /// \returns true if an error occurred, false otherwise.
14581 bool DiagnoseUnexpandedParameterPacks(
14582 SourceLocation Loc, UnexpandedParameterPackContext UPPC,
14583 ArrayRef<UnexpandedParameterPack> Unexpanded);
14584
14585 /// If the given type contains an unexpanded parameter pack,
14586 /// diagnose the error.
14587 ///
14588 /// \param Loc The source location where a diagnostc should be emitted.
14589 ///
14590 /// \param T The type that is being checked for unexpanded parameter
14591 /// packs.
14592 ///
14593 /// \returns true if an error occurred, false otherwise.
14594 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
14595 UnexpandedParameterPackContext UPPC);
14596
14597 /// If the given expression contains an unexpanded parameter
14598 /// pack, diagnose the error.
14599 ///
14600 /// \param E The expression that is being checked for unexpanded
14601 /// parameter packs.
14602 ///
14603 /// \returns true if an error occurred, false otherwise.
14604 bool DiagnoseUnexpandedParameterPack(
14605 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression);
14606
14607 /// If the given requirees-expression contains an unexpanded reference to one
14608 /// of its own parameter packs, diagnose the error.
14609 ///
14610 /// \param RE The requiress-expression that is being checked for unexpanded
14611 /// parameter packs.
14612 ///
14613 /// \returns true if an error occurred, false otherwise.
14614 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
14615
14616 /// If the given nested-name-specifier contains an unexpanded
14617 /// parameter pack, diagnose the error.
14618 ///
14619 /// \param SS The nested-name-specifier that is being checked for
14620 /// unexpanded parameter packs.
14621 ///
14622 /// \returns true if an error occurred, false otherwise.
14623 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
14624 UnexpandedParameterPackContext UPPC);
14625
14626 /// If the given name contains an unexpanded parameter pack,
14627 /// diagnose the error.
14628 ///
14629 /// \param NameInfo The name (with source location information) that
14630 /// is being checked for unexpanded parameter packs.
14631 ///
14632 /// \returns true if an error occurred, false otherwise.
14633 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
14634 UnexpandedParameterPackContext UPPC);
14635
14636 /// If the given template name contains an unexpanded parameter pack,
14637 /// diagnose the error.
14638 ///
14639 /// \param Loc The location of the template name.
14640 ///
14641 /// \param Template The template name that is being checked for unexpanded
14642 /// parameter packs.
14643 ///
14644 /// \returns true if an error occurred, false otherwise.
14645 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
14646 TemplateName Template,
14647 UnexpandedParameterPackContext UPPC);
14648
14649 /// If the given template argument contains an unexpanded parameter
14650 /// pack, diagnose the error.
14651 ///
14652 /// \param Arg The template argument that is being checked for unexpanded
14653 /// parameter packs.
14654 ///
14655 /// \returns true if an error occurred, false otherwise.
14656 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
14657 UnexpandedParameterPackContext UPPC);
14658
14659 /// Collect the set of unexpanded parameter packs within the given
14660 /// template argument.
14661 ///
14662 /// \param Arg The template argument that will be traversed to find
14663 /// unexpanded parameter packs.
14664 void collectUnexpandedParameterPacks(
14665 TemplateArgument Arg,
14666 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14667
14668 /// Collect the set of unexpanded parameter packs within the given
14669 /// template argument.
14670 ///
14671 /// \param Arg The template argument that will be traversed to find
14672 /// unexpanded parameter packs.
14673 void collectUnexpandedParameterPacks(
14674 TemplateArgumentLoc Arg,
14675 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14676
14677 /// Collect the set of unexpanded parameter packs within the given
14678 /// type.
14679 ///
14680 /// \param T The type that will be traversed to find
14681 /// unexpanded parameter packs.
14682 void collectUnexpandedParameterPacks(
14683 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14684
14685 /// Collect the set of unexpanded parameter packs within the given
14686 /// type.
14687 ///
14688 /// \param TL The type that will be traversed to find
14689 /// unexpanded parameter packs.
14690 void collectUnexpandedParameterPacks(
14691 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14692
14693 /// Collect the set of unexpanded parameter packs within the given
14694 /// nested-name-specifier.
14695 ///
14696 /// \param NNS The nested-name-specifier that will be traversed to find
14697 /// unexpanded parameter packs.
14698 void collectUnexpandedParameterPacks(
14699 NestedNameSpecifierLoc NNS,
14700 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14701
14702 /// Collect the set of unexpanded parameter packs within the given
14703 /// name.
14704 ///
14705 /// \param NameInfo The name that will be traversed to find
14706 /// unexpanded parameter packs.
14707 void collectUnexpandedParameterPacks(
14708 const DeclarationNameInfo &NameInfo,
14709 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14710
14711 /// Collect the set of unexpanded parameter packs within the given
14712 /// expression.
14713 static void collectUnexpandedParameterPacks(
14714 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
14715
14716 /// Invoked when parsing a template argument.
14717 ///
14718 /// \param Arg the template argument, which may already be invalid.
14719 ///
14720 /// If it is followed by ellipsis, this function is called before
14721 /// `ActOnPackExpansion`.
14722 ParsedTemplateArgument
14723 ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg);
14724
14725 /// Invoked when parsing a template argument followed by an
14726 /// ellipsis, which creates a pack expansion.
14727 ///
14728 /// \param Arg The template argument preceding the ellipsis, which
14729 /// may already be invalid.
14730 ///
14731 /// \param EllipsisLoc The location of the ellipsis.
14732 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
14733 SourceLocation EllipsisLoc);
14734
14735 /// Invoked when parsing a type followed by an ellipsis, which
14736 /// creates a pack expansion.
14737 ///
14738 /// \param Type The type preceding the ellipsis, which will become
14739 /// the pattern of the pack expansion.
14740 ///
14741 /// \param EllipsisLoc The location of the ellipsis.
14742 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
14743
14744 /// Construct a pack expansion type from the pattern of the pack
14745 /// expansion.
14746 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
14747 SourceLocation EllipsisLoc,
14748 UnsignedOrNone NumExpansions);
14749
14750 /// Construct a pack expansion type from the pattern of the pack
14751 /// expansion.
14752 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
14753 SourceLocation EllipsisLoc,
14754 UnsignedOrNone NumExpansions);
14755
14756 /// Invoked when parsing an expression followed by an ellipsis, which
14757 /// creates a pack expansion.
14758 ///
14759 /// \param Pattern The expression preceding the ellipsis, which will become
14760 /// the pattern of the pack expansion.
14761 ///
14762 /// \param EllipsisLoc The location of the ellipsis.
14763 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
14764
14765 /// Invoked when parsing an expression followed by an ellipsis, which
14766 /// creates a pack expansion.
14767 ///
14768 /// \param Pattern The expression preceding the ellipsis, which will become
14769 /// the pattern of the pack expansion.
14770 ///
14771 /// \param EllipsisLoc The location of the ellipsis.
14772 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
14773 UnsignedOrNone NumExpansions);
14774
14775 /// Determine whether we could expand a pack expansion with the
14776 /// given set of parameter packs into separate arguments by repeatedly
14777 /// transforming the pattern.
14778 ///
14779 /// \param EllipsisLoc The location of the ellipsis that identifies the
14780 /// pack expansion.
14781 ///
14782 /// \param PatternRange The source range that covers the entire pattern of
14783 /// the pack expansion.
14784 ///
14785 /// \param Unexpanded The set of unexpanded parameter packs within the
14786 /// pattern.
14787 ///
14788 /// \param ShouldExpand Will be set to \c true if the transformer should
14789 /// expand the corresponding pack expansions into separate arguments. When
14790 /// set, \c NumExpansions must also be set.
14791 ///
14792 /// \param RetainExpansion Whether the caller should add an unexpanded
14793 /// pack expansion after all of the expanded arguments. This is used
14794 /// when extending explicitly-specified template argument packs per
14795 /// C++0x [temp.arg.explicit]p9.
14796 ///
14797 /// \param NumExpansions The number of separate arguments that will be in
14798 /// the expanded form of the corresponding pack expansion. This is both an
14799 /// input and an output parameter, which can be set by the caller if the
14800 /// number of expansions is known a priori (e.g., due to a prior substitution)
14801 /// and will be set by the callee when the number of expansions is known.
14802 /// The callee must set this value when \c ShouldExpand is \c true; it may
14803 /// set this value in other cases.
14804 ///
14805 /// \returns true if an error occurred (e.g., because the parameter packs
14806 /// are to be instantiated with arguments of different lengths), false
14807 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
14808 /// must be set.
14809 bool CheckParameterPacksForExpansion(
14810 SourceLocation EllipsisLoc, SourceRange PatternRange,
14811 ArrayRef<UnexpandedParameterPack> Unexpanded,
14812 const MultiLevelTemplateArgumentList &TemplateArgs,
14813 bool FailOnPackProducingTemplates, bool &ShouldExpand,
14814 bool &RetainExpansion, UnsignedOrNone &NumExpansions,
14815 bool Diagnose = true);
14816
14817 /// Determine the number of arguments in the given pack expansion
14818 /// type.
14819 ///
14820 /// This routine assumes that the number of arguments in the expansion is
14821 /// consistent across all of the unexpanded parameter packs in its pattern.
14822 ///
14823 /// Returns an empty Optional if the type can't be expanded.
14824 UnsignedOrNone getNumArgumentsInExpansion(
14825 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs);
14826
14827 UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(
14828 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
14829 const MultiLevelTemplateArgumentList &TemplateArgs);
14830
14831 /// Determine whether the given declarator contains any unexpanded
14832 /// parameter packs.
14833 ///
14834 /// This routine is used by the parser to disambiguate function declarators
14835 /// with an ellipsis prior to the ')', e.g.,
14836 ///
14837 /// \code
14838 /// void f(T...);
14839 /// \endcode
14840 ///
14841 /// To determine whether we have an (unnamed) function parameter pack or
14842 /// a variadic function.
14843 ///
14844 /// \returns true if the declarator contains any unexpanded parameter packs,
14845 /// false otherwise.
14846 bool containsUnexpandedParameterPacks(Declarator &D);
14847
14848 /// Returns the pattern of the pack expansion for a template argument.
14849 ///
14850 /// \param OrigLoc The template argument to expand.
14851 ///
14852 /// \param Ellipsis Will be set to the location of the ellipsis.
14853 ///
14854 /// \param NumExpansions Will be set to the number of expansions that will
14855 /// be generated from this pack expansion, if known a priori.
14856 TemplateArgumentLoc
14857 getTemplateArgumentPackExpansionPattern(TemplateArgumentLoc OrigLoc,
14858 SourceLocation &Ellipsis,
14859 UnsignedOrNone &NumExpansions) const;
14860
14861 /// Given a template argument that contains an unexpanded parameter pack, but
14862 /// which has already been substituted, attempt to determine the number of
14863 /// elements that will be produced once this argument is fully-expanded.
14864 ///
14865 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
14866 /// avoid actually expanding the pack where possible.
14867 UnsignedOrNone getFullyPackExpandedSize(TemplateArgument Arg);
14868
14869 /// Called when an expression computing the size of a parameter pack
14870 /// is parsed.
14871 ///
14872 /// \code
14873 /// template<typename ...Types> struct count {
14874 /// static const unsigned value = sizeof...(Types);
14875 /// };
14876 /// \endcode
14877 ///
14878 //
14879 /// \param OpLoc The location of the "sizeof" keyword.
14880 /// \param Name The name of the parameter pack whose size will be determined.
14881 /// \param NameLoc The source location of the name of the parameter pack.
14882 /// \param RParenLoc The location of the closing parentheses.
14883 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc,
14884 IdentifierInfo &Name,
14885 SourceLocation NameLoc,
14886 SourceLocation RParenLoc);
14887
14888 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
14889 SourceLocation EllipsisLoc,
14890 SourceLocation LSquareLoc, Expr *IndexExpr,
14891 SourceLocation RSquareLoc);
14892
14893 ExprResult BuildPackIndexingExpr(Expr *PackExpression,
14894 SourceLocation EllipsisLoc, Expr *IndexExpr,
14895 SourceLocation RSquareLoc,
14896 ArrayRef<Expr *> ExpandedExprs = {},
14897 bool FullySubstituted = false);
14898
14899 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
14900 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
14901 tok::TokenKind Operator,
14902 SourceLocation EllipsisLoc, Expr *RHS,
14903 SourceLocation RParenLoc);
14904 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
14905 SourceLocation LParenLoc, Expr *LHS,
14906 BinaryOperatorKind Operator,
14907 SourceLocation EllipsisLoc, Expr *RHS,
14908 SourceLocation RParenLoc,
14909 UnsignedOrNone NumExpansions);
14910 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
14911 BinaryOperatorKind Operator);
14912
14913 ///@}
14914
14915 //
14916 //
14917 // -------------------------------------------------------------------------
14918 //
14919 //
14920
14921 /// \name Constraints and Concepts
14922 /// Implementations are in SemaConcept.cpp
14923 ///@{
14924
14925public:
14926 ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI);
14927
14928 ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc,
14929 TypeSourceInfo *TSI);
14930
14931public:
14932 void PushSatisfactionStackEntry(const NamedDecl *D,
14933 const llvm::FoldingSetNodeID &ID) {
14934 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14935 SatisfactionStack.emplace_back(Args&: Can, Args: ID);
14936 }
14937
14938 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); }
14939
14940 bool SatisfactionStackContains(const NamedDecl *D,
14941 const llvm::FoldingSetNodeID &ID) const {
14942 const NamedDecl *Can = cast<NamedDecl>(Val: D->getCanonicalDecl());
14943 return llvm::is_contained(Range: SatisfactionStack,
14944 Element: SatisfactionStackEntryTy{Can, ID});
14945 }
14946
14947 using SatisfactionStackEntryTy =
14948 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>;
14949
14950 // Resets the current SatisfactionStack for cases where we are instantiating
14951 // constraints as a 'side effect' of normal instantiation in a way that is not
14952 // indicative of recursive definition.
14953 class SatisfactionStackResetRAII {
14954 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack;
14955 Sema &SemaRef;
14956
14957 public:
14958 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) {
14959 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14960 }
14961
14962 ~SatisfactionStackResetRAII() {
14963 SemaRef.SwapSatisfactionStack(NewSS&: BackupSatisfactionStack);
14964 }
14965
14966 SatisfactionStackResetRAII(const SatisfactionStackResetRAII &) = delete;
14967 SatisfactionStackResetRAII &
14968 operator=(const SatisfactionStackResetRAII &) = delete;
14969 };
14970
14971 void SwapSatisfactionStack(
14972 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) {
14973 SatisfactionStack.swap(RHS&: NewSS);
14974 }
14975
14976 using ConstrainedDeclOrNestedRequirement =
14977 llvm::PointerUnion<const NamedDecl *,
14978 const concepts::NestedRequirement *>;
14979
14980 /// Check whether the given expression is a valid constraint expression.
14981 /// A diagnostic is emitted if it is not, false is returned, and
14982 /// PossibleNonPrimary will be set to true if the failure might be due to a
14983 /// non-primary expression being used as an atomic constraint.
14984 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
14985 bool *PossibleNonPrimary = nullptr,
14986 bool IsTrailingRequiresClause = false);
14987
14988 /// \brief Check whether the given list of constraint expressions are
14989 /// satisfied (as if in a 'conjunction') given template arguments.
14990 /// \param Template the template-like entity that triggered the constraints
14991 /// check (either a concept or a constrained entity).
14992 /// \param ConstraintExprs a list of constraint expressions, treated as if
14993 /// they were 'AND'ed together.
14994 /// \param TemplateArgLists the list of template arguments to substitute into
14995 /// the constraint expression.
14996 /// \param TemplateIDRange The source range of the template id that
14997 /// caused the constraints check.
14998 /// \param Satisfaction if true is returned, will contain details of the
14999 /// satisfaction, with enough information to diagnose an unsatisfied
15000 /// expression.
15001 /// \returns true if an error occurred and satisfaction could not be checked,
15002 /// false otherwise.
15003 bool CheckConstraintSatisfaction(
15004 ConstrainedDeclOrNestedRequirement Entity,
15005 ArrayRef<AssociatedConstraint> AssociatedConstraints,
15006 const MultiLevelTemplateArgumentList &TemplateArgLists,
15007 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction,
15008 const ConceptReference *TopLevelConceptId = nullptr,
15009 Expr **ConvertedExpr = nullptr);
15010
15011 /// Check whether the given function decl's trailing requires clause is
15012 /// satisfied, if any. Returns false and updates Satisfaction with the
15013 /// satisfaction verdict if successful, emits a diagnostic and returns true if
15014 /// an error occurred and satisfaction could not be determined.
15015 ///
15016 /// \returns true if an error occurred, false otherwise.
15017 bool CheckFunctionConstraints(const FunctionDecl *FD,
15018 ConstraintSatisfaction &Satisfaction,
15019 SourceLocation UsageLoc = SourceLocation(),
15020 bool ForOverloadResolution = false);
15021
15022 // Calculates whether two constraint expressions are equal irrespective of a
15023 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
15024 // 'New', which are the "source" of the constraint, since this is necessary
15025 // for figuring out the relative 'depth' of the constraint. The depth of the
15026 // 'primary template' and the 'instantiated from' templates aren't necessarily
15027 // the same, such as a case when one is a 'friend' defined in a class.
15028 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
15029 const Expr *OldConstr,
15030 const TemplateCompareNewDeclInfo &New,
15031 const Expr *NewConstr);
15032
15033 // Calculates whether the friend function depends on an enclosing template for
15034 // the purposes of [temp.friend] p9.
15035 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
15036
15037 /// \brief Ensure that the given template arguments satisfy the constraints
15038 /// associated with the given template, emitting a diagnostic if they do not.
15039 ///
15040 /// \param Template The template to which the template arguments are being
15041 /// provided.
15042 ///
15043 /// \param TemplateArgs The converted, canonicalized template arguments.
15044 ///
15045 /// \param TemplateIDRange The source range of the template id that
15046 /// caused the constraints check.
15047 ///
15048 /// \returns true if the constrains are not satisfied or could not be checked
15049 /// for satisfaction, false if the constraints are satisfied.
15050 bool EnsureTemplateArgumentListConstraints(
15051 TemplateDecl *Template,
15052 const MultiLevelTemplateArgumentList &TemplateArgs,
15053 SourceRange TemplateIDRange);
15054
15055 bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation,
15056 FunctionDecl *Decl,
15057 ArrayRef<TemplateArgument> TemplateArgs,
15058 ConstraintSatisfaction &Satisfaction);
15059
15060 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15061 /// unsatisfied.
15062 /// \param First whether this is the first time an unsatisfied constraint is
15063 /// diagnosed for this error.
15064 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
15065 SourceLocation Loc = {},
15066 bool First = true);
15067
15068 /// \brief Emit diagnostics explaining why a constraint expression was deemed
15069 /// unsatisfied.
15070 void
15071 DiagnoseUnsatisfiedConstraint(const ConceptSpecializationExpr *ConstraintExpr,
15072 bool First = true);
15073
15074 const NormalizedConstraint *getNormalizedAssociatedConstraints(
15075 ConstrainedDeclOrNestedRequirement Entity,
15076 ArrayRef<AssociatedConstraint> AssociatedConstraints);
15077
15078 /// \brief Check whether the given declaration's associated constraints are
15079 /// at least as constrained than another declaration's according to the
15080 /// partial ordering of constraints.
15081 ///
15082 /// \param Result If no error occurred, receives the result of true if D1 is
15083 /// at least constrained than D2, and false otherwise.
15084 ///
15085 /// \returns true if an error occurred, false otherwise.
15086 bool IsAtLeastAsConstrained(const NamedDecl *D1,
15087 MutableArrayRef<AssociatedConstraint> AC1,
15088 const NamedDecl *D2,
15089 MutableArrayRef<AssociatedConstraint> AC2,
15090 bool &Result);
15091
15092 /// If D1 was not at least as constrained as D2, but would've been if a pair
15093 /// of atomic constraints involved had been declared in a concept and not
15094 /// repeated in two separate places in code.
15095 /// \returns true if such a diagnostic was emitted, false otherwise.
15096 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
15097 const NamedDecl *D1, ArrayRef<AssociatedConstraint> AC1,
15098 const NamedDecl *D2, ArrayRef<AssociatedConstraint> AC2);
15099
15100 /// Cache the satisfaction of an atomic constraint.
15101 /// The key is based on the unsubstituted expression and the parameter
15102 /// mapping. This lets us not substituting the mapping more than once,
15103 /// which is (very!) expensive.
15104 /// FIXME: this should be private.
15105 llvm::DenseMap<llvm::FoldingSetNodeID,
15106 UnsubstitutedConstraintSatisfactionCacheResult>
15107 UnsubstitutedConstraintSatisfactionCache;
15108
15109 /// Cache the instantiation results of template parameter mappings within
15110 /// concepts. Substituting into normalized concepts can be extremely expensive
15111 /// due to the redundancy of template parameters. This cache is intended for
15112 /// use by TemplateInstantiator to avoid redundant semantic checking.
15113 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
15114 *CurrentCachedTemplateArgs = nullptr;
15115
15116private:
15117 /// Caches pairs of template-like decls whose associated constraints were
15118 /// checked for subsumption and whether or not the first's constraints did in
15119 /// fact subsume the second's.
15120 llvm::DenseMap<std::pair<const NamedDecl *, const NamedDecl *>, bool>
15121 SubsumptionCache;
15122 /// Caches the normalized associated constraints of declarations (concepts or
15123 /// constrained declarations). If an error occurred while normalizing the
15124 /// associated constraints of the template or concept, nullptr will be cached
15125 /// here.
15126 llvm::DenseMap<ConstrainedDeclOrNestedRequirement, NormalizedConstraint *>
15127 NormalizationCache;
15128
15129 /// Cache whether the associated constraint of a declaration
15130 /// is satisfied.
15131 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
15132 SatisfactionCache;
15133
15134 // The current stack of constraint satisfactions, so we can exit-early.
15135 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack;
15136
15137 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the
15138 /// LocalInstantiationScope of the current non-lambda function. For lambdas,
15139 /// use LambdaScopeForCallOperatorInstantiationRAII.
15140 bool
15141 SetupConstraintScope(FunctionDecl *FD,
15142 std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15143 const MultiLevelTemplateArgumentList &MLTAL,
15144 LocalInstantiationScope &Scope);
15145
15146 /// Used during constraint checking, sets up the constraint template argument
15147 /// lists, and calls SetupConstraintScope to set up the
15148 /// LocalInstantiationScope to have the proper set of ParVarDecls configured.
15149 std::optional<MultiLevelTemplateArgumentList>
15150 SetupConstraintCheckingTemplateArgumentsAndScope(
15151 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs,
15152 LocalInstantiationScope &Scope);
15153
15154 ///@}
15155
15156 //
15157 //
15158 // -------------------------------------------------------------------------
15159 //
15160 //
15161
15162 /// \name Types
15163 /// Implementations are in SemaType.cpp
15164 ///@{
15165
15166public:
15167 /// A mapping that describes the nullability we've seen in each header file.
15168 FileNullabilityMap NullabilityMap;
15169
15170 static int getPrintable(int I) { return I; }
15171 static unsigned getPrintable(unsigned I) { return I; }
15172 static bool getPrintable(bool B) { return B; }
15173 static const char *getPrintable(const char *S) { return S; }
15174 static StringRef getPrintable(StringRef S) { return S; }
15175 static const std::string &getPrintable(const std::string &S) { return S; }
15176 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
15177 return II;
15178 }
15179 static DeclarationName getPrintable(DeclarationName N) { return N; }
15180 static QualType getPrintable(QualType T) { return T; }
15181 static SourceRange getPrintable(SourceRange R) { return R; }
15182 static SourceRange getPrintable(SourceLocation L) { return L; }
15183 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
15184 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); }
15185
15186 enum class CompleteTypeKind {
15187 /// Apply the normal rules for complete types. In particular,
15188 /// treat all sizeless types as incomplete.
15189 Normal,
15190
15191 /// Relax the normal rules for complete types so that they include
15192 /// sizeless built-in types.
15193 AcceptSizeless,
15194
15195 // FIXME: Eventually we should flip the default to Normal and opt in
15196 // to AcceptSizeless rather than opt out of it.
15197 Default = AcceptSizeless
15198 };
15199
15200 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
15201 const DeclSpec *DS = nullptr);
15202 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
15203 const DeclSpec *DS = nullptr);
15204
15205 /// Build a pointer type.
15206 ///
15207 /// \param T The type to which we'll be building a pointer.
15208 ///
15209 /// \param Loc The location of the entity whose type involves this
15210 /// pointer type or, if there is no such entity, the location of the
15211 /// type that will have pointer type.
15212 ///
15213 /// \param Entity The name of the entity that involves the pointer
15214 /// type, if known.
15215 ///
15216 /// \returns A suitable pointer type, if there are no
15217 /// errors. Otherwise, returns a NULL type.
15218 QualType BuildPointerType(QualType T, SourceLocation Loc,
15219 DeclarationName Entity);
15220
15221 /// Build a reference type.
15222 ///
15223 /// \param T The type to which we'll be building a reference.
15224 ///
15225 /// \param Loc The location of the entity whose type involves this
15226 /// reference type or, if there is no such entity, the location of the
15227 /// type that will have reference type.
15228 ///
15229 /// \param Entity The name of the entity that involves the reference
15230 /// type, if known.
15231 ///
15232 /// \returns A suitable reference type, if there are no
15233 /// errors. Otherwise, returns a NULL type.
15234 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc,
15235 DeclarationName Entity);
15236
15237 /// Build an array type.
15238 ///
15239 /// \param T The type of each element in the array.
15240 ///
15241 /// \param ASM C99 array size modifier (e.g., '*', 'static').
15242 ///
15243 /// \param ArraySize Expression describing the size of the array.
15244 ///
15245 /// \param Brackets The range from the opening '[' to the closing ']'.
15246 ///
15247 /// \param Entity The name of the entity that involves the array
15248 /// type, if known.
15249 ///
15250 /// \returns A suitable array type, if there are no errors. Otherwise,
15251 /// returns a NULL type.
15252 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize,
15253 unsigned Quals, SourceRange Brackets,
15254 DeclarationName Entity);
15255 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
15256
15257 /// Build an ext-vector type.
15258 ///
15259 /// Run the required checks for the extended vector type.
15260 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
15261 SourceLocation AttrLoc);
15262 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
15263 SourceLocation AttrLoc);
15264
15265 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
15266 Expr *CountExpr,
15267 bool CountInBytes,
15268 bool OrNull);
15269
15270 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an
15271 /// expression is uninstantiated. If instantiated it will apply the
15272 /// appropriate address space to the type. This function allows dependent
15273 /// template variables to be used in conjunction with the address_space
15274 /// attribute
15275 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
15276 SourceLocation AttrLoc);
15277
15278 /// Same as above, but constructs the AddressSpace index if not provided.
15279 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
15280 SourceLocation AttrLoc);
15281
15282 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
15283
15284 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
15285
15286 /// Build a function type.
15287 ///
15288 /// This routine checks the function type according to C++ rules and
15289 /// under the assumption that the result type and parameter types have
15290 /// just been instantiated from a template. It therefore duplicates
15291 /// some of the behavior of GetTypeForDeclarator, but in a much
15292 /// simpler form that is only suitable for this narrow use case.
15293 ///
15294 /// \param T The return type of the function.
15295 ///
15296 /// \param ParamTypes The parameter types of the function. This array
15297 /// will be modified to account for adjustments to the types of the
15298 /// function parameters.
15299 ///
15300 /// \param Loc The location of the entity whose type involves this
15301 /// function type or, if there is no such entity, the location of the
15302 /// type that will have function type.
15303 ///
15304 /// \param Entity The name of the entity that involves the function
15305 /// type, if known.
15306 ///
15307 /// \param EPI Extra information about the function type. Usually this will
15308 /// be taken from an existing function with the same prototype.
15309 ///
15310 /// \returns A suitable function type, if there are no errors. The
15311 /// unqualified type will always be a FunctionProtoType.
15312 /// Otherwise, returns a NULL type.
15313 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
15314 SourceLocation Loc, DeclarationName Entity,
15315 const FunctionProtoType::ExtProtoInfo &EPI);
15316
15317 /// Build a member pointer type \c T Class::*.
15318 ///
15319 /// \param T the type to which the member pointer refers.
15320 /// \param Class the class type into which the member pointer points.
15321 /// \param Loc the location where this type begins
15322 /// \param Entity the name of the entity that will have this member pointer
15323 /// type
15324 ///
15325 /// \returns a member pointer type, if successful, or a NULL type if there was
15326 /// an error.
15327 QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
15328 CXXRecordDecl *Cls, SourceLocation Loc,
15329 DeclarationName Entity);
15330
15331 /// Build a block pointer type.
15332 ///
15333 /// \param T The type to which we'll be building a block pointer.
15334 ///
15335 /// \param Loc The source location, used for diagnostics.
15336 ///
15337 /// \param Entity The name of the entity that involves the block pointer
15338 /// type, if known.
15339 ///
15340 /// \returns A suitable block pointer type, if there are no
15341 /// errors. Otherwise, returns a NULL type.
15342 QualType BuildBlockPointerType(QualType T, SourceLocation Loc,
15343 DeclarationName Entity);
15344
15345 /// Build a paren type including \p T.
15346 QualType BuildParenType(QualType T);
15347 QualType BuildAtomicType(QualType T, SourceLocation Loc);
15348
15349 /// Build a Read-only Pipe type.
15350 ///
15351 /// \param T The type to which we'll be building a Pipe.
15352 ///
15353 /// \param Loc We do not use it for now.
15354 ///
15355 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15356 /// a NULL type.
15357 QualType BuildReadPipeType(QualType T, SourceLocation Loc);
15358
15359 /// Build a Write-only Pipe type.
15360 ///
15361 /// \param T The type to which we'll be building a Pipe.
15362 ///
15363 /// \param Loc We do not use it for now.
15364 ///
15365 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns
15366 /// a NULL type.
15367 QualType BuildWritePipeType(QualType T, SourceLocation Loc);
15368
15369 /// Build a bit-precise integer type.
15370 ///
15371 /// \param IsUnsigned Boolean representing the signedness of the type.
15372 ///
15373 /// \param BitWidth Size of this int type in bits, or an expression
15374 /// representing that.
15375 ///
15376 /// \param Loc Location of the keyword.
15377 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
15378
15379 /// GetTypeForDeclarator - Convert the type for the specified
15380 /// declarator to Type instances.
15381 ///
15382 /// The result of this call will never be null, but the associated
15383 /// type may be a null type if there's an unrecoverable error.
15384 TypeSourceInfo *GetTypeForDeclarator(Declarator &D);
15385 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
15386
15387 /// Package the given type and TSI into a ParsedType.
15388 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
15389 static QualType GetTypeFromParser(ParsedType Ty,
15390 TypeSourceInfo **TInfo = nullptr);
15391
15392 TypeResult ActOnTypeName(Declarator &D);
15393
15394 // Check whether the size of array element of type \p EltTy is a multiple of
15395 // its alignment and return false if it isn't.
15396 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
15397
15398 void
15399 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
15400 SourceLocation FallbackLoc,
15401 SourceLocation ConstQualLoc = SourceLocation(),
15402 SourceLocation VolatileQualLoc = SourceLocation(),
15403 SourceLocation RestrictQualLoc = SourceLocation(),
15404 SourceLocation AtomicQualLoc = SourceLocation(),
15405 SourceLocation UnalignedQualLoc = SourceLocation());
15406
15407 /// Retrieve the keyword associated
15408 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
15409
15410 /// Adjust the calling convention of a method to be the ABI default if it
15411 /// wasn't specified explicitly. This handles method types formed from
15412 /// function type typedefs and typename template arguments.
15413 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
15414 bool IsCtorOrDtor, SourceLocation Loc);
15415
15416 // Check if there is an explicit attribute, but only look through parens.
15417 // The intent is to look for an attribute on the current declarator, but not
15418 // one that came from a typedef.
15419 bool hasExplicitCallingConv(QualType T);
15420
15421 /// Check whether a nullability type specifier can be added to the given
15422 /// type through some means not written in source (e.g. API notes).
15423 ///
15424 /// \param Type The type to which the nullability specifier will be
15425 /// added. On success, this type will be updated appropriately.
15426 ///
15427 /// \param Nullability The nullability specifier to add.
15428 ///
15429 /// \param DiagLoc The location to use for diagnostics.
15430 ///
15431 /// \param AllowArrayTypes Whether to accept nullability specifiers on an
15432 /// array type (e.g., because it will decay to a pointer).
15433 ///
15434 /// \param OverrideExisting Whether to override an existing, locally-specified
15435 /// nullability specifier rather than complaining about the conflict.
15436 ///
15437 /// \returns true if nullability cannot be applied, false otherwise.
15438 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type,
15439 NullabilityKind Nullability,
15440 SourceLocation DiagLoc,
15441 bool AllowArrayTypes,
15442 bool OverrideExisting);
15443
15444 /// Check whether the given variable declaration has a size that fits within
15445 /// the address space it is declared in. This issues a diagnostic if not.
15446 ///
15447 /// \param VD The variable declaration to check the size of.
15448 ///
15449 /// \param AS The address space to check the size of \p VD against.
15450 ///
15451 /// \returns true if the variable's size fits within the address space, false
15452 /// otherwise.
15453 bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS);
15454
15455 /// Get the type of expression E, triggering instantiation to complete the
15456 /// type if necessary -- that is, if the expression refers to a templated
15457 /// static data member of incomplete array type.
15458 ///
15459 /// May still return an incomplete type if instantiation was not possible or
15460 /// if the type is incomplete for a different reason. Use
15461 /// RequireCompleteExprType instead if a diagnostic is expected for an
15462 /// incomplete expression type.
15463 QualType getCompletedType(Expr *E);
15464
15465 void completeExprArrayBound(Expr *E);
15466
15467 /// Ensure that the type of the given expression is complete.
15468 ///
15469 /// This routine checks whether the expression \p E has a complete type. If
15470 /// the expression refers to an instantiable construct, that instantiation is
15471 /// performed as needed to complete its type. Furthermore
15472 /// Sema::RequireCompleteType is called for the expression's type (or in the
15473 /// case of a reference type, the referred-to type).
15474 ///
15475 /// \param E The expression whose type is required to be complete.
15476 /// \param Kind Selects which completeness rules should be applied.
15477 /// \param Diagnoser The object that will emit a diagnostic if the type is
15478 /// incomplete.
15479 ///
15480 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
15481 /// otherwise.
15482 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
15483 TypeDiagnoser &Diagnoser);
15484 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
15485
15486 template <typename... Ts>
15487 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
15488 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15489 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
15490 }
15491
15492 // Returns the underlying type of a decltype with the given expression.
15493 QualType getDecltypeForExpr(Expr *E);
15494
15495 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
15496 /// If AsUnevaluated is false, E is treated as though it were an evaluated
15497 /// context, such as when building a type for decltype(auto).
15498 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
15499
15500 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
15501 SourceLocation Loc,
15502 SourceLocation EllipsisLoc);
15503 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
15504 SourceLocation Loc, SourceLocation EllipsisLoc,
15505 bool FullySubstituted = false,
15506 ArrayRef<QualType> Expansions = {});
15507
15508 using UTTKind = UnaryTransformType::UTTKind;
15509 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
15510 SourceLocation Loc);
15511 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
15512 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
15513 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
15514 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
15515 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
15516 SourceLocation Loc);
15517 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
15518 SourceLocation Loc);
15519 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
15520 SourceLocation Loc);
15521
15522 QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc) {
15523 return BuiltinRemoveReference(BaseType, UKind: UTTKind::RemoveCVRef, Loc);
15524 }
15525
15526 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
15527 SourceLocation Loc);
15528 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
15529 SourceLocation Loc);
15530
15531 bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT);
15532
15533 /// Ensure that the type T is a literal type.
15534 ///
15535 /// This routine checks whether the type @p T is a literal type. If @p T is an
15536 /// incomplete type, an attempt is made to complete it. If @p T is a literal
15537 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
15538 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
15539 /// it the type @p T), along with notes explaining why the type is not a
15540 /// literal type, and returns true.
15541 ///
15542 /// @param Loc The location in the source that the non-literal type
15543 /// diagnostic should refer to.
15544 ///
15545 /// @param T The type that this routine is examining for literalness.
15546 ///
15547 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
15548 ///
15549 /// @returns @c true if @p T is not a literal type and a diagnostic was
15550 /// emitted, @c false otherwise.
15551 bool RequireLiteralType(SourceLocation Loc, QualType T,
15552 TypeDiagnoser &Diagnoser);
15553 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
15554
15555 template <typename... Ts>
15556 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
15557 const Ts &...Args) {
15558 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15559 return RequireLiteralType(Loc, T, Diagnoser);
15560 }
15561
15562 bool isCompleteType(SourceLocation Loc, QualType T,
15563 CompleteTypeKind Kind = CompleteTypeKind::Default) {
15564 return !RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: nullptr);
15565 }
15566
15567 /// Ensure that the type T is a complete type.
15568 ///
15569 /// This routine checks whether the type @p T is complete in any
15570 /// context where a complete type is required. If @p T is a complete
15571 /// type, returns false. If @p T is a class template specialization,
15572 /// this routine then attempts to perform class template
15573 /// instantiation. If instantiation fails, or if @p T is incomplete
15574 /// and cannot be completed, issues the diagnostic @p diag (giving it
15575 /// the type @p T) and returns true.
15576 ///
15577 /// @param Loc The location in the source that the incomplete type
15578 /// diagnostic should refer to.
15579 ///
15580 /// @param T The type that this routine is examining for completeness.
15581 ///
15582 /// @param Kind Selects which completeness rules should be applied.
15583 ///
15584 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
15585 /// @c false otherwise.
15586 bool RequireCompleteType(SourceLocation Loc, QualType T,
15587 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
15588 bool RequireCompleteType(SourceLocation Loc, QualType T,
15589 CompleteTypeKind Kind, unsigned DiagID);
15590
15591 bool RequireCompleteType(SourceLocation Loc, QualType T,
15592 TypeDiagnoser &Diagnoser) {
15593 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, Diagnoser);
15594 }
15595 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
15596 return RequireCompleteType(Loc, T, Kind: CompleteTypeKind::Default, DiagID);
15597 }
15598
15599 template <typename... Ts>
15600 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
15601 const Ts &...Args) {
15602 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
15603 return RequireCompleteType(Loc, T, Diagnoser);
15604 }
15605
15606 /// Determine whether a declaration is visible to name lookup.
15607 bool isVisible(const NamedDecl *D) {
15608 return D->isUnconditionallyVisible() ||
15609 isAcceptableSlow(D, Kind: AcceptableKind::Visible);
15610 }
15611
15612 /// Determine whether a declaration is reachable.
15613 bool isReachable(const NamedDecl *D) {
15614 // All visible declarations are reachable.
15615 return D->isUnconditionallyVisible() ||
15616 isAcceptableSlow(D, Kind: AcceptableKind::Reachable);
15617 }
15618
15619 /// Determine whether a declaration is acceptable (visible/reachable).
15620 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
15621 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
15622 }
15623
15624 /// Determine if \p D and \p Suggested have a structurally compatible
15625 /// layout as described in C11 6.2.7/1.
15626 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
15627
15628 /// Determine if \p D has a visible definition. If not, suggest a declaration
15629 /// that should be made visible to expose the definition.
15630 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
15631 bool OnlyNeedComplete = false);
15632 bool hasVisibleDefinition(const NamedDecl *D) {
15633 NamedDecl *Hidden;
15634 return hasVisibleDefinition(D: const_cast<NamedDecl *>(D), Suggested: &Hidden);
15635 }
15636 /// Determine if \p D has a definition which allows we redefine it in current
15637 /// TU. \p Suggested is the definition that should be made visible to expose
15638 /// the definition.
15639 bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested,
15640 bool &Visible);
15641 bool isRedefinitionAllowedFor(const NamedDecl *D, bool &Visible) {
15642 NamedDecl *Hidden;
15643 return isRedefinitionAllowedFor(D: const_cast<NamedDecl *>(D), Suggested: &Hidden,
15644 Visible);
15645 }
15646
15647 /// Determine if \p D has a reachable definition. If not, suggest a
15648 /// declaration that should be made reachable to expose the definition.
15649 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
15650 bool OnlyNeedComplete = false);
15651 bool hasReachableDefinition(NamedDecl *D) {
15652 NamedDecl *Hidden;
15653 return hasReachableDefinition(D, Suggested: &Hidden);
15654 }
15655
15656 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
15657 AcceptableKind Kind,
15658 bool OnlyNeedComplete = false);
15659 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
15660 NamedDecl *Hidden;
15661 return hasAcceptableDefinition(D, Suggested: &Hidden, Kind);
15662 }
15663
15664 /// Try to parse the conditional expression attached to an effect attribute
15665 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty
15666 /// optional on error.
15667 std::optional<FunctionEffectMode>
15668 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName);
15669
15670 void ActOnCleanupAttr(Decl *D, const Attr *A);
15671 void ActOnInitPriorityAttr(Decl *D, const Attr *A);
15672
15673private:
15674 /// The implementation of RequireCompleteType
15675 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
15676 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
15677
15678 /// Nullability type specifiers.
15679 IdentifierInfo *Ident__Nonnull = nullptr;
15680 IdentifierInfo *Ident__Nullable = nullptr;
15681 IdentifierInfo *Ident__Nullable_result = nullptr;
15682 IdentifierInfo *Ident__Null_unspecified = nullptr;
15683
15684 ///@}
15685
15686 //
15687 //
15688 // -------------------------------------------------------------------------
15689 //
15690 //
15691
15692 /// \name FixIt Helpers
15693 /// Implementations are in SemaFixItUtils.cpp
15694 ///@{
15695
15696public:
15697 /// Get a string to suggest for zero-initialization of a type.
15698 std::string getFixItZeroInitializerForType(QualType T,
15699 SourceLocation Loc) const;
15700 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
15701
15702 ///@}
15703
15704 //
15705 //
15706 // -------------------------------------------------------------------------
15707 //
15708 //
15709
15710 /// \name Function Effects
15711 /// Implementations are in SemaFunctionEffects.cpp
15712 ///@{
15713public:
15714 struct FunctionEffectDiff {
15715 enum class Kind { Added, Removed, ConditionMismatch };
15716
15717 FunctionEffect::Kind EffectKind;
15718 Kind DiffKind;
15719 std::optional<FunctionEffectWithCondition>
15720 Old; // Invalid when 'Kind' is 'Added'.
15721 std::optional<FunctionEffectWithCondition>
15722 New; // Invalid when 'Kind' is 'Removed'.
15723
15724 StringRef effectName() const {
15725 if (Old)
15726 return Old.value().Effect.name();
15727 return New.value().Effect.name();
15728 }
15729
15730 /// Describes the result of effects differing between a base class's virtual
15731 /// method and an overriding method in a subclass.
15732 enum class OverrideResult {
15733 NoAction,
15734 Warn,
15735 Merge // Merge missing effect from base to derived.
15736 };
15737
15738 /// Return true if adding or removing the effect as part of a type
15739 /// conversion should generate a diagnostic.
15740 bool shouldDiagnoseConversion(QualType SrcType,
15741 const FunctionEffectsRef &SrcFX,
15742 QualType DstType,
15743 const FunctionEffectsRef &DstFX) const;
15744
15745 /// Return true if adding or removing the effect in a redeclaration should
15746 /// generate a diagnostic.
15747 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction,
15748 const FunctionEffectsRef &OldFX,
15749 const FunctionDecl &NewFunction,
15750 const FunctionEffectsRef &NewFX) const;
15751
15752 /// Return true if adding or removing the effect in a C++ virtual method
15753 /// override should generate a diagnostic.
15754 OverrideResult shouldDiagnoseMethodOverride(
15755 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
15756 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const;
15757 };
15758
15759 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> {
15760 /// Caller should short-circuit by checking for equality first.
15761 FunctionEffectDiffVector(const FunctionEffectsRef &Old,
15762 const FunctionEffectsRef &New);
15763 };
15764
15765 /// All functions/lambdas/blocks which have bodies and which have a non-empty
15766 /// FunctionEffectsRef to be verified.
15767 SmallVector<const Decl *> DeclsWithEffectsToVerify;
15768
15769 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions
15770 /// are all null.
15771 FunctionEffectKindSet AllEffectsToVerify;
15772
15773public:
15774 /// Warn and return true if adding a function effect to a set would create a
15775 /// conflict.
15776 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
15777 const FunctionEffectWithCondition &EC,
15778 SourceLocation NewAttrLoc);
15779
15780 // Report a failure to merge function effects between declarations due to a
15781 // conflict.
15782 void
15783 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs,
15784 SourceLocation NewLoc,
15785 SourceLocation OldLoc);
15786
15787 /// Inline checks from the start of maybeAddDeclWithEffects, to
15788 /// minimize performance impact on code not using effects.
15789 template <class FuncOrBlockDecl>
15790 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) {
15791 if (Context.hasAnyFunctionEffects())
15792 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty())
15793 maybeAddDeclWithEffects(D, FX);
15794 }
15795
15796 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
15797 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15798
15799 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify.
15800 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);
15801
15802 void performFunctionEffectAnalysis(TranslationUnitDecl *TU);
15803
15804 ///@}
15805};
15806
15807DeductionFailureInfo
15808MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK,
15809 sema::TemplateDeductionInfo &Info);
15810
15811/// Contains a late templated function.
15812/// Will be parsed at the end of the translation unit, used by Sema & Parser.
15813struct LateParsedTemplate {
15814 CachedTokens Toks;
15815 /// The template function declaration to be late parsed.
15816 Decl *D;
15817 /// Floating-point options in the point of definition.
15818 FPOptions FPO;
15819};
15820
15821template <>
15822void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
15823 PragmaMsStackAction Action,
15824 llvm::StringRef StackSlotLabel,
15825 AlignPackInfo Value);
15826
15827} // end namespace clang
15828
15829#endif
15830