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/Basic/AttrSubjectMatchRules.h" 37 #include "clang/Basic/Builtins.h" 38 #include "clang/Basic/CapturedStmt.h" 39 #include "clang/Basic/Cuda.h" 40 #include "clang/Basic/DiagnosticSema.h" 41 #include "clang/Basic/ExceptionSpecificationType.h" 42 #include "clang/Basic/ExpressionTraits.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/Lambda.h" 45 #include "clang/Basic/LangOptions.h" 46 #include "clang/Basic/Module.h" 47 #include "clang/Basic/OpenCLOptions.h" 48 #include "clang/Basic/OperatorKinds.h" 49 #include "clang/Basic/PartialDiagnostic.h" 50 #include "clang/Basic/PragmaKinds.h" 51 #include "clang/Basic/SourceLocation.h" 52 #include "clang/Basic/Specifiers.h" 53 #include "clang/Basic/StackExhaustionHandler.h" 54 #include "clang/Basic/TemplateKinds.h" 55 #include "clang/Basic/TokenKinds.h" 56 #include "clang/Basic/TypeTraits.h" 57 #include "clang/Sema/AnalysisBasedWarnings.h" 58 #include "clang/Sema/Attr.h" 59 #include "clang/Sema/CleanupInfo.h" 60 #include "clang/Sema/DeclSpec.h" 61 #include "clang/Sema/ExternalSemaSource.h" 62 #include "clang/Sema/IdentifierResolver.h" 63 #include "clang/Sema/Ownership.h" 64 #include "clang/Sema/ParsedAttr.h" 65 #include "clang/Sema/Redeclaration.h" 66 #include "clang/Sema/Scope.h" 67 #include "clang/Sema/SemaBase.h" 68 #include "clang/Sema/TypoCorrection.h" 69 #include "clang/Sema/Weak.h" 70 #include "llvm/ADT/APInt.h" 71 #include "llvm/ADT/ArrayRef.h" 72 #include "llvm/ADT/BitmaskEnum.h" 73 #include "llvm/ADT/DenseMap.h" 74 #include "llvm/ADT/DenseSet.h" 75 #include "llvm/ADT/FloatingPointMode.h" 76 #include "llvm/ADT/FoldingSet.h" 77 #include "llvm/ADT/MapVector.h" 78 #include "llvm/ADT/PointerIntPair.h" 79 #include "llvm/ADT/PointerUnion.h" 80 #include "llvm/ADT/STLExtras.h" 81 #include "llvm/ADT/STLForwardCompat.h" 82 #include "llvm/ADT/STLFunctionalExtras.h" 83 #include "llvm/ADT/SetVector.h" 84 #include "llvm/ADT/SmallBitVector.h" 85 #include "llvm/ADT/SmallPtrSet.h" 86 #include "llvm/ADT/SmallSet.h" 87 #include "llvm/ADT/SmallVector.h" 88 #include "llvm/ADT/StringExtras.h" 89 #include "llvm/ADT/StringMap.h" 90 #include "llvm/ADT/TinyPtrVector.h" 91 #include "llvm/Support/Allocator.h" 92 #include "llvm/Support/Compiler.h" 93 #include "llvm/Support/Error.h" 94 #include "llvm/Support/ErrorHandling.h" 95 #include <cassert> 96 #include <climits> 97 #include <cstddef> 98 #include <cstdint> 99 #include <deque> 100 #include <functional> 101 #include <iterator> 102 #include <memory> 103 #include <optional> 104 #include <string> 105 #include <tuple> 106 #include <type_traits> 107 #include <utility> 108 #include <vector> 109 110 namespace llvm { 111 struct InlineAsmIdentifierInfo; 112 } // namespace llvm 113 114 namespace clang { 115 class ADLResult; 116 class APValue; 117 struct ASTConstraintSatisfaction; 118 class ASTConsumer; 119 class ASTContext; 120 class ASTDeclReader; 121 class ASTMutationListener; 122 class ASTReader; 123 class ASTWriter; 124 class CXXBasePath; 125 class CXXBasePaths; 126 class CXXFieldCollector; 127 class CodeCompleteConsumer; 128 enum class ComparisonCategoryType : unsigned char; 129 class ConstraintSatisfaction; 130 class DarwinSDKInfo; 131 class DeclGroupRef; 132 class DeducedTemplateArgument; 133 struct DeductionFailureInfo; 134 class DependentDiagnostic; 135 class Designation; 136 class IdentifierInfo; 137 class ImplicitConversionSequence; 138 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; 139 class InitializationKind; 140 class InitializationSequence; 141 class InitializedEntity; 142 enum class LangAS : unsigned int; 143 class LocalInstantiationScope; 144 class LookupResult; 145 class MangleNumberingContext; 146 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; 147 class ModuleLoader; 148 class MultiLevelTemplateArgumentList; 149 struct NormalizedConstraint; 150 class ObjCInterfaceDecl; 151 class ObjCMethodDecl; 152 struct OverloadCandidate; 153 enum class OverloadCandidateParamOrder : char; 154 enum OverloadCandidateRewriteKind : unsigned; 155 class OverloadCandidateSet; 156 class Preprocessor; 157 class SemaAMDGPU; 158 class SemaARM; 159 class SemaAVR; 160 class SemaBPF; 161 class SemaCodeCompletion; 162 class SemaCUDA; 163 class SemaHLSL; 164 class SemaHexagon; 165 class SemaLoongArch; 166 class SemaM68k; 167 class SemaMIPS; 168 class SemaMSP430; 169 class SemaNVPTX; 170 class SemaObjC; 171 class SemaOpenACC; 172 class SemaOpenCL; 173 class SemaOpenMP; 174 class SemaPPC; 175 class SemaPseudoObject; 176 class SemaRISCV; 177 class SemaSPIRV; 178 class SemaSYCL; 179 class SemaSwift; 180 class SemaSystemZ; 181 class SemaWasm; 182 class SemaX86; 183 class StandardConversionSequence; 184 class TemplateArgument; 185 class TemplateArgumentLoc; 186 class TemplateInstantiationCallback; 187 class TemplatePartialOrderingContext; 188 class TemplateSpecCandidateSet; 189 class Token; 190 class TypeConstraint; 191 class TypoCorrectionConsumer; 192 class UnresolvedSetImpl; 193 class UnresolvedSetIterator; 194 class VisibleDeclConsumer; 195 196 namespace sema { 197 class BlockScopeInfo; 198 class Capture; 199 class CapturedRegionScopeInfo; 200 class CapturingScopeInfo; 201 class CompoundScopeInfo; 202 class DelayedDiagnostic; 203 class DelayedDiagnosticPool; 204 class FunctionScopeInfo; 205 class LambdaScopeInfo; 206 class SemaPPCallbacks; 207 class TemplateDeductionInfo; 208 } // namespace sema 209 210 // AssignmentAction - This is used by all the assignment diagnostic functions 211 // to represent what is actually causing the operation 212 enum class AssignmentAction { 213 Assigning, 214 Passing, 215 Returning, 216 Converting, 217 Initializing, 218 Sending, 219 Casting, 220 Passing_CFAudited 221 }; 222 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, 223 const AssignmentAction &AA) { 224 DB << llvm::to_underlying(AA); 225 return DB; 226 } 227 228 namespace threadSafety { 229 class BeforeSet; 230 void threadSafetyCleanup(BeforeSet *Cache); 231 } // namespace threadSafety 232 233 // FIXME: No way to easily map from TemplateTypeParmTypes to 234 // TemplateTypeParmDecls, so we have this horrible PointerUnion. 235 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *, 236 ResolvedUnexpandedPackExpr *>, 237 SourceLocation> 238 UnexpandedParameterPack; 239 240 /// Describes whether we've seen any nullability information for the given 241 /// file. 242 struct 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. 260 class 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 270 public: 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. 292 class PreferredTypeBuilder { 293 public: 294 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} 295 296 void enterCondition(Sema &S, SourceLocation Tok); 297 void enterReturn(Sema &S, SourceLocation Tok); 298 void enterVariableInit(SourceLocation Tok, Decl *D); 299 /// Handles e.g. BaseType{ .D = Tok... 300 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, 301 const Designation &D); 302 /// Computing a type for the function argument may require running 303 /// overloading, so we postpone its computation until it is actually needed. 304 /// 305 /// Clients should be very careful when using this function, as it stores a 306 /// function_ref, clients should make sure all calls to get() with the same 307 /// location happen while function_ref is alive. 308 /// 309 /// The callback should also emit signature help as a side-effect, but only 310 /// if the completion point has been reached. 311 void enterFunctionArgument(SourceLocation Tok, 312 llvm::function_ref<QualType()> ComputeType); 313 314 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); 315 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, 316 SourceLocation OpLoc); 317 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); 318 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); 319 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); 320 /// Handles all type casts, including C-style cast, C++ casts, etc. 321 void enterTypeCast(SourceLocation Tok, QualType CastType); 322 323 /// Get the expected type associated with this location, if any. 324 /// 325 /// If the location is a function argument, determining the expected type 326 /// involves considering all function overloads and the arguments so far. 327 /// In this case, signature help for these function overloads will be reported 328 /// as a side-effect (only if the completion point has been reached). 329 QualType get(SourceLocation Tok) const { 330 if (!Enabled || Tok != ExpectedLoc) 331 return QualType(); 332 if (!Type.isNull()) 333 return Type; 334 if (ComputeType) 335 return ComputeType(); 336 return QualType(); 337 } 338 339 private: 340 bool Enabled; 341 /// Start position of a token for which we store expected type. 342 SourceLocation ExpectedLoc; 343 /// Expected type for a token starting at ExpectedLoc. 344 QualType Type; 345 /// A function to compute expected type at ExpectedLoc. It is only considered 346 /// if Type is null. 347 llvm::function_ref<QualType()> ComputeType; 348 }; 349 350 struct SkipBodyInfo { 351 SkipBodyInfo() = default; 352 bool ShouldSkip = false; 353 bool CheckSameAsPrevious = false; 354 NamedDecl *Previous = nullptr; 355 NamedDecl *New = nullptr; 356 }; 357 358 /// Describes the result of template argument deduction. 359 /// 360 /// The TemplateDeductionResult enumeration describes the result of 361 /// template argument deduction, as returned from 362 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 363 /// structure provides additional information about the results of 364 /// template argument deduction, e.g., the deduced template argument 365 /// list (if successful) or the specific template parameters or 366 /// deduced arguments that were involved in the failure. 367 enum class TemplateDeductionResult { 368 /// Template argument deduction was successful. 369 Success = 0, 370 /// The declaration was invalid; do nothing. 371 Invalid, 372 /// Template argument deduction exceeded the maximum template 373 /// instantiation depth (which has already been diagnosed). 374 InstantiationDepth, 375 /// Template argument deduction did not deduce a value 376 /// for every template parameter. 377 Incomplete, 378 /// Template argument deduction did not deduce a value for every 379 /// expansion of an expanded template parameter pack. 380 IncompletePack, 381 /// Template argument deduction produced inconsistent 382 /// deduced values for the given template parameter. 383 Inconsistent, 384 /// Template argument deduction failed due to inconsistent 385 /// cv-qualifiers on a template parameter type that would 386 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 387 /// but were given a non-const "X". 388 Underqualified, 389 /// Substitution of the deduced template argument values 390 /// resulted in an error. 391 SubstitutionFailure, 392 /// After substituting deduced template arguments, a dependent 393 /// parameter type did not match the corresponding argument. 394 DeducedMismatch, 395 /// After substituting deduced template arguments, an element of 396 /// a dependent parameter type did not match the corresponding element 397 /// of the corresponding argument (when deducing from an initializer list). 398 DeducedMismatchNested, 399 /// A non-depnedent component of the parameter did not match the 400 /// corresponding component of the argument. 401 NonDeducedMismatch, 402 /// When performing template argument deduction for a function 403 /// template, there were too many call arguments. 404 TooManyArguments, 405 /// When performing template argument deduction for a function 406 /// template, there were too few call arguments. 407 TooFewArguments, 408 /// The explicitly-specified template arguments were not valid 409 /// template arguments for the given template. 410 InvalidExplicitArguments, 411 /// Checking non-dependent argument conversions failed. 412 NonDependentConversionFailure, 413 /// The deduced arguments did not satisfy the constraints associated 414 /// with the template. 415 ConstraintsNotSatisfied, 416 /// Deduction failed; that's all we know. 417 MiscellaneousDeductionFailure, 418 /// CUDA Target attributes do not match. 419 CUDATargetMismatch, 420 /// Some error which was already diagnosed. 421 AlreadyDiagnosed 422 }; 423 424 /// Kinds of C++ special members. 425 enum class CXXSpecialMemberKind { 426 DefaultConstructor, 427 CopyConstructor, 428 MoveConstructor, 429 CopyAssignment, 430 MoveAssignment, 431 Destructor, 432 Invalid 433 }; 434 435 /// The kind of conversion being performed. 436 enum class CheckedConversionKind { 437 /// An implicit conversion. 438 Implicit, 439 /// A C-style cast. 440 CStyleCast, 441 /// A functional-style cast. 442 FunctionalCast, 443 /// A cast other than a C-style cast. 444 OtherCast, 445 /// A conversion for an operand of a builtin overloaded operator. 446 ForBuiltinOverloadedOp 447 }; 448 449 enum class TagUseKind { 450 Reference, // Reference to a tag: 'struct foo *X;' 451 Declaration, // Fwd decl of a tag: 'struct foo;' 452 Definition, // Definition of a tag: 'struct foo { int X; } Y;' 453 Friend // Friend declaration: 'friend struct foo;' 454 }; 455 456 /// Used with attributes/effects with a boolean condition, e.g. `nonblocking`. 457 enum class FunctionEffectMode : uint8_t { 458 None, // effect is not present. 459 False, // effect(false). 460 True, // effect(true). 461 Dependent // effect(expr) where expr is dependent. 462 }; 463 464 /// Sema - This implements semantic analysis and AST building for C. 465 /// \nosubgrouping 466 class Sema final : public SemaBase { 467 // Table of Contents 468 // ----------------- 469 // 1. Semantic Analysis (Sema.cpp) 470 // 2. API Notes (SemaAPINotes.cpp) 471 // 3. C++ Access Control (SemaAccess.cpp) 472 // 4. Attributes (SemaAttr.cpp) 473 // 5. Availability Attribute Handling (SemaAvailability.cpp) 474 // 6. Bounds Safety (SemaBoundsSafety.cpp) 475 // 7. Casts (SemaCast.cpp) 476 // 8. Extra Semantic Checking (SemaChecking.cpp) 477 // 9. C++ Coroutines (SemaCoroutine.cpp) 478 // 10. C++ Scope Specifiers (SemaCXXScopeSpec.cpp) 479 // 11. Declarations (SemaDecl.cpp) 480 // 12. Declaration Attribute Handling (SemaDeclAttr.cpp) 481 // 13. C++ Declarations (SemaDeclCXX.cpp) 482 // 14. C++ Exception Specifications (SemaExceptionSpec.cpp) 483 // 15. Expressions (SemaExpr.cpp) 484 // 16. C++ Expressions (SemaExprCXX.cpp) 485 // 17. Member Access Expressions (SemaExprMember.cpp) 486 // 18. Initializers (SemaInit.cpp) 487 // 19. C++ Lambda Expressions (SemaLambda.cpp) 488 // 20. Name Lookup (SemaLookup.cpp) 489 // 21. Modules (SemaModule.cpp) 490 // 22. C++ Overloading (SemaOverload.cpp) 491 // 23. Statements (SemaStmt.cpp) 492 // 24. `inline asm` Statement (SemaStmtAsm.cpp) 493 // 25. Statement Attribute Handling (SemaStmtAttr.cpp) 494 // 26. C++ Templates (SemaTemplate.cpp) 495 // 27. C++ Template Argument Deduction (SemaTemplateDeduction.cpp) 496 // 28. C++ Template Deduction Guide (SemaTemplateDeductionGuide.cpp) 497 // 29. C++ Template Instantiation (SemaTemplateInstantiate.cpp) 498 // 30. C++ Template Declaration Instantiation 499 // (SemaTemplateInstantiateDecl.cpp) 500 // 31. C++ Variadic Templates (SemaTemplateVariadic.cpp) 501 // 32. Constraints and Concepts (SemaConcept.cpp) 502 // 33. Types (SemaType.cpp) 503 // 34. FixIt Helpers (SemaFixItUtils.cpp) 504 // 35. Function Effects (SemaFunctionEffects.cpp) 505 506 /// \name Semantic Analysis 507 /// Implementations are in Sema.cpp 508 ///@{ 509 510 public: 511 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 512 TranslationUnitKind TUKind = TU_Complete, 513 CodeCompleteConsumer *CompletionConsumer = nullptr); 514 ~Sema(); 515 516 /// Perform initialization that occurs after the parser has been 517 /// initialized but before it parses anything. 518 void Initialize(); 519 520 /// This virtual key function only exists to limit the emission of debug info 521 /// describing the Sema class. GCC and Clang only emit debug info for a class 522 /// with a vtable when the vtable is emitted. Sema is final and not 523 /// polymorphic, but the debug info size savings are so significant that it is 524 /// worth adding a vtable just to take advantage of this optimization. 525 virtual void anchor(); 526 527 const LangOptions &getLangOpts() const { return LangOpts; } 528 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } 529 FPOptions &getCurFPFeatures() { return CurFPFeatures; } 530 531 DiagnosticsEngine &getDiagnostics() const { return Diags; } 532 SourceManager &getSourceManager() const { return SourceMgr; } 533 Preprocessor &getPreprocessor() const { return PP; } 534 ASTContext &getASTContext() const { return Context; } 535 ASTConsumer &getASTConsumer() const { return Consumer; } 536 ASTMutationListener *getASTMutationListener() const; 537 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); } 538 539 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, 540 StringRef Platform); 541 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(); 542 543 /// Registers an external source. If an external source already exists, 544 /// creates a multiplex external source and appends to it. 545 /// 546 ///\param[in] E - A non-null external sema source. 547 /// 548 void addExternalSource(ExternalSemaSource *E); 549 550 /// Print out statistics about the semantic analysis. 551 void PrintStats() const; 552 553 /// Run some code with "sufficient" stack space. (Currently, at least 256K is 554 /// guaranteed). Produces a warning if we're low on stack space and allocates 555 /// more in that case. Use this in code that may recurse deeply (for example, 556 /// in template instantiation) to avoid stack overflow. 557 void runWithSufficientStackSpace(SourceLocation Loc, 558 llvm::function_ref<void()> Fn); 559 560 /// Returns default addr space for method qualifiers. 561 LangAS getDefaultCXXMethodAddrSpace() const; 562 563 /// Load weak undeclared identifiers from the external source. 564 void LoadExternalWeakUndeclaredIdentifiers(); 565 566 /// Determine if VD, which must be a variable or function, is an external 567 /// symbol that nonetheless can't be referenced from outside this translation 568 /// unit because its type has no linkage and it's not extern "C". 569 bool isExternalWithNoLinkageType(const ValueDecl *VD) const; 570 571 /// Obtain a sorted list of functions that are undefined but ODR-used. 572 void getUndefinedButUsed( 573 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation>> &Undefined); 574 575 typedef std::pair<SourceLocation, bool> DeleteExprLoc; 576 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; 577 /// Retrieves list of suspicious delete-expressions that will be checked at 578 /// the end of translation unit. 579 const llvm::MapVector<FieldDecl *, DeleteLocs> & 580 getMismatchingDeleteExpressions() const; 581 582 /// Cause the built diagnostic to be emitted on the DiagosticsEngine. 583 /// This is closely coupled to the SemaDiagnosticBuilder class and 584 /// should not be used elsewhere. 585 void EmitDiagnostic(unsigned DiagID, const DiagnosticBuilder &DB); 586 587 void addImplicitTypedef(StringRef Name, QualType T); 588 589 /// Whether uncompilable error has occurred. This includes error happens 590 /// in deferred diagnostics. 591 bool hasUncompilableErrorOccurred() const; 592 593 /// Looks through the macro-expansion chain for the given 594 /// location, looking for a macro expansion with the given name. 595 /// If one is found, returns true and sets the location to that 596 /// expansion loc. 597 bool findMacroSpelling(SourceLocation &loc, StringRef name); 598 599 /// Calls \c Lexer::getLocForEndOfToken() 600 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 601 602 /// Retrieve the module loader associated with the preprocessor. 603 ModuleLoader &getModuleLoader() const; 604 605 /// Invent a new identifier for parameters of abbreviated templates. 606 IdentifierInfo * 607 InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, 608 unsigned Index); 609 610 void emitAndClearUnusedLocalTypedefWarnings(); 611 612 // Emit all deferred diagnostics. 613 void emitDeferredDiags(); 614 615 enum TUFragmentKind { 616 /// The global module fragment, between 'module;' and a module-declaration. 617 Global, 618 /// A normal translation unit fragment. For a non-module unit, this is the 619 /// entire translation unit. Otherwise, it runs from the module-declaration 620 /// to the private-module-fragment (if any) or the end of the TU (if not). 621 Normal, 622 /// The private module fragment, between 'module :private;' and the end of 623 /// the translation unit. 624 Private 625 }; 626 627 /// This is called before the very first declaration in the translation unit 628 /// is parsed. Note that the ASTContext may have already injected some 629 /// declarations. 630 void ActOnStartOfTranslationUnit(); 631 /// ActOnEndOfTranslationUnit - This is called at the very end of the 632 /// translation unit when EOF is reached and all but the top-level scope is 633 /// popped. 634 void ActOnEndOfTranslationUnit(); 635 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); 636 637 /// Determines the active Scope associated with the given declaration 638 /// context. 639 /// 640 /// This routine maps a declaration context to the active Scope object that 641 /// represents that declaration context in the parser. It is typically used 642 /// from "scope-less" code (e.g., template instantiation, lazy creation of 643 /// declarations) that injects a name for name-lookup purposes and, therefore, 644 /// must update the Scope. 645 /// 646 /// \returns The scope corresponding to the given declaraion context, or NULL 647 /// if no such scope is open. 648 Scope *getScopeForContext(DeclContext *Ctx); 649 650 void PushFunctionScope(); 651 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 652 sema::LambdaScopeInfo *PushLambdaScope(); 653 654 /// This is used to inform Sema what the current TemplateParameterDepth 655 /// is during Parsing. Currently it is used to pass on the depth 656 /// when parsing generic lambda 'auto' parameters. 657 void RecordParsingTemplateParameterDepth(unsigned Depth); 658 659 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 660 RecordDecl *RD, CapturedRegionKind K, 661 unsigned OpenMPCaptureLevel = 0); 662 663 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short 664 /// time after they've been popped. 665 class PoppedFunctionScopeDeleter { 666 Sema *Self; 667 668 public: 669 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} 670 void operator()(sema::FunctionScopeInfo *Scope) const; 671 }; 672 673 using PoppedFunctionScopePtr = 674 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; 675 676 /// Pop a function (or block or lambda or captured region) scope from the 677 /// stack. 678 /// 679 /// \param WP The warning policy to use for CFG-based warnings, or null if 680 /// such warnings should not be produced. 681 /// \param D The declaration corresponding to this function scope, if 682 /// producing CFG-based warnings. 683 /// \param BlockType The type of the block expression, if D is a BlockDecl. 684 PoppedFunctionScopePtr 685 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 686 const Decl *D = nullptr, 687 QualType BlockType = QualType()); 688 689 sema::FunctionScopeInfo *getEnclosingFunction() const; 690 691 void setFunctionHasBranchIntoScope(); 692 void setFunctionHasBranchProtectedScope(); 693 void setFunctionHasIndirectGoto(); 694 void setFunctionHasMustTail(); 695 696 void PushCompoundScope(bool IsStmtExpr); 697 void PopCompoundScope(); 698 699 /// Determine whether any errors occurred within this function/method/ 700 /// block. 701 bool hasAnyUnrecoverableErrorsInThisFunction() const; 702 703 /// Retrieve the current block, if any. 704 sema::BlockScopeInfo *getCurBlock(); 705 706 /// Get the innermost lambda or block enclosing the current location, if any. 707 /// This looks through intervening non-lambda, non-block scopes such as local 708 /// functions. 709 sema::CapturingScopeInfo *getEnclosingLambdaOrBlock() const; 710 711 /// Retrieve the current lambda scope info, if any. 712 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most 713 /// lambda scope info ignoring all inner capturing scopes that are not 714 /// lambda scopes. 715 sema::LambdaScopeInfo * 716 getCurLambda(bool IgnoreNonLambdaCapturingScope = false); 717 718 /// Retrieve the current generic lambda info, if any. 719 sema::LambdaScopeInfo *getCurGenericLambda(); 720 721 /// Retrieve the current captured region, if any. 722 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 723 724 void ActOnComment(SourceRange Comment); 725 726 /// Retrieve the parser's current scope. 727 /// 728 /// This routine must only be used when it is certain that semantic analysis 729 /// and the parser are in precisely the same context, which is not the case 730 /// when, e.g., we are performing any kind of template instantiation. 731 /// Therefore, the only safe places to use this scope are in the parser 732 /// itself and in routines directly invoked from the parser and *never* from 733 /// template substitution or instantiation. 734 Scope *getCurScope() const { return CurScope; } 735 736 IdentifierInfo *getSuperIdentifier() const; 737 738 DeclContext *getCurLexicalContext() const { 739 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 740 } 741 742 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, 743 const FunctionDecl *FD = nullptr); 744 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, 745 const PartialDiagnostic &PD, 746 const FunctionDecl *FD = nullptr) { 747 return targetDiag(Loc, PD.getDiagID(), FD) << PD; 748 } 749 750 /// Check if the type is allowed to be used for the current target. 751 void checkTypeSupport(QualType Ty, SourceLocation Loc, 752 ValueDecl *D = nullptr); 753 754 // /// The kind of conversion being performed. 755 // enum CheckedConversionKind { 756 // /// An implicit conversion. 757 // CCK_ImplicitConversion, 758 // /// A C-style cast. 759 // CCK_CStyleCast, 760 // /// A functional-style cast. 761 // CCK_FunctionalCast, 762 // /// A cast other than a C-style cast. 763 // CCK_OtherCast, 764 // /// A conversion for an operand of a builtin overloaded operator. 765 // CCK_ForBuiltinOverloadedOp 766 // }; 767 768 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 769 /// cast. If there is already an implicit cast, merge into the existing one. 770 /// If isLvalue, the result of the cast is an lvalue. 771 ExprResult ImpCastExprToType( 772 Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue, 773 const CXXCastPath *BasePath = nullptr, 774 CheckedConversionKind CCK = CheckedConversionKind::Implicit); 775 776 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 777 /// to the conversion from scalar type ScalarTy to the Boolean type. 778 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 779 780 /// If \p AllowLambda is true, treat lambda as function. 781 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const; 782 783 /// Returns a pointer to the innermost enclosing function, or nullptr if the 784 /// current context is not inside a function. If \p AllowLambda is true, 785 /// this can return the call operator of an enclosing lambda, otherwise 786 /// lambdas are skipped when looking for an enclosing function. 787 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const; 788 789 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 790 /// the method decl for the method being parsed. If we're currently 791 /// in a 'block', this returns the containing context. 792 ObjCMethodDecl *getCurMethodDecl(); 793 794 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 795 /// or C function we're in, otherwise return null. If we're currently 796 /// in a 'block', this returns the containing context. 797 NamedDecl *getCurFunctionOrMethodDecl() const; 798 799 /// Warn if we're implicitly casting from a _Nullable pointer type to a 800 /// _Nonnull one. 801 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, 802 SourceLocation Loc); 803 804 /// Warn when implicitly casting 0 to nullptr. 805 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); 806 807 /// Warn when implicitly changing function effects. 808 void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, 809 SourceLocation Loc); 810 811 /// makeUnavailableInSystemHeader - There is an error in the current 812 /// context. If we're still in a system header, and we can plausibly 813 /// make the relevant declaration unavailable instead of erroring, do 814 /// so and return true. 815 bool makeUnavailableInSystemHeader(SourceLocation loc, 816 UnavailableAttr::ImplicitReason reason); 817 818 /// Retrieve a suitable printing policy for diagnostics. 819 PrintingPolicy getPrintingPolicy() const { 820 return getPrintingPolicy(Context, PP); 821 } 822 823 /// Retrieve a suitable printing policy for diagnostics. 824 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 825 const Preprocessor &PP); 826 827 /// Scope actions. 828 void ActOnTranslationUnitScope(Scope *S); 829 830 /// Determine whether \param D is function like (function or function 831 /// template) for parsing. 832 bool isDeclaratorFunctionLike(Declarator &D); 833 834 /// The maximum alignment, same as in llvm::Value. We duplicate them here 835 /// because that allows us not to duplicate the constants in clang code, 836 /// which we must to since we can't directly use the llvm constants. 837 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp 838 /// 839 /// This is the greatest alignment value supported by load, store, and alloca 840 /// instructions, and global values. 841 static const unsigned MaxAlignmentExponent = 32; 842 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent; 843 844 /// Flag indicating whether or not to collect detailed statistics. 845 bool CollectStats; 846 847 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; 848 849 /// Stack containing information about each of the nested 850 /// function, block, and method scopes that are currently active. 851 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 852 853 /// The index of the first FunctionScope that corresponds to the current 854 /// context. 855 unsigned FunctionScopesStart = 0; 856 857 /// Track the number of currently active capturing scopes. 858 unsigned CapturingFunctionScopes = 0; 859 860 llvm::BumpPtrAllocator BumpAlloc; 861 862 /// The kind of translation unit we are processing. 863 /// 864 /// When we're processing a complete translation unit, Sema will perform 865 /// end-of-translation-unit semantic tasks (such as creating 866 /// initializers for tentative definitions in C) once parsing has 867 /// completed. Modules and precompiled headers perform different kinds of 868 /// checks. 869 const TranslationUnitKind TUKind; 870 871 /// Translation Unit Scope - useful to Objective-C actions that need 872 /// to lookup file scope declarations in the "ordinary" C decl namespace. 873 /// For example, user-defined classes, built-in "id" type, etc. 874 Scope *TUScope; 875 876 void incrementMSManglingNumber() const { 877 return CurScope->incrementMSManglingNumber(); 878 } 879 880 /// Try to recover by turning the given expression into a 881 /// call. Returns true if recovery was attempted or an error was 882 /// emitted; this may also leave the ExprResult invalid. 883 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 884 bool ForceComplain = false, 885 bool (*IsPlausibleResult)(QualType) = nullptr); 886 887 /// Figure out if an expression could be turned into a call. 888 /// 889 /// Use this when trying to recover from an error where the programmer may 890 /// have written just the name of a function instead of actually calling it. 891 /// 892 /// \param E - The expression to examine. 893 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call 894 /// with no arguments, this parameter is set to the type returned by such a 895 /// call; otherwise, it is set to an empty QualType. 896 /// \param OverloadSet - If the expression is an overloaded function 897 /// name, this parameter is populated with the decls of the various 898 /// overloads. 899 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 900 UnresolvedSetImpl &NonTemplateOverloads); 901 902 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 903 typedef OpaquePtr<TemplateName> TemplateTy; 904 typedef OpaquePtr<QualType> TypeTy; 905 906 OpenCLOptions OpenCLFeatures; 907 FPOptions CurFPFeatures; 908 909 const LangOptions &LangOpts; 910 Preprocessor &PP; 911 ASTContext &Context; 912 ASTConsumer &Consumer; 913 DiagnosticsEngine &Diags; 914 SourceManager &SourceMgr; 915 api_notes::APINotesManager APINotes; 916 917 /// A RAII object to enter scope of a compound statement. 918 class CompoundScopeRAII { 919 public: 920 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { 921 S.ActOnStartOfCompoundStmt(IsStmtExpr); 922 } 923 924 ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } 925 926 private: 927 Sema &S; 928 }; 929 930 /// An RAII helper that pops function a function scope on exit. 931 struct FunctionScopeRAII { 932 Sema &S; 933 bool Active; 934 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} 935 ~FunctionScopeRAII() { 936 if (Active) 937 S.PopFunctionScopeInfo(); 938 } 939 void disable() { Active = false; } 940 }; 941 942 sema::FunctionScopeInfo *getCurFunction() const { 943 return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); 944 } 945 946 /// Worker object for performing CFG-based warnings. 947 sema::AnalysisBasedWarnings AnalysisWarnings; 948 threadSafety::BeforeSet *ThreadSafetyDeclCache; 949 950 /// Callback to the parser to parse templated functions when needed. 951 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 952 typedef void LateTemplateParserCleanupCB(void *P); 953 LateTemplateParserCB *LateTemplateParser; 954 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 955 void *OpaqueParser; 956 957 void SetLateTemplateParser(LateTemplateParserCB *LTP, 958 LateTemplateParserCleanupCB *LTPCleanup, void *P) { 959 LateTemplateParser = LTP; 960 LateTemplateParserCleanup = LTPCleanup; 961 OpaqueParser = P; 962 } 963 964 /// Callback to the parser to parse a type expressed as a string. 965 std::function<TypeResult(StringRef, StringRef, SourceLocation)> 966 ParseTypeFromStringCallback; 967 968 /// VAListTagName - The declaration name corresponding to __va_list_tag. 969 /// This is used as part of a hack to omit that class from ADL results. 970 DeclarationName VAListTagName; 971 972 /// Is the last error level diagnostic immediate. This is used to determined 973 /// whether the next info diagnostic should be immediate. 974 bool IsLastErrorImmediate = true; 975 976 class DelayedDiagnostics; 977 978 class DelayedDiagnosticsState { 979 sema::DelayedDiagnosticPool *SavedPool = nullptr; 980 friend class Sema::DelayedDiagnostics; 981 }; 982 typedef DelayedDiagnosticsState ParsingDeclState; 983 typedef DelayedDiagnosticsState ProcessingContextState; 984 985 /// A class which encapsulates the logic for delaying diagnostics 986 /// during parsing and other processing. 987 class DelayedDiagnostics { 988 /// The current pool of diagnostics into which delayed 989 /// diagnostics should go. 990 sema::DelayedDiagnosticPool *CurPool = nullptr; 991 992 public: 993 DelayedDiagnostics() = default; 994 995 /// Adds a delayed diagnostic. 996 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 997 998 /// Determines whether diagnostics should be delayed. 999 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 1000 1001 /// Returns the current delayed-diagnostics pool. 1002 sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } 1003 1004 /// Enter a new scope. Access and deprecation diagnostics will be 1005 /// collected in this pool. 1006 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 1007 DelayedDiagnosticsState state; 1008 state.SavedPool = CurPool; 1009 CurPool = &pool; 1010 return state; 1011 } 1012 1013 /// Leave a delayed-diagnostic state that was previously pushed. 1014 /// Do not emit any of the diagnostics. This is performed as part 1015 /// of the bookkeeping of popping a pool "properly". 1016 void popWithoutEmitting(DelayedDiagnosticsState state) { 1017 CurPool = state.SavedPool; 1018 } 1019 1020 /// Enter a new scope where access and deprecation diagnostics are 1021 /// not delayed. 1022 DelayedDiagnosticsState pushUndelayed() { 1023 DelayedDiagnosticsState state; 1024 state.SavedPool = CurPool; 1025 CurPool = nullptr; 1026 return state; 1027 } 1028 1029 /// Undo a previous pushUndelayed(). 1030 void popUndelayed(DelayedDiagnosticsState state) { 1031 assert(CurPool == nullptr); 1032 CurPool = state.SavedPool; 1033 } 1034 } DelayedDiagnostics; 1035 1036 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 1037 return DelayedDiagnostics.push(pool); 1038 } 1039 1040 /// Diagnostics that are emitted only if we discover that the given function 1041 /// must be codegen'ed. Because handling these correctly adds overhead to 1042 /// compilation, this is currently only enabled for CUDA compilations. 1043 SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags; 1044 1045 /// CurContext - This is the current declaration context of parsing. 1046 DeclContext *CurContext; 1047 1048 SemaAMDGPU &AMDGPU() { 1049 assert(AMDGPUPtr); 1050 return *AMDGPUPtr; 1051 } 1052 1053 SemaARM &ARM() { 1054 assert(ARMPtr); 1055 return *ARMPtr; 1056 } 1057 1058 SemaAVR &AVR() { 1059 assert(AVRPtr); 1060 return *AVRPtr; 1061 } 1062 1063 SemaBPF &BPF() { 1064 assert(BPFPtr); 1065 return *BPFPtr; 1066 } 1067 1068 SemaCodeCompletion &CodeCompletion() { 1069 assert(CodeCompletionPtr); 1070 return *CodeCompletionPtr; 1071 } 1072 1073 SemaCUDA &CUDA() { 1074 assert(CUDAPtr); 1075 return *CUDAPtr; 1076 } 1077 1078 SemaHLSL &HLSL() { 1079 assert(HLSLPtr); 1080 return *HLSLPtr; 1081 } 1082 1083 SemaHexagon &Hexagon() { 1084 assert(HexagonPtr); 1085 return *HexagonPtr; 1086 } 1087 1088 SemaLoongArch &LoongArch() { 1089 assert(LoongArchPtr); 1090 return *LoongArchPtr; 1091 } 1092 1093 SemaM68k &M68k() { 1094 assert(M68kPtr); 1095 return *M68kPtr; 1096 } 1097 1098 SemaMIPS &MIPS() { 1099 assert(MIPSPtr); 1100 return *MIPSPtr; 1101 } 1102 1103 SemaMSP430 &MSP430() { 1104 assert(MSP430Ptr); 1105 return *MSP430Ptr; 1106 } 1107 1108 SemaNVPTX &NVPTX() { 1109 assert(NVPTXPtr); 1110 return *NVPTXPtr; 1111 } 1112 1113 SemaObjC &ObjC() { 1114 assert(ObjCPtr); 1115 return *ObjCPtr; 1116 } 1117 1118 SemaOpenACC &OpenACC() { 1119 assert(OpenACCPtr); 1120 return *OpenACCPtr; 1121 } 1122 1123 SemaOpenCL &OpenCL() { 1124 assert(OpenCLPtr); 1125 return *OpenCLPtr; 1126 } 1127 1128 SemaOpenMP &OpenMP() { 1129 assert(OpenMPPtr && "SemaOpenMP is dead"); 1130 return *OpenMPPtr; 1131 } 1132 1133 SemaPPC &PPC() { 1134 assert(PPCPtr); 1135 return *PPCPtr; 1136 } 1137 1138 SemaPseudoObject &PseudoObject() { 1139 assert(PseudoObjectPtr); 1140 return *PseudoObjectPtr; 1141 } 1142 1143 SemaRISCV &RISCV() { 1144 assert(RISCVPtr); 1145 return *RISCVPtr; 1146 } 1147 1148 SemaSPIRV &SPIRV() { 1149 assert(SPIRVPtr); 1150 return *SPIRVPtr; 1151 } 1152 1153 SemaSYCL &SYCL() { 1154 assert(SYCLPtr); 1155 return *SYCLPtr; 1156 } 1157 1158 SemaSwift &Swift() { 1159 assert(SwiftPtr); 1160 return *SwiftPtr; 1161 } 1162 1163 SemaSystemZ &SystemZ() { 1164 assert(SystemZPtr); 1165 return *SystemZPtr; 1166 } 1167 1168 SemaWasm &Wasm() { 1169 assert(WasmPtr); 1170 return *WasmPtr; 1171 } 1172 1173 SemaX86 &X86() { 1174 assert(X86Ptr); 1175 return *X86Ptr; 1176 } 1177 1178 /// Source of additional semantic information. 1179 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource; 1180 1181 protected: 1182 friend class Parser; 1183 friend class InitializationSequence; 1184 friend class ASTReader; 1185 friend class ASTDeclReader; 1186 friend class ASTWriter; 1187 1188 private: 1189 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; 1190 bool WarnedDarwinSDKInfoMissing = false; 1191 1192 StackExhaustionHandler StackHandler; 1193 1194 Sema(const Sema &) = delete; 1195 void operator=(const Sema &) = delete; 1196 1197 /// The handler for the FileChanged preprocessor events. 1198 /// 1199 /// Used for diagnostics that implement custom semantic analysis for #include 1200 /// directives, like -Wpragma-pack. 1201 sema::SemaPPCallbacks *SemaPPCallbackHandler; 1202 1203 /// The parser's current scope. 1204 /// 1205 /// The parser maintains this state here. 1206 Scope *CurScope; 1207 1208 mutable IdentifierInfo *Ident_super; 1209 1210 std::unique_ptr<SemaAMDGPU> AMDGPUPtr; 1211 std::unique_ptr<SemaARM> ARMPtr; 1212 std::unique_ptr<SemaAVR> AVRPtr; 1213 std::unique_ptr<SemaBPF> BPFPtr; 1214 std::unique_ptr<SemaCodeCompletion> CodeCompletionPtr; 1215 std::unique_ptr<SemaCUDA> CUDAPtr; 1216 std::unique_ptr<SemaHLSL> HLSLPtr; 1217 std::unique_ptr<SemaHexagon> HexagonPtr; 1218 std::unique_ptr<SemaLoongArch> LoongArchPtr; 1219 std::unique_ptr<SemaM68k> M68kPtr; 1220 std::unique_ptr<SemaMIPS> MIPSPtr; 1221 std::unique_ptr<SemaMSP430> MSP430Ptr; 1222 std::unique_ptr<SemaNVPTX> NVPTXPtr; 1223 std::unique_ptr<SemaObjC> ObjCPtr; 1224 std::unique_ptr<SemaOpenACC> OpenACCPtr; 1225 std::unique_ptr<SemaOpenCL> OpenCLPtr; 1226 std::unique_ptr<SemaOpenMP> OpenMPPtr; 1227 std::unique_ptr<SemaPPC> PPCPtr; 1228 std::unique_ptr<SemaPseudoObject> PseudoObjectPtr; 1229 std::unique_ptr<SemaRISCV> RISCVPtr; 1230 std::unique_ptr<SemaSPIRV> SPIRVPtr; 1231 std::unique_ptr<SemaSYCL> SYCLPtr; 1232 std::unique_ptr<SemaSwift> SwiftPtr; 1233 std::unique_ptr<SemaSystemZ> SystemZPtr; 1234 std::unique_ptr<SemaWasm> WasmPtr; 1235 std::unique_ptr<SemaX86> X86Ptr; 1236 1237 ///@} 1238 1239 // 1240 // 1241 // ------------------------------------------------------------------------- 1242 // 1243 // 1244 1245 /// \name API Notes 1246 /// Implementations are in SemaAPINotes.cpp 1247 ///@{ 1248 1249 public: 1250 /// Map any API notes provided for this declaration to attributes on the 1251 /// declaration. 1252 /// 1253 /// Triggered by declaration-attribute processing. 1254 void ProcessAPINotes(Decl *D); 1255 1256 ///@} 1257 1258 // 1259 // 1260 // ------------------------------------------------------------------------- 1261 // 1262 // 1263 1264 /// \name C++ Access Control 1265 /// Implementations are in SemaAccess.cpp 1266 ///@{ 1267 1268 public: 1269 enum AccessResult { 1270 AR_accessible, 1271 AR_inaccessible, 1272 AR_dependent, 1273 AR_delayed 1274 }; 1275 1276 /// SetMemberAccessSpecifier - Set the access specifier of a member. 1277 /// Returns true on error (when the previous member decl access specifier 1278 /// is different from the new member decl access specifier). 1279 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 1280 NamedDecl *PrevMemberDecl, 1281 AccessSpecifier LexicalAS); 1282 1283 /// Perform access-control checking on a previously-unresolved member 1284 /// access which has now been resolved to a member. 1285 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 1286 DeclAccessPair FoundDecl); 1287 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 1288 DeclAccessPair FoundDecl); 1289 1290 /// Checks access to an overloaded operator new or delete. 1291 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 1292 SourceRange PlacementRange, 1293 CXXRecordDecl *NamingClass, 1294 DeclAccessPair FoundDecl, 1295 bool Diagnose = true); 1296 1297 /// Checks access to a constructor. 1298 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, 1299 DeclAccessPair FoundDecl, 1300 const InitializedEntity &Entity, 1301 bool IsCopyBindingRefToTemp = false); 1302 1303 /// Checks access to a constructor. 1304 AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, 1305 DeclAccessPair FoundDecl, 1306 const InitializedEntity &Entity, 1307 const PartialDiagnostic &PDiag); 1308 AccessResult CheckDestructorAccess(SourceLocation Loc, 1309 CXXDestructorDecl *Dtor, 1310 const PartialDiagnostic &PDiag, 1311 QualType objectType = QualType()); 1312 1313 /// Checks access to the target of a friend declaration. 1314 AccessResult CheckFriendAccess(NamedDecl *D); 1315 1316 /// Checks access to a member. 1317 AccessResult CheckMemberAccess(SourceLocation UseLoc, 1318 CXXRecordDecl *NamingClass, 1319 DeclAccessPair Found); 1320 1321 /// Checks implicit access to a member in a structured binding. 1322 AccessResult 1323 CheckStructuredBindingMemberAccess(SourceLocation UseLoc, 1324 CXXRecordDecl *DecomposedClass, 1325 DeclAccessPair Field); 1326 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, 1327 const SourceRange &, 1328 DeclAccessPair FoundDecl); 1329 1330 /// Checks access to an overloaded member operator, including 1331 /// conversion operators. 1332 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, 1333 Expr *ArgExpr, 1334 DeclAccessPair FoundDecl); 1335 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, 1336 ArrayRef<Expr *> ArgExprs, 1337 DeclAccessPair FoundDecl); 1338 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 1339 DeclAccessPair FoundDecl); 1340 1341 /// Checks access for a hierarchy conversion. 1342 /// 1343 /// \param ForceCheck true if this check should be performed even if access 1344 /// control is disabled; some things rely on this for semantics 1345 /// \param ForceUnprivileged true if this check should proceed as if the 1346 /// context had no special privileges 1347 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, 1348 QualType Derived, const CXXBasePath &Path, 1349 unsigned DiagID, bool ForceCheck = false, 1350 bool ForceUnprivileged = false); 1351 1352 /// Checks access to all the declarations in the given result set. 1353 void CheckLookupAccess(const LookupResult &R); 1354 1355 /// Checks access to Target from the given class. The check will take access 1356 /// specifiers into account, but no member access expressions and such. 1357 /// 1358 /// \param Target the declaration to check if it can be accessed 1359 /// \param NamingClass the class in which the lookup was started. 1360 /// \param BaseType type of the left side of member access expression. 1361 /// \p BaseType and \p NamingClass are used for C++ access control. 1362 /// Depending on the lookup case, they should be set to the following: 1363 /// - lhs.target (member access without a qualifier): 1364 /// \p BaseType and \p NamingClass are both the type of 'lhs'. 1365 /// - lhs.X::target (member access with a qualifier): 1366 /// BaseType is the type of 'lhs', NamingClass is 'X' 1367 /// - X::target (qualified lookup without member access): 1368 /// BaseType is null, NamingClass is 'X'. 1369 /// - target (unqualified lookup). 1370 /// BaseType is null, NamingClass is the parent class of 'target'. 1371 /// \return true if the Target is accessible from the Class, false otherwise. 1372 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, 1373 QualType BaseType); 1374 1375 /// Is the given member accessible for the purposes of deciding whether to 1376 /// define a special member function as deleted? 1377 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 1378 DeclAccessPair Found, QualType ObjectType, 1379 SourceLocation Loc, 1380 const PartialDiagnostic &Diag); 1381 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 1382 DeclAccessPair Found, 1383 QualType ObjectType) { 1384 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, 1385 SourceLocation(), PDiag()); 1386 } 1387 1388 void HandleDependentAccessCheck( 1389 const DependentDiagnostic &DD, 1390 const MultiLevelTemplateArgumentList &TemplateArgs); 1391 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 1392 1393 ///@} 1394 1395 // 1396 // 1397 // ------------------------------------------------------------------------- 1398 // 1399 // 1400 1401 /// \name Attributes 1402 /// Implementations are in SemaAttr.cpp 1403 ///@{ 1404 1405 public: 1406 /// Controls member pointer representation format under the MS ABI. 1407 LangOptions::PragmaMSPointersToMembersKind 1408 MSPointerToMemberRepresentationMethod; 1409 1410 bool MSStructPragmaOn; // True when \#pragma ms_struct on 1411 1412 /// Source location for newly created implicit MSInheritanceAttrs 1413 SourceLocation ImplicitMSInheritanceAttrLoc; 1414 1415 /// pragma clang section kind 1416 enum PragmaClangSectionKind { 1417 PCSK_Invalid = 0, 1418 PCSK_BSS = 1, 1419 PCSK_Data = 2, 1420 PCSK_Rodata = 3, 1421 PCSK_Text = 4, 1422 PCSK_Relro = 5 1423 }; 1424 1425 enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; 1426 1427 struct PragmaClangSection { 1428 std::string SectionName; 1429 bool Valid = false; 1430 SourceLocation PragmaLocation; 1431 }; 1432 1433 PragmaClangSection PragmaClangBSSSection; 1434 PragmaClangSection PragmaClangDataSection; 1435 PragmaClangSection PragmaClangRodataSection; 1436 PragmaClangSection PragmaClangRelroSection; 1437 PragmaClangSection PragmaClangTextSection; 1438 1439 enum PragmaMsStackAction { 1440 PSK_Reset = 0x0, // #pragma () 1441 PSK_Set = 0x1, // #pragma (value) 1442 PSK_Push = 0x2, // #pragma (push[, id]) 1443 PSK_Pop = 0x4, // #pragma (pop[, id]) 1444 PSK_Show = 0x8, // #pragma (show) -- only for "pack"! 1445 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) 1446 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) 1447 }; 1448 1449 struct PragmaPackInfo { 1450 PragmaMsStackAction Action; 1451 StringRef SlotLabel; 1452 Token Alignment; 1453 }; 1454 1455 // #pragma pack and align. 1456 class AlignPackInfo { 1457 public: 1458 // `Native` represents default align mode, which may vary based on the 1459 // platform. 1460 enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; 1461 1462 // #pragma pack info constructor 1463 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) 1464 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { 1465 assert(Num == PackNumber && "The pack number has been truncated."); 1466 } 1467 1468 // #pragma align info constructor 1469 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) 1470 : PackAttr(false), AlignMode(M), 1471 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} 1472 1473 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} 1474 1475 AlignPackInfo() : AlignPackInfo(Native, false) {} 1476 1477 // When a AlignPackInfo itself cannot be used, this returns an 32-bit 1478 // integer encoding for it. This should only be passed to 1479 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. 1480 static uint32_t getRawEncoding(const AlignPackInfo &Info) { 1481 std::uint32_t Encoding{}; 1482 if (Info.IsXLStack()) 1483 Encoding |= IsXLMask; 1484 1485 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; 1486 1487 if (Info.IsPackAttr()) 1488 Encoding |= PackAttrMask; 1489 1490 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; 1491 1492 return Encoding; 1493 } 1494 1495 static AlignPackInfo getFromRawEncoding(unsigned Encoding) { 1496 bool IsXL = static_cast<bool>(Encoding & IsXLMask); 1497 AlignPackInfo::Mode M = 1498 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); 1499 int PackNumber = (Encoding & PackNumMask) >> 4; 1500 1501 if (Encoding & PackAttrMask) 1502 return AlignPackInfo(M, PackNumber, IsXL); 1503 1504 return AlignPackInfo(M, IsXL); 1505 } 1506 1507 bool IsPackAttr() const { return PackAttr; } 1508 1509 bool IsAlignAttr() const { return !PackAttr; } 1510 1511 Mode getAlignMode() const { return AlignMode; } 1512 1513 unsigned getPackNumber() const { return PackNumber; } 1514 1515 bool IsPackSet() const { 1516 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack 1517 // attriute on a decl. 1518 return PackNumber != UninitPackVal && PackNumber != 0; 1519 } 1520 1521 bool IsXLStack() const { return XLStack; } 1522 1523 bool operator==(const AlignPackInfo &Info) const { 1524 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == 1525 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, 1526 Info.XLStack); 1527 } 1528 1529 bool operator!=(const AlignPackInfo &Info) const { 1530 return !(*this == Info); 1531 } 1532 1533 private: 1534 /// \brief True if this is a pragma pack attribute, 1535 /// not a pragma align attribute. 1536 bool PackAttr; 1537 1538 /// \brief The alignment mode that is in effect. 1539 Mode AlignMode; 1540 1541 /// \brief The pack number of the stack. 1542 unsigned char PackNumber; 1543 1544 /// \brief True if it is a XL #pragma align/pack stack. 1545 bool XLStack; 1546 1547 /// \brief Uninitialized pack value. 1548 static constexpr unsigned char UninitPackVal = -1; 1549 1550 // Masks to encode and decode an AlignPackInfo. 1551 static constexpr uint32_t IsXLMask{0x0000'0001}; 1552 static constexpr uint32_t AlignModeMask{0x0000'0006}; 1553 static constexpr uint32_t PackAttrMask{0x00000'0008}; 1554 static constexpr uint32_t PackNumMask{0x0000'01F0}; 1555 }; 1556 1557 template <typename ValueType> struct PragmaStack { 1558 struct Slot { 1559 llvm::StringRef StackSlotLabel; 1560 ValueType Value; 1561 SourceLocation PragmaLocation; 1562 SourceLocation PragmaPushLocation; 1563 Slot(llvm::StringRef StackSlotLabel, ValueType Value, 1564 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) 1565 : StackSlotLabel(StackSlotLabel), Value(Value), 1566 PragmaLocation(PragmaLocation), 1567 PragmaPushLocation(PragmaPushLocation) {} 1568 }; 1569 1570 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, 1571 llvm::StringRef StackSlotLabel, ValueType Value) { 1572 if (Action == PSK_Reset) { 1573 CurrentValue = DefaultValue; 1574 CurrentPragmaLocation = PragmaLocation; 1575 return; 1576 } 1577 if (Action & PSK_Push) 1578 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, 1579 PragmaLocation); 1580 else if (Action & PSK_Pop) { 1581 if (!StackSlotLabel.empty()) { 1582 // If we've got a label, try to find it and jump there. 1583 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { 1584 return x.StackSlotLabel == StackSlotLabel; 1585 }); 1586 // If we found the label so pop from there. 1587 if (I != Stack.rend()) { 1588 CurrentValue = I->Value; 1589 CurrentPragmaLocation = I->PragmaLocation; 1590 Stack.erase(std::prev(I.base()), Stack.end()); 1591 } 1592 } else if (!Stack.empty()) { 1593 // We do not have a label, just pop the last entry. 1594 CurrentValue = Stack.back().Value; 1595 CurrentPragmaLocation = Stack.back().PragmaLocation; 1596 Stack.pop_back(); 1597 } 1598 } 1599 if (Action & PSK_Set) { 1600 CurrentValue = Value; 1601 CurrentPragmaLocation = PragmaLocation; 1602 } 1603 } 1604 1605 // MSVC seems to add artificial slots to #pragma stacks on entering a C++ 1606 // method body to restore the stacks on exit, so it works like this: 1607 // 1608 // struct S { 1609 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) 1610 // void Method {} 1611 // #pragma <name>(pop, InternalPragmaSlot) 1612 // }; 1613 // 1614 // It works even with #pragma vtordisp, although MSVC doesn't support 1615 // #pragma vtordisp(push [, id], n) 1616 // syntax. 1617 // 1618 // Push / pop a named sentinel slot. 1619 void SentinelAction(PragmaMsStackAction Action, StringRef Label) { 1620 assert((Action == PSK_Push || Action == PSK_Pop) && 1621 "Can only push / pop #pragma stack sentinels!"); 1622 Act(CurrentPragmaLocation, Action, Label, CurrentValue); 1623 } 1624 1625 // Constructors. 1626 explicit PragmaStack(const ValueType &Default) 1627 : DefaultValue(Default), CurrentValue(Default) {} 1628 1629 bool hasValue() const { return CurrentValue != DefaultValue; } 1630 1631 SmallVector<Slot, 2> Stack; 1632 ValueType DefaultValue; // Value used for PSK_Reset action. 1633 ValueType CurrentValue; 1634 SourceLocation CurrentPragmaLocation; 1635 }; 1636 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 1637 // we shouldn't do so if they're in a module). 1638 1639 /// Whether to insert vtordisps prior to virtual bases in the Microsoft 1640 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 1641 /// 1642 /// 0: Suppress all vtordisps 1643 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 1644 /// structors 1645 /// 2: Always insert vtordisps to support RTTI on partially constructed 1646 /// objects 1647 PragmaStack<MSVtorDispMode> VtorDispStack; 1648 PragmaStack<AlignPackInfo> AlignPackStack; 1649 // The current #pragma align/pack values and locations at each #include. 1650 struct AlignPackIncludeState { 1651 AlignPackInfo CurrentValue; 1652 SourceLocation CurrentPragmaLocation; 1653 bool HasNonDefaultValue, ShouldWarnOnInclude; 1654 }; 1655 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; 1656 // Segment #pragmas. 1657 PragmaStack<StringLiteral *> DataSegStack; 1658 PragmaStack<StringLiteral *> BSSSegStack; 1659 PragmaStack<StringLiteral *> ConstSegStack; 1660 PragmaStack<StringLiteral *> CodeSegStack; 1661 1662 // #pragma strict_gs_check. 1663 PragmaStack<bool> StrictGuardStackCheckStack; 1664 1665 // This stack tracks the current state of Sema.CurFPFeatures. 1666 PragmaStack<FPOptionsOverride> FpPragmaStack; 1667 FPOptionsOverride CurFPFeatureOverrides() { 1668 FPOptionsOverride result; 1669 if (!FpPragmaStack.hasValue()) { 1670 result = FPOptionsOverride(); 1671 } else { 1672 result = FpPragmaStack.CurrentValue; 1673 } 1674 return result; 1675 } 1676 1677 enum PragmaSectionKind { 1678 PSK_DataSeg, 1679 PSK_BSSSeg, 1680 PSK_ConstSeg, 1681 PSK_CodeSeg, 1682 }; 1683 1684 // RAII object to push / pop sentinel slots for all MS #pragma stacks. 1685 // Actions should be performed only if we enter / exit a C++ method body. 1686 class PragmaStackSentinelRAII { 1687 public: 1688 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); 1689 ~PragmaStackSentinelRAII(); 1690 1691 private: 1692 Sema &S; 1693 StringRef SlotLabel; 1694 bool ShouldAct; 1695 }; 1696 1697 /// Last section used with #pragma init_seg. 1698 StringLiteral *CurInitSeg; 1699 SourceLocation CurInitSegLoc; 1700 1701 /// Sections used with #pragma alloc_text. 1702 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap; 1703 1704 /// VisContext - Manages the stack for \#pragma GCC visibility. 1705 void *VisContext; // Really a "PragmaVisStack*" 1706 1707 /// This an attribute introduced by \#pragma clang attribute. 1708 struct PragmaAttributeEntry { 1709 SourceLocation Loc; 1710 ParsedAttr *Attribute; 1711 SmallVector<attr::SubjectMatchRule, 4> MatchRules; 1712 bool IsUsed; 1713 }; 1714 1715 /// A push'd group of PragmaAttributeEntries. 1716 struct PragmaAttributeGroup { 1717 /// The location of the push attribute. 1718 SourceLocation Loc; 1719 /// The namespace of this push group. 1720 const IdentifierInfo *Namespace; 1721 SmallVector<PragmaAttributeEntry, 2> Entries; 1722 }; 1723 1724 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; 1725 1726 /// The declaration that is currently receiving an attribute from the 1727 /// #pragma attribute stack. 1728 const Decl *PragmaAttributeCurrentTargetDecl; 1729 1730 /// This represents the last location of a "#pragma clang optimize off" 1731 /// directive if such a directive has not been closed by an "on" yet. If 1732 /// optimizations are currently "on", this is set to an invalid location. 1733 SourceLocation OptimizeOffPragmaLocation; 1734 1735 /// Get the location for the currently active "\#pragma clang optimize 1736 /// off". If this location is invalid, then the state of the pragma is "on". 1737 SourceLocation getOptimizeOffPragmaLocation() const { 1738 return OptimizeOffPragmaLocation; 1739 } 1740 1741 /// The "on" or "off" argument passed by \#pragma optimize, that denotes 1742 /// whether the optimizations in the list passed to the pragma should be 1743 /// turned off or on. This boolean is true by default because command line 1744 /// options are honored when `#pragma optimize("", on)`. 1745 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing) 1746 bool MSPragmaOptimizeIsOn = true; 1747 1748 /// Set of no-builtin functions listed by \#pragma function. 1749 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins; 1750 1751 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 1752 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 1753 void AddAlignmentAttributesForRecord(RecordDecl *RD); 1754 1755 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 1756 void AddMsStructLayoutForRecord(RecordDecl *RD); 1757 1758 /// Add gsl::Pointer attribute to std::container::iterator 1759 /// \param ND The declaration that introduces the name 1760 /// std::container::iterator. \param UnderlyingRecord The record named by ND. 1761 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); 1762 1763 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. 1764 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); 1765 1766 /// Add [[clang:::lifetimebound]] attr for std:: functions and methods. 1767 void inferLifetimeBoundAttribute(FunctionDecl *FD); 1768 1769 /// Add [[clang:::lifetime_capture_by(this)]] to STL container methods. 1770 void inferLifetimeCaptureByAttribute(FunctionDecl *FD); 1771 1772 /// Add [[gsl::Pointer]] attributes for std:: types. 1773 void inferGslPointerAttribute(TypedefNameDecl *TD); 1774 1775 LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL, 1776 StringRef ParamName); 1777 // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X' 1778 // can be the name of a function parameter, we need to parse the function 1779 // declaration and rest of the parameters before processesing 'X'. Therefore 1780 // do this lazily instead of processing while parsing the annotation itself. 1781 void LazyProcessLifetimeCaptureByParams(FunctionDecl *FD); 1782 1783 /// Add _Nullable attributes for std:: types. 1784 void inferNullableClassAttribute(CXXRecordDecl *CRD); 1785 1786 enum PragmaOptionsAlignKind { 1787 POAK_Native, // #pragma options align=native 1788 POAK_Natural, // #pragma options align=natural 1789 POAK_Packed, // #pragma options align=packed 1790 POAK_Power, // #pragma options align=power 1791 POAK_Mac68k, // #pragma options align=mac68k 1792 POAK_Reset // #pragma options align=reset 1793 }; 1794 1795 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section 1796 void ActOnPragmaClangSection(SourceLocation PragmaLoc, 1797 PragmaClangSectionAction Action, 1798 PragmaClangSectionKind SecKind, 1799 StringRef SecName); 1800 1801 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 1802 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 1803 SourceLocation PragmaLoc); 1804 1805 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 1806 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, 1807 StringRef SlotLabel, Expr *Alignment); 1808 1809 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs 1810 /// (unless they are value dependent or type dependent). Returns false 1811 /// and emits a diagnostic if one or more of the arguments could not be 1812 /// folded into a constant. 1813 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, 1814 MutableArrayRef<Expr *> Args); 1815 1816 enum class PragmaAlignPackDiagnoseKind { 1817 NonDefaultStateAtInclude, 1818 ChangedStateAtExit 1819 }; 1820 1821 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, 1822 SourceLocation IncludeLoc); 1823 void DiagnoseUnterminatedPragmaAlignPack(); 1824 1825 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 1826 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 1827 1828 /// ActOnPragmaMSComment - Called on well formed 1829 /// \#pragma comment(kind, "arg"). 1830 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, 1831 StringRef Arg); 1832 1833 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 1834 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, 1835 StringRef Value); 1836 1837 /// Are precise floating point semantics currently enabled? 1838 bool isPreciseFPEnabled() { 1839 return !CurFPFeatures.getAllowFPReassociate() && 1840 !CurFPFeatures.getNoSignedZero() && 1841 !CurFPFeatures.getAllowReciprocal() && 1842 !CurFPFeatures.getAllowApproxFunc(); 1843 } 1844 1845 void ActOnPragmaFPEvalMethod(SourceLocation Loc, 1846 LangOptions::FPEvalMethodKind Value); 1847 1848 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control 1849 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, 1850 PragmaFloatControlKind Value); 1851 1852 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 1853 /// pointers_to_members(representation method[, general purpose 1854 /// representation]). 1855 void ActOnPragmaMSPointersToMembers( 1856 LangOptions::PragmaMSPointersToMembersKind Kind, 1857 SourceLocation PragmaLoc); 1858 1859 /// Called on well formed \#pragma vtordisp(). 1860 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, 1861 SourceLocation PragmaLoc, MSVtorDispMode Value); 1862 1863 bool UnifySection(StringRef SectionName, int SectionFlags, 1864 NamedDecl *TheDecl); 1865 bool UnifySection(StringRef SectionName, int SectionFlags, 1866 SourceLocation PragmaSectionLocation); 1867 1868 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 1869 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 1870 PragmaMsStackAction Action, 1871 llvm::StringRef StackSlotLabel, 1872 StringLiteral *SegmentName, llvm::StringRef PragmaName); 1873 1874 /// Called on well formed \#pragma section(). 1875 void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, 1876 StringLiteral *SegmentName); 1877 1878 /// Called on well-formed \#pragma init_seg(). 1879 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 1880 StringLiteral *SegmentName); 1881 1882 /// Called on well-formed \#pragma alloc_text(). 1883 void ActOnPragmaMSAllocText( 1884 SourceLocation PragmaLocation, StringRef Section, 1885 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>> 1886 &Functions); 1887 1888 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma 1889 /// strict_gs_check. 1890 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation, 1891 PragmaMsStackAction Action, 1892 bool Value); 1893 1894 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 1895 void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, 1896 SourceLocation PragmaLoc); 1897 1898 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, 1899 SourceLocation PragmaLoc, 1900 attr::ParsedSubjectMatchRuleSet Rules); 1901 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, 1902 const IdentifierInfo *Namespace); 1903 1904 /// Called on well-formed '\#pragma clang attribute pop'. 1905 void ActOnPragmaAttributePop(SourceLocation PragmaLoc, 1906 const IdentifierInfo *Namespace); 1907 1908 /// Adds the attributes that have been specified using the 1909 /// '\#pragma clang attribute push' directives to the given declaration. 1910 void AddPragmaAttributes(Scope *S, Decl *D); 1911 1912 void PrintPragmaAttributeInstantiationPoint(); 1913 1914 void DiagnoseUnterminatedPragmaAttribute(); 1915 1916 /// Called on well formed \#pragma clang optimize. 1917 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 1918 1919 /// #pragma optimize("[optimization-list]", on | off). 1920 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn); 1921 1922 /// Call on well formed \#pragma function. 1923 void 1924 ActOnPragmaMSFunction(SourceLocation Loc, 1925 const llvm::SmallVectorImpl<StringRef> &NoBuiltins); 1926 1927 /// Only called on function definitions; if there is a pragma in scope 1928 /// with the effect of a range-based optnone, consider marking the function 1929 /// with attribute optnone. 1930 void AddRangeBasedOptnone(FunctionDecl *FD); 1931 1932 /// Only called on function definitions; if there is a `#pragma alloc_text` 1933 /// that decides which code section the function should be in, add 1934 /// attribute section to the function. 1935 void AddSectionMSAllocText(FunctionDecl *FD); 1936 1937 /// Adds the 'optnone' attribute to the function declaration if there 1938 /// are no conflicts; Loc represents the location causing the 'optnone' 1939 /// attribute to be added (usually because of a pragma). 1940 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 1941 1942 /// Only called on function definitions; if there is a MSVC #pragma optimize 1943 /// in scope, consider changing the function's attributes based on the 1944 /// optimization list passed to the pragma. 1945 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD); 1946 1947 /// Only called on function definitions; if there is a pragma in scope 1948 /// with the effect of a range-based no_builtin, consider marking the function 1949 /// with attribute no_builtin. 1950 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD); 1951 1952 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 1953 /// add an appropriate visibility attribute. 1954 void AddPushedVisibilityAttribute(Decl *RD); 1955 1956 /// FreeVisContext - Deallocate and null out VisContext. 1957 void FreeVisContext(); 1958 1959 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 1960 void ActOnPragmaVisibility(const IdentifierInfo *VisType, 1961 SourceLocation PragmaLoc); 1962 1963 /// ActOnPragmaFPContract - Called on well formed 1964 /// \#pragma {STDC,OPENCL} FP_CONTRACT and 1965 /// \#pragma clang fp contract 1966 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); 1967 1968 /// Called on well formed 1969 /// \#pragma clang fp reassociate 1970 /// or 1971 /// \#pragma clang fp reciprocal 1972 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind, 1973 bool IsEnabled); 1974 1975 /// ActOnPragmaFenvAccess - Called on well formed 1976 /// \#pragma STDC FENV_ACCESS 1977 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); 1978 1979 /// ActOnPragmaCXLimitedRange - Called on well formed 1980 /// \#pragma STDC CX_LIMITED_RANGE 1981 void ActOnPragmaCXLimitedRange(SourceLocation Loc, 1982 LangOptions::ComplexRangeKind Range); 1983 1984 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. 1985 void ActOnPragmaFPExceptions(SourceLocation Loc, 1986 LangOptions::FPExceptionModeKind); 1987 1988 /// Called to set constant rounding mode for floating point operations. 1989 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode); 1990 1991 /// Called to set exception behavior for floating point operations. 1992 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); 1993 1994 /// PushNamespaceVisibilityAttr - Note that we've entered a 1995 /// namespace with a visibility attribute. 1996 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 1997 SourceLocation Loc); 1998 1999 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 2000 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 2001 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 2002 2003 /// Handles semantic checking for features that are common to all attributes, 2004 /// such as checking whether a parameter was properly specified, or the 2005 /// correct number of arguments were passed, etc. Returns true if the 2006 /// attribute has been diagnosed. 2007 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, 2008 bool SkipArgCountCheck = false); 2009 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A, 2010 bool SkipArgCountCheck = false); 2011 2012 ///@} 2013 2014 // 2015 // 2016 // ------------------------------------------------------------------------- 2017 // 2018 // 2019 2020 /// \name Availability Attribute Handling 2021 /// Implementations are in SemaAvailability.cpp 2022 ///@{ 2023 2024 public: 2025 /// Issue any -Wunguarded-availability warnings in \c FD 2026 void DiagnoseUnguardedAvailabilityViolations(Decl *FD); 2027 2028 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2029 2030 /// Retrieve the current function, if any, that should be analyzed for 2031 /// potential availability violations. 2032 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); 2033 2034 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 2035 const ObjCInterfaceDecl *UnknownObjCClass, 2036 bool ObjCPropertyAccess, 2037 bool AvoidPartialAvailabilityChecks = false, 2038 ObjCInterfaceDecl *ClassReceiver = nullptr); 2039 2040 ///@} 2041 2042 // 2043 // 2044 // ------------------------------------------------------------------------- 2045 // 2046 // 2047 2048 /// \name Bounds Safety 2049 /// Implementations are in SemaBoundsSafety.cpp 2050 ///@{ 2051 public: 2052 /// Check if applying the specified attribute variant from the "counted by" 2053 /// family of attributes to FieldDecl \p FD is semantically valid. If 2054 /// semantically invalid diagnostics will be emitted explaining the problems. 2055 /// 2056 /// \param FD The FieldDecl to apply the attribute to 2057 /// \param E The count expression on the attribute 2058 /// \param CountInBytes If true the attribute is from the "sized_by" family of 2059 /// attributes. If the false the attribute is from 2060 /// "counted_by" family of attributes. 2061 /// \param OrNull If true the attribute is from the "_or_null" suffixed family 2062 /// of attributes. If false the attribute does not have the 2063 /// suffix. 2064 /// 2065 /// Together \p CountInBytes and \p OrNull decide the attribute variant. E.g. 2066 /// \p CountInBytes and \p OrNull both being true indicates the 2067 /// `counted_by_or_null` attribute. 2068 /// 2069 /// \returns false iff semantically valid. 2070 bool CheckCountedByAttrOnField(FieldDecl *FD, Expr *E, bool CountInBytes, 2071 bool OrNull); 2072 2073 ///@} 2074 2075 // 2076 // 2077 // ------------------------------------------------------------------------- 2078 // 2079 // 2080 2081 /// \name Casts 2082 /// Implementations are in SemaCast.cpp 2083 ///@{ 2084 2085 public: 2086 static bool isCast(CheckedConversionKind CCK) { 2087 return CCK == CheckedConversionKind::CStyleCast || 2088 CCK == CheckedConversionKind::FunctionalCast || 2089 CCK == CheckedConversionKind::OtherCast; 2090 } 2091 2092 /// ActOnCXXNamedCast - Parse 2093 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 2094 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 2095 SourceLocation LAngleBracketLoc, Declarator &D, 2096 SourceLocation RAngleBracketLoc, 2097 SourceLocation LParenLoc, Expr *E, 2098 SourceLocation RParenLoc); 2099 2100 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, 2101 TypeSourceInfo *Ty, Expr *E, 2102 SourceRange AngleBrackets, SourceRange Parens); 2103 2104 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, 2105 ExprResult Operand, 2106 SourceLocation RParenLoc); 2107 2108 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, 2109 Expr *Operand, SourceLocation RParenLoc); 2110 2111 // Checks that reinterpret casts don't have undefined behavior. 2112 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 2113 bool IsDereference, SourceRange Range); 2114 2115 // Checks that the vector type should be initialized from a scalar 2116 // by splatting the value rather than populating a single element. 2117 // This is the case for AltiVecVector types as well as with 2118 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified. 2119 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy); 2120 2121 // Checks if the -faltivec-src-compat=gcc option is specified. 2122 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are 2123 // treated the same way as they are when trying to initialize 2124 // these vectors on gcc (an error is emitted). 2125 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, 2126 QualType SrcTy); 2127 2128 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, 2129 SourceLocation RParenLoc, Expr *Op); 2130 2131 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, 2132 SourceLocation LParenLoc, 2133 Expr *CastExpr, 2134 SourceLocation RParenLoc); 2135 2136 ///@} 2137 2138 // 2139 // 2140 // ------------------------------------------------------------------------- 2141 // 2142 // 2143 2144 /// \name Extra Semantic Checking 2145 /// Implementations are in SemaChecking.cpp 2146 ///@{ 2147 2148 public: 2149 /// Used to change context to isConstantEvaluated without pushing a heavy 2150 /// ExpressionEvaluationContextRecord object. 2151 bool isConstantEvaluatedOverride = false; 2152 2153 bool isConstantEvaluatedContext() const { 2154 return currentEvaluationContext().isConstantEvaluated() || 2155 isConstantEvaluatedOverride; 2156 } 2157 2158 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 2159 unsigned ByteNo) const; 2160 2161 enum FormatArgumentPassingKind { 2162 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments) 2163 FAPK_Variadic, // values to format are passed as variadic arguments 2164 FAPK_VAList, // values to format are passed in a va_list 2165 }; 2166 2167 // Used to grab the relevant information from a FormatAttr and a 2168 // FunctionDeclaration. 2169 struct FormatStringInfo { 2170 unsigned FormatIdx; 2171 unsigned FirstDataArg; 2172 FormatArgumentPassingKind ArgPassingKind; 2173 }; 2174 2175 /// Given a FunctionDecl's FormatAttr, attempts to populate the 2176 /// FomatStringInfo parameter with the FormatAttr's correct format_idx and 2177 /// firstDataArg. Returns true when the format fits the function and the 2178 /// FormatStringInfo has been populated. 2179 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 2180 bool IsVariadic, FormatStringInfo *FSI); 2181 2182 // Used by C++ template instantiation. 2183 ExprResult BuiltinShuffleVector(CallExpr *TheCall); 2184 2185 /// ConvertVectorExpr - Handle __builtin_convertvector 2186 ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 2187 SourceLocation BuiltinLoc, 2188 SourceLocation RParenLoc); 2189 2190 enum FormatStringType { 2191 FST_Scanf, 2192 FST_Printf, 2193 FST_NSString, 2194 FST_Strftime, 2195 FST_Strfmon, 2196 FST_Kprintf, 2197 FST_FreeBSDKPrintf, 2198 FST_OSTrace, 2199 FST_OSLog, 2200 FST_Syslog, 2201 FST_Unknown 2202 }; 2203 static FormatStringType GetFormatStringType(const FormatAttr *Format); 2204 2205 bool FormatStringHasSArg(const StringLiteral *FExpr); 2206 2207 /// Check for comparisons of floating-point values using == and !=. Issue a 2208 /// warning if the comparison is not likely to do what the programmer 2209 /// intended. 2210 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, 2211 BinaryOperatorKind Opcode); 2212 2213 /// Register a magic integral constant to be used as a type tag. 2214 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 2215 uint64_t MagicValue, QualType Type, 2216 bool LayoutCompatible, bool MustBeNull); 2217 2218 struct TypeTagData { 2219 TypeTagData() {} 2220 2221 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) 2222 : Type(Type), LayoutCompatible(LayoutCompatible), 2223 MustBeNull(MustBeNull) {} 2224 2225 QualType Type; 2226 2227 /// If true, \c Type should be compared with other expression's types for 2228 /// layout-compatibility. 2229 LLVM_PREFERRED_TYPE(bool) 2230 unsigned LayoutCompatible : 1; 2231 LLVM_PREFERRED_TYPE(bool) 2232 unsigned MustBeNull : 1; 2233 }; 2234 2235 /// A pair of ArgumentKind identifier and magic value. This uniquely 2236 /// identifies the magic value. 2237 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 2238 2239 /// Diagnoses the current set of gathered accesses. This typically 2240 /// happens at full expression level. The set is cleared after emitting the 2241 /// diagnostics. 2242 void DiagnoseMisalignedMembers(); 2243 2244 /// This function checks if the expression is in the sef of potentially 2245 /// misaligned members and it is converted to some pointer type T with lower 2246 /// or equal alignment requirements. If so it removes it. This is used when 2247 /// we do not want to diagnose such misaligned access (e.g. in conversions to 2248 /// void*). 2249 void DiscardMisalignedMemberAddress(const Type *T, Expr *E); 2250 2251 /// This function calls Action when it determines that E designates a 2252 /// misaligned member due to the packed attribute. This is used to emit 2253 /// local diagnostics like in reference binding. 2254 void RefersToMemberWithReducedAlignment( 2255 Expr *E, 2256 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 2257 Action); 2258 2259 enum class AtomicArgumentOrder { API, AST }; 2260 ExprResult 2261 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 2262 SourceLocation RParenLoc, MultiExprArg Args, 2263 AtomicExpr::AtomicOp Op, 2264 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); 2265 2266 /// Check to see if a given expression could have '.c_str()' called on it. 2267 bool hasCStrMethod(const Expr *E); 2268 2269 /// Diagnose pointers that are always non-null. 2270 /// \param E the expression containing the pointer 2271 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 2272 /// compared to a null pointer 2273 /// \param IsEqual True when the comparison is equal to a null pointer 2274 /// \param Range Extra SourceRange to highlight in the diagnostic 2275 void DiagnoseAlwaysNonNullPointer(Expr *E, 2276 Expr::NullPointerConstantKind NullType, 2277 bool IsEqual, SourceRange Range); 2278 2279 /// CheckParmsForFunctionDef - Check that the parameters of the given 2280 /// function are appropriate for the definition of a function. This 2281 /// takes care of any checks that cannot be performed on the 2282 /// declaration itself, e.g., that the types of each of the function 2283 /// parameters are complete. 2284 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 2285 bool CheckParameterNames); 2286 2287 /// CheckCastAlign - Implements -Wcast-align, which warns when a 2288 /// pointer cast increases the alignment requirements. 2289 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 2290 2291 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 2292 /// to weak/__unsafe_unretained type. 2293 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 2294 2295 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 2296 /// to weak/__unsafe_unretained expression. 2297 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 2298 2299 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 2300 /// statement as a \p Body, and it is located on the same line. 2301 /// 2302 /// This helps prevent bugs due to typos, such as: 2303 /// if (condition); 2304 /// do_stuff(); 2305 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, 2306 unsigned DiagID); 2307 2308 /// Warn if a for/while loop statement \p S, which is followed by 2309 /// \p PossibleBody, has a suspicious null statement as a body. 2310 void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); 2311 2312 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 2313 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 2314 SourceLocation OpLoc); 2315 2316 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 2317 enum VariadicCallType { 2318 VariadicFunction, 2319 VariadicBlock, 2320 VariadicMethod, 2321 VariadicConstructor, 2322 VariadicDoesNotApply 2323 }; 2324 2325 bool IsLayoutCompatible(QualType T1, QualType T2) const; 2326 bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, 2327 const TypeSourceInfo *Derived); 2328 2329 /// CheckFunctionCall - Check a direct function call for various correctness 2330 /// and safety properties not strictly enforced by the C type system. 2331 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 2332 const FunctionProtoType *Proto); 2333 2334 /// \param FPOnly restricts the arguments to floating-point types. 2335 std::optional<QualType> BuiltinVectorMath(CallExpr *TheCall, 2336 bool FPOnly = false); 2337 bool BuiltinVectorToScalarMath(CallExpr *TheCall); 2338 2339 void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, 2340 const Expr *ThisArg, ArrayRef<const Expr *> Args); 2341 2342 /// Handles the checks for format strings, non-POD arguments to vararg 2343 /// functions, NULL arguments passed to non-NULL parameters, diagnose_if 2344 /// attributes and AArch64 SME attributes. 2345 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 2346 const Expr *ThisArg, ArrayRef<const Expr *> Args, 2347 bool IsMemberFunction, SourceLocation Loc, SourceRange Range, 2348 VariadicCallType CallType); 2349 2350 /// \brief Enforce the bounds of a TCB 2351 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 2352 /// directly calls other functions in the same TCB as marked by the 2353 /// enforce_tcb and enforce_tcb_leaf attributes. 2354 void CheckTCBEnforcement(const SourceLocation CallExprLoc, 2355 const NamedDecl *Callee); 2356 2357 void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc); 2358 2359 /// BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 2360 /// TheCall is a constant expression. 2361 bool BuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); 2362 2363 /// BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 2364 /// TheCall is a constant expression in the range [Low, High]. 2365 bool BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, 2366 bool RangeIsError = true); 2367 2368 /// BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 2369 /// TheCall is a constant expression is a multiple of Num.. 2370 bool BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 2371 unsigned Multiple); 2372 2373 /// BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 2374 /// constant expression representing a power of 2. 2375 bool BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); 2376 2377 /// BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 2378 /// a constant expression representing an arbitrary byte value shifted left by 2379 /// a multiple of 8 bits. 2380 bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 2381 unsigned ArgBits); 2382 2383 /// BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 2384 /// TheCall is a constant expression representing either a shifted byte value, 2385 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 2386 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 2387 /// Arm MVE intrinsics. 2388 bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, 2389 unsigned ArgBits); 2390 2391 /// Checks that a call expression's argument count is at least the desired 2392 /// number. This is useful when doing custom type-checking on a variadic 2393 /// function. Returns true on error. 2394 bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount); 2395 2396 /// Checks that a call expression's argument count is at most the desired 2397 /// number. This is useful when doing custom type-checking on a variadic 2398 /// function. Returns true on error. 2399 bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount); 2400 2401 /// Checks that a call expression's argument count is in the desired range. 2402 /// This is useful when doing custom type-checking on a variadic function. 2403 /// Returns true on error. 2404 bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, 2405 unsigned MaxArgCount); 2406 2407 /// Checks that a call expression's argument count is the desired number. 2408 /// This is useful when doing custom type-checking. Returns true on error. 2409 bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount); 2410 2411 /// Returns true if the argument consists of one contiguous run of 1s with any 2412 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, 2413 /// so 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 2414 /// since all 1s are not contiguous. 2415 bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum); 2416 2417 void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, 2418 bool *ICContext = nullptr, 2419 bool IsListInit = false); 2420 2421 bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, 2422 bool CheckForFloatArgs = true); 2423 bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall); 2424 2425 private: 2426 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 2427 const ArraySubscriptExpr *ASE = nullptr, 2428 bool AllowOnePastEnd = true, bool IndexNegated = false); 2429 void CheckArrayAccess(const Expr *E); 2430 2431 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 2432 const FunctionProtoType *Proto); 2433 2434 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 2435 /// such as function pointers returned from functions. 2436 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 2437 2438 /// CheckConstructorCall - Check a constructor call for correctness and safety 2439 /// properties not enforced by the C type system. 2440 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 2441 ArrayRef<const Expr *> Args, 2442 const FunctionProtoType *Proto, SourceLocation Loc); 2443 2444 /// Warn if a pointer or reference argument passed to a function points to an 2445 /// object that is less aligned than the parameter. This can happen when 2446 /// creating a typedef with a lower alignment than the original type and then 2447 /// calling functions defined in terms of the original type. 2448 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 2449 StringRef ParamName, QualType ArgTy, QualType ParamTy); 2450 2451 ExprResult CheckOSLogFormatStringArg(Expr *Arg); 2452 2453 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 2454 CallExpr *TheCall); 2455 2456 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2457 CallExpr *TheCall); 2458 2459 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); 2460 2461 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 2462 /// for validity. Emit an error and return true on failure; return false 2463 /// on success. 2464 bool BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); 2465 bool BuiltinVAStartARMMicrosoft(CallExpr *Call); 2466 2467 /// BuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 2468 /// friends. This is declared to take (...), so we have to check everything. 2469 bool BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID); 2470 2471 /// BuiltinSemaBuiltinFPClassification - Handle functions like 2472 /// __builtin_isnan and friends. This is declared to take (...), so we have 2473 /// to check everything. 2474 bool BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs, 2475 unsigned BuiltinID); 2476 2477 /// Perform semantic analysis for a call to __builtin_complex. 2478 bool BuiltinComplex(CallExpr *TheCall); 2479 bool BuiltinOSLogFormat(CallExpr *TheCall); 2480 2481 /// BuiltinPrefetch - Handle __builtin_prefetch. 2482 /// This is declared to take (const void*, ...) and can take two 2483 /// optional constant int args. 2484 bool BuiltinPrefetch(CallExpr *TheCall); 2485 2486 /// Handle __builtin_alloca_with_align. This is declared 2487 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 2488 /// than 8. 2489 bool BuiltinAllocaWithAlign(CallExpr *TheCall); 2490 2491 /// BuiltinArithmeticFence - Handle __arithmetic_fence. 2492 bool BuiltinArithmeticFence(CallExpr *TheCall); 2493 2494 /// BuiltinAssume - Handle __assume (MS Extension). 2495 /// __assume does not evaluate its arguments, and should warn if its argument 2496 /// has side effects. 2497 bool BuiltinAssume(CallExpr *TheCall); 2498 2499 /// Handle __builtin_assume_aligned. This is declared 2500 /// as (const void*, size_t, ...) and can take one optional constant int arg. 2501 bool BuiltinAssumeAligned(CallExpr *TheCall); 2502 2503 /// BuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 2504 /// This checks that the target supports __builtin_longjmp and 2505 /// that val is a constant 1. 2506 bool BuiltinLongjmp(CallExpr *TheCall); 2507 2508 /// BuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 2509 /// This checks that the target supports __builtin_setjmp. 2510 bool BuiltinSetjmp(CallExpr *TheCall); 2511 2512 /// We have a call to a function like __sync_fetch_and_add, which is an 2513 /// overloaded function based on the pointer type of its first argument. 2514 /// The main BuildCallExpr routines have already promoted the types of 2515 /// arguments because all of these calls are prototyped as void(...). 2516 /// 2517 /// This function goes through and does final semantic checking for these 2518 /// builtins, as well as generating any warnings. 2519 ExprResult BuiltinAtomicOverloaded(ExprResult TheCallResult); 2520 2521 /// BuiltinNontemporalOverloaded - We have a call to 2522 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 2523 /// overloaded function based on the pointer type of its last argument. 2524 /// 2525 /// This function goes through and does final semantic checking for these 2526 /// builtins. 2527 ExprResult BuiltinNontemporalOverloaded(ExprResult TheCallResult); 2528 ExprResult AtomicOpsOverloaded(ExprResult TheCallResult, 2529 AtomicExpr::AtomicOp Op); 2530 2531 /// \param FPOnly restricts the arguments to floating-point types. 2532 bool BuiltinElementwiseMath(CallExpr *TheCall, bool FPOnly = false); 2533 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall); 2534 2535 bool BuiltinNonDeterministicValue(CallExpr *TheCall); 2536 2537 enum BuiltinCountedByRefKind { 2538 AssignmentKind, 2539 InitializerKind, 2540 FunctionArgKind, 2541 ReturnArgKind, 2542 ArraySubscriptKind, 2543 BinaryExprKind, 2544 }; 2545 2546 bool CheckInvalidBuiltinCountedByRef(const Expr *E, 2547 BuiltinCountedByRefKind K); 2548 bool BuiltinCountedByRef(CallExpr *TheCall); 2549 2550 // Matrix builtin handling. 2551 ExprResult BuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); 2552 ExprResult BuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 2553 ExprResult CallResult); 2554 ExprResult BuiltinMatrixColumnMajorStore(CallExpr *TheCall, 2555 ExprResult CallResult); 2556 2557 /// CheckFormatArguments - Check calls to printf and scanf (and similar 2558 /// functions) for correct use of format strings. 2559 /// Returns true if a format string has been fully checked. 2560 bool CheckFormatArguments(const FormatAttr *Format, 2561 ArrayRef<const Expr *> Args, bool IsCXXMember, 2562 VariadicCallType CallType, SourceLocation Loc, 2563 SourceRange Range, 2564 llvm::SmallBitVector &CheckedVarArgs); 2565 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 2566 FormatArgumentPassingKind FAPK, unsigned format_idx, 2567 unsigned firstDataArg, FormatStringType Type, 2568 VariadicCallType CallType, SourceLocation Loc, 2569 SourceRange range, 2570 llvm::SmallBitVector &CheckedVarArgs); 2571 2572 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl); 2573 2574 /// Warn when using the wrong abs() function. 2575 void CheckAbsoluteValueFunction(const CallExpr *Call, 2576 const FunctionDecl *FDecl); 2577 2578 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); 2579 2580 /// Check for dangerous or invalid arguments to memset(). 2581 /// 2582 /// This issues warnings on known problematic, dangerous or unspecified 2583 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 2584 /// function calls. 2585 /// 2586 /// \param Call The call expression to diagnose. 2587 void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, 2588 IdentifierInfo *FnName); 2589 2590 // Warn if the user has made the 'size' argument to strlcpy or strlcat 2591 // be the size of the source, instead of the destination. 2592 void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); 2593 2594 // Warn on anti-patterns as the 'size' argument to strncat. 2595 // The correct size argument should look like following: 2596 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 2597 void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); 2598 2599 /// Alerts the user that they are attempting to free a non-malloc'd object. 2600 void CheckFreeArguments(const CallExpr *E); 2601 2602 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 2603 SourceLocation ReturnLoc, bool isObjCMethod = false, 2604 const AttrVec *Attrs = nullptr, 2605 const FunctionDecl *FD = nullptr); 2606 2607 /// Diagnoses "dangerous" implicit conversions within the given 2608 /// expression (which is a full expression). Implements -Wconversion 2609 /// and -Wsign-compare. 2610 /// 2611 /// \param CC the "context" location of the implicit conversion, i.e. 2612 /// the most location of the syntactic entity requiring the implicit 2613 /// conversion 2614 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 2615 2616 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 2617 /// Input argument E is a logical expression. 2618 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 2619 2620 /// Diagnose when expression is an integer constant expression and its 2621 /// evaluation results in integer overflow 2622 void CheckForIntOverflow(const Expr *E); 2623 void CheckUnsequencedOperations(const Expr *E); 2624 2625 /// Perform semantic checks on a completed expression. This will either 2626 /// be a full-expression or a default argument expression. 2627 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 2628 bool IsConstexpr = false); 2629 2630 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 2631 Expr *Init); 2632 2633 /// A map from magic value to type information. 2634 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 2635 TypeTagForDatatypeMagicValues; 2636 2637 /// Peform checks on a call of a function with argument_with_type_tag 2638 /// or pointer_with_type_tag attributes. 2639 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 2640 const ArrayRef<const Expr *> ExprArgs, 2641 SourceLocation CallSiteLoc); 2642 2643 /// Check if we are taking the address of a packed field 2644 /// as this may be a problem if the pointer value is dereferenced. 2645 void CheckAddressOfPackedMember(Expr *rhs); 2646 2647 /// Helper class that collects misaligned member designations and 2648 /// their location info for delayed diagnostics. 2649 struct MisalignedMember { 2650 Expr *E; 2651 RecordDecl *RD; 2652 ValueDecl *MD; 2653 CharUnits Alignment; 2654 2655 MisalignedMember() : E(), RD(), MD() {} 2656 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, 2657 CharUnits Alignment) 2658 : E(E), RD(RD), MD(MD), Alignment(Alignment) {} 2659 explicit MisalignedMember(Expr *E) 2660 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} 2661 2662 bool operator==(const MisalignedMember &m) { return this->E == m.E; } 2663 }; 2664 /// Small set of gathered accesses to potentially misaligned members 2665 /// due to the packed attribute. 2666 SmallVector<MisalignedMember, 4> MisalignedMembers; 2667 2668 /// Adds an expression to the set of gathered misaligned members. 2669 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 2670 CharUnits Alignment); 2671 ///@} 2672 2673 // 2674 // 2675 // ------------------------------------------------------------------------- 2676 // 2677 // 2678 2679 /// \name C++ Coroutines 2680 /// Implementations are in SemaCoroutine.cpp 2681 ///@{ 2682 2683 public: 2684 /// The C++ "std::coroutine_traits" template, which is defined in 2685 /// \<coroutine_traits> 2686 ClassTemplateDecl *StdCoroutineTraitsCache; 2687 2688 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, 2689 StringRef Keyword); 2690 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); 2691 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); 2692 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); 2693 2694 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc); 2695 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E, 2696 UnresolvedLookupExpr *Lookup); 2697 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, 2698 Expr *Awaiter, bool IsImplicit = false); 2699 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, 2700 UnresolvedLookupExpr *Lookup); 2701 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); 2702 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, 2703 bool IsImplicit = false); 2704 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); 2705 bool buildCoroutineParameterMoves(SourceLocation Loc); 2706 VarDecl *buildCoroutinePromise(SourceLocation Loc); 2707 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); 2708 2709 // As a clang extension, enforces that a non-coroutine function must be marked 2710 // with [[clang::coro_wrapper]] if it returns a type marked with 2711 // [[clang::coro_return_type]]. 2712 // Expects that FD is not a coroutine. 2713 void CheckCoroutineWrapper(FunctionDecl *FD); 2714 /// Lookup 'coroutine_traits' in std namespace and std::experimental 2715 /// namespace. The namespace found is recorded in Namespace. 2716 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, 2717 SourceLocation FuncLoc); 2718 /// Check that the expression co_await promise.final_suspend() shall not be 2719 /// potentially-throwing. 2720 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); 2721 2722 ///@} 2723 2724 // 2725 // 2726 // ------------------------------------------------------------------------- 2727 // 2728 // 2729 2730 /// \name C++ Scope Specifiers 2731 /// Implementations are in SemaCXXScopeSpec.cpp 2732 ///@{ 2733 2734 public: 2735 // Marks SS invalid if it represents an incomplete type. 2736 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 2737 // Complete an enum decl, maybe without a scope spec. 2738 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, 2739 CXXScopeSpec *SS = nullptr); 2740 2741 /// Compute the DeclContext that is associated with the given type. 2742 /// 2743 /// \param T the type for which we are attempting to find a DeclContext. 2744 /// 2745 /// \returns the declaration context represented by the type T, 2746 /// or NULL if the declaration context cannot be computed (e.g., because it is 2747 /// dependent and not the current instantiation). 2748 DeclContext *computeDeclContext(QualType T); 2749 2750 /// Compute the DeclContext that is associated with the given 2751 /// scope specifier. 2752 /// 2753 /// \param SS the C++ scope specifier as it appears in the source 2754 /// 2755 /// \param EnteringContext when true, we will be entering the context of 2756 /// this scope specifier, so we can retrieve the declaration context of a 2757 /// class template or class template partial specialization even if it is 2758 /// not the current instantiation. 2759 /// 2760 /// \returns the declaration context represented by the scope specifier @p SS, 2761 /// or NULL if the declaration context cannot be computed (e.g., because it is 2762 /// dependent and not the current instantiation). 2763 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 2764 bool EnteringContext = false); 2765 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 2766 2767 /// If the given nested name specifier refers to the current 2768 /// instantiation, return the declaration that corresponds to that 2769 /// current instantiation (C++0x [temp.dep.type]p1). 2770 /// 2771 /// \param NNS a dependent nested name specifier. 2772 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 2773 2774 /// The parser has parsed a global nested-name-specifier '::'. 2775 /// 2776 /// \param CCLoc The location of the '::'. 2777 /// 2778 /// \param SS The nested-name-specifier, which will be updated in-place 2779 /// to reflect the parsed nested-name-specifier. 2780 /// 2781 /// \returns true if an error occurred, false otherwise. 2782 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 2783 2784 /// The parser has parsed a '__super' nested-name-specifier. 2785 /// 2786 /// \param SuperLoc The location of the '__super' keyword. 2787 /// 2788 /// \param ColonColonLoc The location of the '::'. 2789 /// 2790 /// \param SS The nested-name-specifier, which will be updated in-place 2791 /// to reflect the parsed nested-name-specifier. 2792 /// 2793 /// \returns true if an error occurred, false otherwise. 2794 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 2795 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 2796 2797 /// Determines whether the given declaration is an valid acceptable 2798 /// result for name lookup of a nested-name-specifier. 2799 /// \param SD Declaration checked for nested-name-specifier. 2800 /// \param IsExtension If not null and the declaration is accepted as an 2801 /// extension, the pointed variable is assigned true. 2802 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, 2803 bool *CanCorrect = nullptr); 2804 2805 /// If the given nested-name-specifier begins with a bare identifier 2806 /// (e.g., Base::), perform name lookup for that identifier as a 2807 /// nested-name-specifier within the given scope, and return the result of 2808 /// that name lookup. 2809 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 2810 2811 /// Keeps information about an identifier in a nested-name-spec. 2812 /// 2813 struct NestedNameSpecInfo { 2814 /// The type of the object, if we're parsing nested-name-specifier in 2815 /// a member access expression. 2816 ParsedType ObjectType; 2817 2818 /// The identifier preceding the '::'. 2819 IdentifierInfo *Identifier; 2820 2821 /// The location of the identifier. 2822 SourceLocation IdentifierLoc; 2823 2824 /// The location of the '::'. 2825 SourceLocation CCLoc; 2826 2827 /// Creates info object for the most typical case. 2828 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 2829 SourceLocation ColonColonLoc, 2830 ParsedType ObjectType = ParsedType()) 2831 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), 2832 CCLoc(ColonColonLoc) {} 2833 2834 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 2835 SourceLocation ColonColonLoc, QualType ObjectType) 2836 : ObjectType(ParsedType::make(ObjectType)), Identifier(II), 2837 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {} 2838 }; 2839 2840 /// Build a new nested-name-specifier for "identifier::", as described 2841 /// by ActOnCXXNestedNameSpecifier. 2842 /// 2843 /// \param S Scope in which the nested-name-specifier occurs. 2844 /// \param IdInfo Parser information about an identifier in the 2845 /// nested-name-spec. 2846 /// \param EnteringContext If true, enter the context specified by the 2847 /// nested-name-specifier. 2848 /// \param SS Optional nested name specifier preceding the identifier. 2849 /// \param ScopeLookupResult Provides the result of name lookup within the 2850 /// scope of the nested-name-specifier that was computed at template 2851 /// definition time. 2852 /// \param ErrorRecoveryLookup Specifies if the method is called to improve 2853 /// error recovery and what kind of recovery is performed. 2854 /// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':' 2855 /// are allowed. The bool value pointed by this parameter is set to 2856 /// 'true' if the identifier is treated as if it was followed by ':', 2857 /// not '::'. 2858 /// \param OnlyNamespace If true, only considers namespaces in lookup. 2859 /// 2860 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in 2861 /// that it contains an extra parameter \p ScopeLookupResult, which provides 2862 /// the result of name lookup within the scope of the nested-name-specifier 2863 /// that was computed at template definition time. 2864 /// 2865 /// If ErrorRecoveryLookup is true, then this call is used to improve error 2866 /// recovery. This means that it should not emit diagnostics, it should 2867 /// just return true on failure. It also means it should only return a valid 2868 /// scope if it *knows* that the result is correct. It should not return in a 2869 /// dependent context, for example. Nor will it extend \p SS with the scope 2870 /// specifier. 2871 bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, 2872 bool EnteringContext, CXXScopeSpec &SS, 2873 NamedDecl *ScopeLookupResult, 2874 bool ErrorRecoveryLookup, 2875 bool *IsCorrectedToColon = nullptr, 2876 bool OnlyNamespace = false); 2877 2878 /// The parser has parsed a nested-name-specifier 'identifier::'. 2879 /// 2880 /// \param S The scope in which this nested-name-specifier occurs. 2881 /// 2882 /// \param IdInfo Parser information about an identifier in the 2883 /// nested-name-spec. 2884 /// 2885 /// \param EnteringContext Whether we're entering the context nominated by 2886 /// this nested-name-specifier. 2887 /// 2888 /// \param SS The nested-name-specifier, which is both an input 2889 /// parameter (the nested-name-specifier before this type) and an 2890 /// output parameter (containing the full nested-name-specifier, 2891 /// including this new type). 2892 /// 2893 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 2894 /// are allowed. The bool value pointed by this parameter is set to 'true' 2895 /// if the identifier is treated as if it was followed by ':', not '::'. 2896 /// 2897 /// \param OnlyNamespace If true, only considers namespaces in lookup. 2898 /// 2899 /// \returns true if an error occurred, false otherwise. 2900 bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, 2901 bool EnteringContext, CXXScopeSpec &SS, 2902 bool *IsCorrectedToColon = nullptr, 2903 bool OnlyNamespace = false); 2904 2905 /// The parser has parsed a nested-name-specifier 2906 /// 'template[opt] template-name < template-args >::'. 2907 /// 2908 /// \param S The scope in which this nested-name-specifier occurs. 2909 /// 2910 /// \param SS The nested-name-specifier, which is both an input 2911 /// parameter (the nested-name-specifier before this type) and an 2912 /// output parameter (containing the full nested-name-specifier, 2913 /// including this new type). 2914 /// 2915 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 2916 /// \param TemplateName the template name. 2917 /// \param TemplateNameLoc The location of the template name. 2918 /// \param LAngleLoc The location of the opening angle bracket ('<'). 2919 /// \param TemplateArgs The template arguments. 2920 /// \param RAngleLoc The location of the closing angle bracket ('>'). 2921 /// \param CCLoc The location of the '::'. 2922 /// 2923 /// \param EnteringContext Whether we're entering the context of the 2924 /// nested-name-specifier. 2925 /// 2926 /// 2927 /// \returns true if an error occurred, false otherwise. 2928 bool ActOnCXXNestedNameSpecifier( 2929 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 2930 TemplateTy TemplateName, SourceLocation TemplateNameLoc, 2931 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, 2932 SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); 2933 2934 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, 2935 SourceLocation ColonColonLoc); 2936 2937 bool ActOnCXXNestedNameSpecifierIndexedPack(CXXScopeSpec &SS, 2938 const DeclSpec &DS, 2939 SourceLocation ColonColonLoc, 2940 QualType Type); 2941 2942 /// IsInvalidUnlessNestedName - This method is used for error recovery 2943 /// purposes to determine whether the specified identifier is only valid as 2944 /// a nested name specifier, for example a namespace name. It is 2945 /// conservatively correct to always return false from this method. 2946 /// 2947 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier. 2948 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 2949 NestedNameSpecInfo &IdInfo, 2950 bool EnteringContext); 2951 2952 /// Given a C++ nested-name-specifier, produce an annotation value 2953 /// that the parser can use later to reconstruct the given 2954 /// nested-name-specifier. 2955 /// 2956 /// \param SS A nested-name-specifier. 2957 /// 2958 /// \returns A pointer containing all of the information in the 2959 /// nested-name-specifier \p SS. 2960 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 2961 2962 /// Given an annotation pointer for a nested-name-specifier, restore 2963 /// the nested-name-specifier structure. 2964 /// 2965 /// \param Annotation The annotation pointer, produced by 2966 /// \c SaveNestedNameSpecifierAnnotation(). 2967 /// 2968 /// \param AnnotationRange The source range corresponding to the annotation. 2969 /// 2970 /// \param SS The nested-name-specifier that will be updated with the contents 2971 /// of the annotation pointer. 2972 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 2973 SourceRange AnnotationRange, 2974 CXXScopeSpec &SS); 2975 2976 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 2977 2978 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 2979 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 2980 /// After this method is called, according to [C++ 3.4.3p3], names should be 2981 /// looked up in the declarator-id's scope, until the declarator is parsed and 2982 /// ActOnCXXExitDeclaratorScope is called. 2983 /// The 'SS' should be a non-empty valid CXXScopeSpec. 2984 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 2985 2986 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 2987 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 2988 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 2989 /// Used to indicate that names should revert to being looked up in the 2990 /// defining scope. 2991 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 2992 2993 ///@} 2994 2995 // 2996 // 2997 // ------------------------------------------------------------------------- 2998 // 2999 // 3000 3001 /// \name Declarations 3002 /// Implementations are in SemaDecl.cpp 3003 ///@{ 3004 3005 public: 3006 IdentifierResolver IdResolver; 3007 3008 /// The index of the first InventedParameterInfo that refers to the current 3009 /// context. 3010 unsigned InventedParameterInfosStart = 0; 3011 3012 /// A RAII object to temporarily push a declaration context. 3013 class ContextRAII { 3014 private: 3015 Sema &S; 3016 DeclContext *SavedContext; 3017 ProcessingContextState SavedContextState; 3018 QualType SavedCXXThisTypeOverride; 3019 unsigned SavedFunctionScopesStart; 3020 unsigned SavedInventedParameterInfosStart; 3021 3022 public: 3023 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) 3024 : S(S), SavedContext(S.CurContext), 3025 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 3026 SavedCXXThisTypeOverride(S.CXXThisTypeOverride), 3027 SavedFunctionScopesStart(S.FunctionScopesStart), 3028 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { 3029 assert(ContextToPush && "pushing null context"); 3030 S.CurContext = ContextToPush; 3031 if (NewThisContext) 3032 S.CXXThisTypeOverride = QualType(); 3033 // Any saved FunctionScopes do not refer to this context. 3034 S.FunctionScopesStart = S.FunctionScopes.size(); 3035 S.InventedParameterInfosStart = S.InventedParameterInfos.size(); 3036 } 3037 3038 void pop() { 3039 if (!SavedContext) 3040 return; 3041 S.CurContext = SavedContext; 3042 S.DelayedDiagnostics.popUndelayed(SavedContextState); 3043 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 3044 S.FunctionScopesStart = SavedFunctionScopesStart; 3045 S.InventedParameterInfosStart = SavedInventedParameterInfosStart; 3046 SavedContext = nullptr; 3047 } 3048 3049 ~ContextRAII() { pop(); } 3050 }; 3051 3052 void DiagnoseInvalidJumps(Stmt *Body); 3053 3054 /// The function definitions which were renamed as part of typo-correction 3055 /// to match their respective declarations. We want to keep track of them 3056 /// to ensure that we don't emit a "redefinition" error if we encounter a 3057 /// correctly named definition after the renamed definition. 3058 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; 3059 3060 /// A cache of the flags available in enumerations with the flag_bits 3061 /// attribute. 3062 mutable llvm::DenseMap<const EnumDecl *, llvm::APInt> FlagBitsCache; 3063 3064 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before 3065 /// declared. Rare. May alias another identifier, declared or undeclared. 3066 /// 3067 /// For aliases, the target identifier is used as a key for eventual 3068 /// processing when the target is declared. For the single-identifier form, 3069 /// the sole identifier is used as the key. Each entry is a `SetVector` 3070 /// (ordered by parse order) of aliases (identified by the alias name) in case 3071 /// of multiple aliases to the same undeclared identifier. 3072 llvm::MapVector< 3073 IdentifierInfo *, 3074 llvm::SetVector< 3075 WeakInfo, llvm::SmallVector<WeakInfo, 1u>, 3076 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>> 3077 WeakUndeclaredIdentifiers; 3078 3079 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 3080 /// \#pragma redefine_extname before declared. Used in Solaris system headers 3081 /// to define functions that occur in multiple standards to call the version 3082 /// in the currently selected standard. 3083 llvm::DenseMap<IdentifierInfo *, AsmLabelAttr *> ExtnameUndeclaredIdentifiers; 3084 3085 /// Set containing all typedefs that are likely unused. 3086 llvm::SmallSetVector<const TypedefNameDecl *, 4> 3087 UnusedLocalTypedefNameCandidates; 3088 3089 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 3090 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 3091 UnusedFileScopedDeclsType; 3092 3093 /// The set of file scoped decls seen so far that have not been used 3094 /// and must warn if not used. Only contains the first declaration. 3095 UnusedFileScopedDeclsType UnusedFileScopedDecls; 3096 3097 typedef LazyVector<VarDecl *, ExternalSemaSource, 3098 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 3099 TentativeDefinitionsType; 3100 3101 /// All the tentative definitions encountered in the TU. 3102 TentativeDefinitionsType TentativeDefinitions; 3103 3104 /// All the external declarations encoutered and used in the TU. 3105 SmallVector<DeclaratorDecl *, 4> ExternalDeclarations; 3106 3107 /// Generally null except when we temporarily switch decl contexts, 3108 /// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext. 3109 DeclContext *OriginalLexicalContext; 3110 3111 /// Is the module scope we are in a C++ Header Unit? 3112 bool currentModuleIsHeaderUnit() const { 3113 return ModuleScopes.empty() ? false 3114 : ModuleScopes.back().Module->isHeaderUnit(); 3115 } 3116 3117 /// Get the module owning an entity. 3118 Module *getOwningModule(const Decl *Entity) { 3119 return Entity->getOwningModule(); 3120 } 3121 3122 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 3123 3124 /// If the identifier refers to a type name within this scope, 3125 /// return the declaration of that type. 3126 /// 3127 /// This routine performs ordinary name lookup of the identifier II 3128 /// within the given scope, with optional C++ scope specifier SS, to 3129 /// determine whether the name refers to a type. If so, returns an 3130 /// opaque pointer (actually a QualType) corresponding to that 3131 /// type. Otherwise, returns NULL. 3132 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 3133 Scope *S, CXXScopeSpec *SS = nullptr, 3134 bool isClassName = false, bool HasTrailingDot = false, 3135 ParsedType ObjectType = nullptr, 3136 bool IsCtorOrDtorName = false, 3137 bool WantNontrivialTypeSourceInfo = false, 3138 bool IsClassTemplateDeductionContext = true, 3139 ImplicitTypenameContext AllowImplicitTypename = 3140 ImplicitTypenameContext::No, 3141 IdentifierInfo **CorrectedII = nullptr); 3142 3143 /// isTagName() - This method is called *for error recovery purposes only* 3144 /// to determine if the specified name is a valid tag name ("struct foo"). If 3145 /// so, this returns the TST for the tag corresponding to it (TST_enum, 3146 /// TST_union, TST_struct, TST_interface, TST_class). This is used to 3147 /// diagnose cases in C where the user forgot to specify the tag. 3148 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 3149 3150 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 3151 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 3152 /// then downgrade the missing typename error to a warning. 3153 /// This is needed for MSVC compatibility; Example: 3154 /// @code 3155 /// template<class T> class A { 3156 /// public: 3157 /// typedef int TYPE; 3158 /// }; 3159 /// template<class T> class B : public A<T> { 3160 /// public: 3161 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 3162 /// }; 3163 /// @endcode 3164 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 3165 void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, 3166 Scope *S, CXXScopeSpec *SS, 3167 ParsedType &SuggestedType, 3168 bool IsTemplateName = false); 3169 3170 /// Attempt to behave like MSVC in situations where lookup of an unqualified 3171 /// type name has failed in a dependent context. In these situations, we 3172 /// automatically form a DependentTypeName that will retry lookup in a related 3173 /// scope during instantiation. 3174 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 3175 SourceLocation NameLoc, 3176 bool IsTemplateTypeArg); 3177 3178 /// Describes the result of the name lookup and resolution performed 3179 /// by \c ClassifyName(). 3180 enum NameClassificationKind { 3181 /// This name is not a type or template in this context, but might be 3182 /// something else. 3183 NC_Unknown, 3184 /// Classification failed; an error has been produced. 3185 NC_Error, 3186 /// The name has been typo-corrected to a keyword. 3187 NC_Keyword, 3188 /// The name was classified as a type. 3189 NC_Type, 3190 /// The name was classified as a specific non-type, non-template 3191 /// declaration. ActOnNameClassifiedAsNonType should be called to 3192 /// convert the declaration to an expression. 3193 NC_NonType, 3194 /// The name was classified as an ADL-only function name. 3195 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the 3196 /// result to an expression. 3197 NC_UndeclaredNonType, 3198 /// The name denotes a member of a dependent type that could not be 3199 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to 3200 /// convert the result to an expression. 3201 NC_DependentNonType, 3202 /// The name was classified as an overload set, and an expression 3203 /// representing that overload set has been formed. 3204 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable 3205 /// expression referencing the overload set. 3206 NC_OverloadSet, 3207 /// The name was classified as a template whose specializations are types. 3208 NC_TypeTemplate, 3209 /// The name was classified as a variable template name. 3210 NC_VarTemplate, 3211 /// The name was classified as a function template name. 3212 NC_FunctionTemplate, 3213 /// The name was classified as an ADL-only function template name. 3214 NC_UndeclaredTemplate, 3215 /// The name was classified as a concept name. 3216 NC_Concept, 3217 }; 3218 3219 class NameClassification { 3220 NameClassificationKind Kind; 3221 union { 3222 ExprResult Expr; 3223 NamedDecl *NonTypeDecl; 3224 TemplateName Template; 3225 ParsedType Type; 3226 }; 3227 3228 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 3229 3230 public: 3231 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 3232 3233 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} 3234 3235 static NameClassification Error() { return NameClassification(NC_Error); } 3236 3237 static NameClassification Unknown() { 3238 return NameClassification(NC_Unknown); 3239 } 3240 3241 static NameClassification OverloadSet(ExprResult E) { 3242 NameClassification Result(NC_OverloadSet); 3243 Result.Expr = E; 3244 return Result; 3245 } 3246 3247 static NameClassification NonType(NamedDecl *D) { 3248 NameClassification Result(NC_NonType); 3249 Result.NonTypeDecl = D; 3250 return Result; 3251 } 3252 3253 static NameClassification UndeclaredNonType() { 3254 return NameClassification(NC_UndeclaredNonType); 3255 } 3256 3257 static NameClassification DependentNonType() { 3258 return NameClassification(NC_DependentNonType); 3259 } 3260 3261 static NameClassification TypeTemplate(TemplateName Name) { 3262 NameClassification Result(NC_TypeTemplate); 3263 Result.Template = Name; 3264 return Result; 3265 } 3266 3267 static NameClassification VarTemplate(TemplateName Name) { 3268 NameClassification Result(NC_VarTemplate); 3269 Result.Template = Name; 3270 return Result; 3271 } 3272 3273 static NameClassification FunctionTemplate(TemplateName Name) { 3274 NameClassification Result(NC_FunctionTemplate); 3275 Result.Template = Name; 3276 return Result; 3277 } 3278 3279 static NameClassification Concept(TemplateName Name) { 3280 NameClassification Result(NC_Concept); 3281 Result.Template = Name; 3282 return Result; 3283 } 3284 3285 static NameClassification UndeclaredTemplate(TemplateName Name) { 3286 NameClassification Result(NC_UndeclaredTemplate); 3287 Result.Template = Name; 3288 return Result; 3289 } 3290 3291 NameClassificationKind getKind() const { return Kind; } 3292 3293 ExprResult getExpression() const { 3294 assert(Kind == NC_OverloadSet); 3295 return Expr; 3296 } 3297 3298 ParsedType getType() const { 3299 assert(Kind == NC_Type); 3300 return Type; 3301 } 3302 3303 NamedDecl *getNonTypeDecl() const { 3304 assert(Kind == NC_NonType); 3305 return NonTypeDecl; 3306 } 3307 3308 TemplateName getTemplateName() const { 3309 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 3310 Kind == NC_VarTemplate || Kind == NC_Concept || 3311 Kind == NC_UndeclaredTemplate); 3312 return Template; 3313 } 3314 3315 TemplateNameKind getTemplateNameKind() const { 3316 switch (Kind) { 3317 case NC_TypeTemplate: 3318 return TNK_Type_template; 3319 case NC_FunctionTemplate: 3320 return TNK_Function_template; 3321 case NC_VarTemplate: 3322 return TNK_Var_template; 3323 case NC_Concept: 3324 return TNK_Concept_template; 3325 case NC_UndeclaredTemplate: 3326 return TNK_Undeclared_template; 3327 default: 3328 llvm_unreachable("unsupported name classification."); 3329 } 3330 } 3331 }; 3332 3333 /// Perform name lookup on the given name, classifying it based on 3334 /// the results of name lookup and the following token. 3335 /// 3336 /// This routine is used by the parser to resolve identifiers and help direct 3337 /// parsing. When the identifier cannot be found, this routine will attempt 3338 /// to correct the typo and classify based on the resulting name. 3339 /// 3340 /// \param S The scope in which we're performing name lookup. 3341 /// 3342 /// \param SS The nested-name-specifier that precedes the name. 3343 /// 3344 /// \param Name The identifier. If typo correction finds an alternative name, 3345 /// this pointer parameter will be updated accordingly. 3346 /// 3347 /// \param NameLoc The location of the identifier. 3348 /// 3349 /// \param NextToken The token following the identifier. Used to help 3350 /// disambiguate the name. 3351 /// 3352 /// \param CCC The correction callback, if typo correction is desired. 3353 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, 3354 IdentifierInfo *&Name, SourceLocation NameLoc, 3355 const Token &NextToken, 3356 CorrectionCandidateCallback *CCC = nullptr); 3357 3358 /// Act on the result of classifying a name as an undeclared (ADL-only) 3359 /// non-type declaration. 3360 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 3361 SourceLocation NameLoc); 3362 /// Act on the result of classifying a name as an undeclared member of a 3363 /// dependent base class. 3364 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 3365 IdentifierInfo *Name, 3366 SourceLocation NameLoc, 3367 bool IsAddressOfOperand); 3368 /// Act on the result of classifying a name as a specific non-type 3369 /// declaration. 3370 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 3371 NamedDecl *Found, 3372 SourceLocation NameLoc, 3373 const Token &NextToken); 3374 /// Act on the result of classifying a name as an overload set. 3375 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); 3376 3377 /// Describes the detailed kind of a template name. Used in diagnostics. 3378 enum class TemplateNameKindForDiagnostics { 3379 ClassTemplate, 3380 FunctionTemplate, 3381 VarTemplate, 3382 AliasTemplate, 3383 TemplateTemplateParam, 3384 Concept, 3385 DependentTemplate 3386 }; 3387 TemplateNameKindForDiagnostics 3388 getTemplateNameKindForDiagnostics(TemplateName Name); 3389 3390 /// Determine whether it's plausible that E was intended to be a 3391 /// template-name. 3392 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { 3393 if (!getLangOpts().CPlusPlus || E.isInvalid()) 3394 return false; 3395 Dependent = false; 3396 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) 3397 return !DRE->hasExplicitTemplateArgs(); 3398 if (auto *ME = dyn_cast<MemberExpr>(E.get())) 3399 return !ME->hasExplicitTemplateArgs(); 3400 Dependent = true; 3401 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) 3402 return !DSDRE->hasExplicitTemplateArgs(); 3403 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) 3404 return !DSME->hasExplicitTemplateArgs(); 3405 // Any additional cases recognized here should also be handled by 3406 // diagnoseExprIntendedAsTemplateName. 3407 return false; 3408 } 3409 3410 void warnOnReservedIdentifier(const NamedDecl *D); 3411 3412 Decl *ActOnDeclarator(Scope *S, Declarator &D); 3413 3414 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 3415 MultiTemplateParamsArg TemplateParameterLists); 3416 3417 /// Attempt to fold a variable-sized type to a constant-sized type, returning 3418 /// true if we were successful. 3419 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, 3420 SourceLocation Loc, 3421 unsigned FailedFoldDiagID); 3422 3423 /// Register the given locally-scoped extern "C" declaration so 3424 /// that it can be found later for redeclarations. We include any extern "C" 3425 /// declaration that is not visible in the translation unit here, not just 3426 /// function-scope declarations. 3427 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 3428 3429 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3430 /// If T is the name of a class, then each of the following shall have a 3431 /// name different from T: 3432 /// - every static data member of class T; 3433 /// - every member function of class T 3434 /// - every member of class T that is itself a type; 3435 /// \returns true if the declaration name violates these rules. 3436 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 3437 3438 /// Diagnose a declaration whose declarator-id has the given 3439 /// nested-name-specifier. 3440 /// 3441 /// \param SS The nested-name-specifier of the declarator-id. 3442 /// 3443 /// \param DC The declaration context to which the nested-name-specifier 3444 /// resolves. 3445 /// 3446 /// \param Name The name of the entity being declared. 3447 /// 3448 /// \param Loc The location of the name of the entity being declared. 3449 /// 3450 /// \param IsMemberSpecialization Whether we are declaring a member 3451 /// specialization. 3452 /// 3453 /// \param TemplateId The template-id, if any. 3454 /// 3455 /// \returns true if we cannot safely recover from this error, false 3456 /// otherwise. 3457 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3458 DeclarationName Name, SourceLocation Loc, 3459 TemplateIdAnnotation *TemplateId, 3460 bool IsMemberSpecialization); 3461 3462 bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range); 3463 3464 bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key); 3465 3466 /// Diagnose function specifiers on a declaration of an identifier that 3467 /// does not identify a function. 3468 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 3469 3470 /// Return the declaration shadowed by the given typedef \p D, or null 3471 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 3472 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, 3473 const LookupResult &R); 3474 3475 /// Return the declaration shadowed by the given variable \p D, or null 3476 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 3477 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); 3478 3479 /// Return the declaration shadowed by the given variable \p D, or null 3480 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 3481 NamedDecl *getShadowedDeclaration(const BindingDecl *D, 3482 const LookupResult &R); 3483 /// Diagnose variable or built-in function shadowing. Implements 3484 /// -Wshadow. 3485 /// 3486 /// This method is called whenever a VarDecl is added to a "useful" 3487 /// scope. 3488 /// 3489 /// \param ShadowedDecl the declaration that is shadowed by the given variable 3490 /// \param R the lookup of the name 3491 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 3492 const LookupResult &R); 3493 3494 /// Check -Wshadow without the advantage of a previous lookup. 3495 void CheckShadow(Scope *S, VarDecl *D); 3496 3497 /// Warn if 'E', which is an expression that is about to be modified, refers 3498 /// to a shadowing declaration. 3499 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); 3500 3501 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 3502 /// when these variables are captured by the lambda. 3503 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); 3504 3505 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); 3506 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3507 TypedefNameDecl *NewTD); 3508 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 3509 NamedDecl *ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3510 TypeSourceInfo *TInfo, 3511 LookupResult &Previous); 3512 3513 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 3514 /// declares a typedef-name, either using the 'typedef' type specifier or via 3515 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 3516 NamedDecl *ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, 3517 LookupResult &Previous, bool &Redeclaration); 3518 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3519 TypeSourceInfo *TInfo, 3520 LookupResult &Previous, 3521 MultiTemplateParamsArg TemplateParamLists, 3522 bool &AddToScope, 3523 ArrayRef<BindingDecl *> Bindings = {}); 3524 3525 /// Perform semantic checking on a newly-created variable 3526 /// declaration. 3527 /// 3528 /// This routine performs all of the type-checking required for a 3529 /// variable declaration once it has been built. It is used both to 3530 /// check variables after they have been parsed and their declarators 3531 /// have been translated into a declaration, and to check variables 3532 /// that have been instantiated from a template. 3533 /// 3534 /// Sets NewVD->isInvalidDecl() if an error was encountered. 3535 /// 3536 /// Returns true if the variable declaration is a redeclaration. 3537 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 3538 void CheckVariableDeclarationType(VarDecl *NewVD); 3539 void CheckCompleteVariableDeclaration(VarDecl *VD); 3540 3541 NamedDecl *ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3542 TypeSourceInfo *TInfo, 3543 LookupResult &Previous, 3544 MultiTemplateParamsArg TemplateParamLists, 3545 bool &AddToScope); 3546 3547 /// AddOverriddenMethods - See if a method overrides any in the base classes, 3548 /// and if so, check that it's a valid override and remember it. 3549 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 3550 3551 /// Perform semantic checking of a new function declaration. 3552 /// 3553 /// Performs semantic analysis of the new function declaration 3554 /// NewFD. This routine performs all semantic checking that does not 3555 /// require the actual declarator involved in the declaration, and is 3556 /// used both for the declaration of functions as they are parsed 3557 /// (called via ActOnDeclarator) and for the declaration of functions 3558 /// that have been instantiated via C++ template instantiation (called 3559 /// via InstantiateDecl). 3560 /// 3561 /// \param IsMemberSpecialization whether this new function declaration is 3562 /// a member specialization (that replaces any definition provided by the 3563 /// previous declaration). 3564 /// 3565 /// This sets NewFD->isInvalidDecl() to true if there was an error. 3566 /// 3567 /// \returns true if the function declaration is a redeclaration. 3568 bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 3569 LookupResult &Previous, 3570 bool IsMemberSpecialization, bool DeclIsDefn); 3571 3572 /// Checks if the new declaration declared in dependent context must be 3573 /// put in the same redeclaration chain as the specified declaration. 3574 /// 3575 /// \param D Declaration that is checked. 3576 /// \param PrevDecl Previous declaration found with proper lookup method for 3577 /// the same declaration name. 3578 /// \returns True if D must be added to the redeclaration chain which PrevDecl 3579 /// belongs to. 3580 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); 3581 3582 /// Determines if we can perform a correct type check for \p D as a 3583 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 3584 /// best-effort check. 3585 /// 3586 /// \param NewD The new declaration. 3587 /// \param OldD The old declaration. 3588 /// \param NewT The portion of the type of the new declaration to check. 3589 /// \param OldT The portion of the type of the old declaration to check. 3590 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 3591 QualType NewT, QualType OldT); 3592 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 3593 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 3594 3595 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 3596 /// containing class. Otherwise it will return implicit SectionAttr if the 3597 /// function is a definition and there is an active value on CodeSegStack 3598 /// (from the current #pragma code-seg value). 3599 /// 3600 /// \param FD Function being declared. 3601 /// \param IsDefinition Whether it is a definition or just a declaration. 3602 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 3603 /// nullptr if no attribute should be added. 3604 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 3605 bool IsDefinition); 3606 3607 /// Common checks for a parameter-declaration that should apply to both 3608 /// function parameters and non-type template parameters. 3609 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); 3610 3611 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 3612 /// to introduce parameters into function prototype scope. 3613 Decl *ActOnParamDeclarator(Scope *S, Declarator &D, 3614 SourceLocation ExplicitThisLoc = {}); 3615 3616 /// Synthesizes a variable for a parameter arising from a 3617 /// typedef. 3618 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, 3619 QualType T); 3620 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 3621 SourceLocation NameLoc, 3622 const IdentifierInfo *Name, QualType T, 3623 TypeSourceInfo *TSInfo, StorageClass SC); 3624 3625 // Contexts where using non-trivial C union types can be disallowed. This is 3626 // passed to err_non_trivial_c_union_in_invalid_context. 3627 enum NonTrivialCUnionContext { 3628 // Function parameter. 3629 NTCUC_FunctionParam, 3630 // Function return. 3631 NTCUC_FunctionReturn, 3632 // Default-initialized object. 3633 NTCUC_DefaultInitializedObject, 3634 // Variable with automatic storage duration. 3635 NTCUC_AutoVar, 3636 // Initializer expression that might copy from another object. 3637 NTCUC_CopyInit, 3638 // Assignment. 3639 NTCUC_Assignment, 3640 // Compound literal. 3641 NTCUC_CompoundLiteral, 3642 // Block capture. 3643 NTCUC_BlockCapture, 3644 // lvalue-to-rvalue conversion of volatile type. 3645 NTCUC_LValueToRValueVolatile, 3646 }; 3647 3648 /// Emit diagnostics if the initializer or any of its explicit or 3649 /// implicitly-generated subexpressions require copying or 3650 /// default-initializing a type that is or contains a C union type that is 3651 /// non-trivial to copy or default-initialize. 3652 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); 3653 3654 // These flags are passed to checkNonTrivialCUnion. 3655 enum NonTrivialCUnionKind { 3656 NTCUK_Init = 0x1, 3657 NTCUK_Destruct = 0x2, 3658 NTCUK_Copy = 0x4, 3659 }; 3660 3661 /// Emit diagnostics if a non-trivial C union type or a struct that contains 3662 /// a non-trivial C union is used in an invalid context. 3663 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 3664 NonTrivialCUnionContext UseContext, 3665 unsigned NonTrivialKind); 3666 3667 /// AddInitializerToDecl - Adds the initializer Init to the 3668 /// declaration dcl. If DirectInit is true, this is C++ direct 3669 /// initialization rather than copy initialization. 3670 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); 3671 void ActOnUninitializedDecl(Decl *dcl); 3672 3673 /// ActOnInitializerError - Given that there was an error parsing an 3674 /// initializer for the given declaration, try to at least re-establish 3675 /// invariants such as whether a variable's type is either dependent or 3676 /// complete. 3677 void ActOnInitializerError(Decl *Dcl); 3678 3679 void ActOnCXXForRangeDecl(Decl *D); 3680 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 3681 IdentifierInfo *Ident, 3682 ParsedAttributes &Attrs); 3683 3684 /// Check if VD needs to be dllexport/dllimport due to being in a 3685 /// dllexport/import function. 3686 void CheckStaticLocalForDllExport(VarDecl *VD); 3687 void CheckThreadLocalForLargeAlignment(VarDecl *VD); 3688 3689 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 3690 /// any semantic actions necessary after any initializer has been attached. 3691 void FinalizeDeclaration(Decl *D); 3692 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 3693 ArrayRef<Decl *> Group); 3694 3695 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 3696 /// group, performing any necessary semantic checking. 3697 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); 3698 3699 /// Should be called on all declarations that might have attached 3700 /// documentation comments. 3701 void ActOnDocumentableDecl(Decl *D); 3702 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 3703 3704 enum class FnBodyKind { 3705 /// C++26 [dcl.fct.def.general]p1 3706 /// function-body: 3707 /// ctor-initializer[opt] compound-statement 3708 /// function-try-block 3709 Other, 3710 /// = default ; 3711 Default, 3712 /// deleted-function-body 3713 /// 3714 /// deleted-function-body: 3715 /// = delete ; 3716 /// = delete ( unevaluated-string ) ; 3717 Delete 3718 }; 3719 3720 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 3721 SourceLocation LocAfterDecls); 3722 void CheckForFunctionRedefinition( 3723 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, 3724 SkipBodyInfo *SkipBody = nullptr); 3725 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, 3726 MultiTemplateParamsArg TemplateParamLists, 3727 SkipBodyInfo *SkipBody = nullptr, 3728 FnBodyKind BodyKind = FnBodyKind::Other); 3729 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, 3730 SkipBodyInfo *SkipBody = nullptr, 3731 FnBodyKind BodyKind = FnBodyKind::Other); 3732 void applyFunctionAttributesBeforeParsingBody(Decl *FD); 3733 3734 /// Determine whether we can delay parsing the body of a function or 3735 /// function template until it is used, assuming we don't care about emitting 3736 /// code for that function. 3737 /// 3738 /// This will be \c false if we may need the body of the function in the 3739 /// middle of parsing an expression (where it's impractical to switch to 3740 /// parsing a different function), for instance, if it's constexpr in C++11 3741 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 3742 bool canDelayFunctionBody(const Declarator &D); 3743 3744 /// Determine whether we can skip parsing the body of a function 3745 /// definition, assuming we don't care about analyzing its body or emitting 3746 /// code for that function. 3747 /// 3748 /// This will be \c false only if we may need the body of the function in 3749 /// order to parse the rest of the program (for instance, if it is 3750 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 3751 bool canSkipFunctionBody(Decl *D); 3752 3753 /// Given the set of return statements within a function body, 3754 /// compute the variables that are subject to the named return value 3755 /// optimization. 3756 /// 3757 /// Each of the variables that is subject to the named return value 3758 /// optimization will be marked as NRVO variables in the AST, and any 3759 /// return statement that has a marked NRVO variable as its NRVO candidate can 3760 /// use the named return value optimization. 3761 /// 3762 /// This function applies a very simplistic algorithm for NRVO: if every 3763 /// return statement in the scope of a variable has the same NRVO candidate, 3764 /// that candidate is an NRVO variable. 3765 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 3766 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 3767 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 3768 Decl *ActOnSkippedFunctionBody(Decl *Decl); 3769 void ActOnFinishInlineFunctionDef(FunctionDecl *D); 3770 3771 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 3772 /// attribute for which parsing is delayed. 3773 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 3774 3775 /// Diagnose any unused parameters in the given sequence of 3776 /// ParmVarDecl pointers. 3777 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); 3778 3779 /// Diagnose whether the size of parameters or return value of a 3780 /// function or obj-c method definition is pass-by-value and larger than a 3781 /// specified threshold. 3782 void 3783 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, 3784 QualType ReturnTy, NamedDecl *D); 3785 3786 Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, 3787 SourceLocation RParenLoc); 3788 3789 TopLevelStmtDecl *ActOnStartTopLevelStmtDecl(Scope *S); 3790 void ActOnFinishTopLevelStmtDecl(TopLevelStmtDecl *D, Stmt *Statement); 3791 3792 void ActOnPopScope(SourceLocation Loc, Scope *S); 3793 3794 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3795 /// no declarator (e.g. "struct foo;") is parsed. 3796 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3797 const ParsedAttributesView &DeclAttrs, 3798 RecordDecl *&AnonRecord); 3799 3800 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3801 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3802 /// parameters to cope with template friend declarations. 3803 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3804 const ParsedAttributesView &DeclAttrs, 3805 MultiTemplateParamsArg TemplateParams, 3806 bool IsExplicitInstantiation, 3807 RecordDecl *&AnonRecord, 3808 SourceLocation EllipsisLoc = {}); 3809 3810 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3811 /// anonymous structure or union. Anonymous unions are a C++ feature 3812 /// (C++ [class.union]) and a C11 feature; anonymous structures 3813 /// are a C11 feature and GNU C++ extension. 3814 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, 3815 RecordDecl *Record, 3816 const PrintingPolicy &Policy); 3817 3818 /// Called once it is known whether 3819 /// a tag declaration is an anonymous union or struct. 3820 void ActOnDefinedDeclarationSpecifier(Decl *D); 3821 3822 /// Emit diagnostic warnings for placeholder members. 3823 /// We can only do that after the class is fully constructed, 3824 /// as anonymous union/structs can insert placeholders 3825 /// in their parent scope (which might be a Record). 3826 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record); 3827 3828 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3829 /// Microsoft C anonymous structure. 3830 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3831 /// Example: 3832 /// 3833 /// struct A { int a; }; 3834 /// struct B { struct A; int b; }; 3835 /// 3836 /// void foo() { 3837 /// B var; 3838 /// var.a = 3; 3839 /// } 3840 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3841 RecordDecl *Record); 3842 3843 /// Common ways to introduce type names without a tag for use in diagnostics. 3844 /// Keep in sync with err_tag_reference_non_tag. 3845 enum NonTagKind { 3846 NTK_NonStruct, 3847 NTK_NonClass, 3848 NTK_NonUnion, 3849 NTK_NonEnum, 3850 NTK_Typedef, 3851 NTK_TypeAlias, 3852 NTK_Template, 3853 NTK_TypeAliasTemplate, 3854 NTK_TemplateTemplateArgument, 3855 }; 3856 3857 /// Given a non-tag type declaration, returns an enum useful for indicating 3858 /// what kind of non-tag type this is. 3859 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); 3860 3861 /// Determine whether a tag with a given kind is acceptable 3862 /// as a redeclaration of the given tag declaration. 3863 /// 3864 /// \returns true if the new tag kind is acceptable, false otherwise. 3865 bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, 3866 bool isDefinition, SourceLocation NewTagLoc, 3867 const IdentifierInfo *Name); 3868 3869 enum OffsetOfKind { 3870 // Not parsing a type within __builtin_offsetof. 3871 OOK_Outside, 3872 // Parsing a type within __builtin_offsetof. 3873 OOK_Builtin, 3874 // Parsing a type within macro "offsetof", defined in __buitin_offsetof 3875 // To improve our diagnostic message. 3876 OOK_Macro, 3877 }; 3878 3879 /// This is invoked when we see 'struct foo' or 'struct {'. In the 3880 /// former case, Name will be non-null. In the later case, Name will be null. 3881 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is 3882 /// a reference/declaration/definition of a tag. 3883 /// 3884 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 3885 /// trailing-type-specifier) other than one in an alias-declaration. 3886 /// 3887 /// \param SkipBody If non-null, will be set to indicate if the caller should 3888 /// skip the definition of this tag and treat it as if it were a declaration. 3889 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 3890 SourceLocation KWLoc, CXXScopeSpec &SS, 3891 IdentifierInfo *Name, SourceLocation NameLoc, 3892 const ParsedAttributesView &Attr, AccessSpecifier AS, 3893 SourceLocation ModulePrivateLoc, 3894 MultiTemplateParamsArg TemplateParameterLists, 3895 bool &OwnedDecl, bool &IsDependent, 3896 SourceLocation ScopedEnumKWLoc, 3897 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 3898 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 3899 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr); 3900 3901 /// ActOnField - Each field of a C struct/union is passed into this in order 3902 /// to create a FieldDecl object for it. 3903 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 3904 Declarator &D, Expr *BitfieldWidth); 3905 3906 /// HandleField - Analyze a field of a C struct or a C++ data member. 3907 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 3908 Declarator &D, Expr *BitfieldWidth, 3909 InClassInitStyle InitStyle, AccessSpecifier AS); 3910 3911 /// Build a new FieldDecl and check its well-formedness. 3912 /// 3913 /// This routine builds a new FieldDecl given the fields name, type, 3914 /// record, etc. \p PrevDecl should refer to any previous declaration 3915 /// with the same name and in the same scope as the field to be 3916 /// created. 3917 /// 3918 /// \returns a new FieldDecl. 3919 /// 3920 /// \todo The Declarator argument is a hack. It will be removed once 3921 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 3922 TypeSourceInfo *TInfo, RecordDecl *Record, 3923 SourceLocation Loc, bool Mutable, 3924 Expr *BitfieldWidth, InClassInitStyle InitStyle, 3925 SourceLocation TSSL, AccessSpecifier AS, 3926 NamedDecl *PrevDecl, Declarator *D = nullptr); 3927 3928 bool CheckNontrivialField(FieldDecl *FD); 3929 3930 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 3931 /// class and class extensions. For every class \@interface and class 3932 /// extension \@interface, if the last ivar is a bitfield of any type, 3933 /// then add an implicit `char :0` ivar to the end of that interface. 3934 void ActOnLastBitfield(SourceLocation DeclStart, 3935 SmallVectorImpl<Decl *> &AllIvarDecls); 3936 3937 // This is used for both record definitions and ObjC interface declarations. 3938 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, 3939 ArrayRef<Decl *> Fields, SourceLocation LBrac, 3940 SourceLocation RBrac, const ParsedAttributesView &AttrList); 3941 3942 /// ActOnTagStartDefinition - Invoked when we have entered the 3943 /// scope of a tag's definition (e.g., for an enumeration, class, 3944 /// struct, or union). 3945 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 3946 3947 /// Perform ODR-like check for C/ObjC when merging tag types from modules. 3948 /// Differently from C++, actually parse the body and reject / error out 3949 /// in case of a structural mismatch. 3950 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody); 3951 3952 typedef void *SkippedDefinitionContext; 3953 3954 /// Invoked when we enter a tag definition that we're skipping. 3955 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); 3956 3957 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 3958 /// C++ record definition's base-specifiers clause and are starting its 3959 /// member declarations. 3960 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 3961 SourceLocation FinalLoc, 3962 bool IsFinalSpelledSealed, 3963 bool IsAbstract, 3964 SourceLocation LBraceLoc); 3965 3966 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 3967 /// the definition of a tag (enumeration, class, struct, or union). 3968 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 3969 SourceRange BraceRange); 3970 3971 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); 3972 3973 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 3974 /// error parsing the definition of a tag. 3975 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 3976 3977 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 3978 EnumConstantDecl *LastEnumConst, 3979 SourceLocation IdLoc, IdentifierInfo *Id, 3980 Expr *val); 3981 3982 /// Check that this is a valid underlying type for an enum declaration. 3983 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 3984 3985 /// Check whether this is a valid redeclaration of a previous enumeration. 3986 /// \return true if the redeclaration was invalid. 3987 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 3988 QualType EnumUnderlyingTy, bool IsFixed, 3989 const EnumDecl *Prev); 3990 3991 /// Determine whether the body of an anonymous enumeration should be skipped. 3992 /// \param II The name of the first enumerator. 3993 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 3994 SourceLocation IILoc); 3995 3996 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 3997 SourceLocation IdLoc, IdentifierInfo *Id, 3998 const ParsedAttributesView &Attrs, 3999 SourceLocation EqualLoc, Expr *Val); 4000 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 4001 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, 4002 const ParsedAttributesView &Attr); 4003 4004 /// Set the current declaration context until it gets popped. 4005 void PushDeclContext(Scope *S, DeclContext *DC); 4006 void PopDeclContext(); 4007 4008 /// EnterDeclaratorContext - Used when we must lookup names in the context 4009 /// of a declarator's nested name specifier. 4010 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 4011 void ExitDeclaratorContext(Scope *S); 4012 4013 /// Enter a template parameter scope, after it's been associated with a 4014 /// particular DeclContext. Causes lookup within the scope to chain through 4015 /// enclosing contexts in the correct order. 4016 void EnterTemplatedContext(Scope *S, DeclContext *DC); 4017 4018 /// Push the parameters of D, which must be a function, into scope. 4019 void ActOnReenterFunctionContext(Scope *S, Decl *D); 4020 void ActOnExitFunctionContext(); 4021 4022 /// Add this decl to the scope shadowed decl chains. 4023 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 4024 4025 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 4026 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 4027 /// true if 'D' belongs to the given declaration context. 4028 /// 4029 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 4030 /// enclosing namespace set of the context, rather than contained 4031 /// directly within it. 4032 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 4033 bool AllowInlineNamespace = false) const; 4034 4035 /// Finds the scope corresponding to the given decl context, if it 4036 /// happens to be an enclosing scope. Otherwise return NULL. 4037 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 4038 4039 /// Subroutines of ActOnDeclarator(). 4040 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 4041 TypeSourceInfo *TInfo); 4042 bool isIncompatibleTypedef(const TypeDecl *Old, TypedefNameDecl *New); 4043 4044 /// Describes the kind of merge to perform for availability 4045 /// attributes (including "deprecated", "unavailable", and "availability"). 4046 enum AvailabilityMergeKind { 4047 /// Don't merge availability attributes at all. 4048 AMK_None, 4049 /// Merge availability attributes for a redeclaration, which requires 4050 /// an exact match. 4051 AMK_Redeclaration, 4052 /// Merge availability attributes for an override, which requires 4053 /// an exact match or a weakening of constraints. 4054 AMK_Override, 4055 /// Merge availability attributes for an implementation of 4056 /// a protocol requirement. 4057 AMK_ProtocolImplementation, 4058 /// Merge availability attributes for an implementation of 4059 /// an optional protocol requirement. 4060 AMK_OptionalProtocolImplementation 4061 }; 4062 4063 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 4064 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 4065 AvailabilityMergeKind AMK = AMK_Redeclaration); 4066 4067 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 4068 /// same name and scope as a previous declaration 'Old'. Figure out 4069 /// how to resolve this situation, merging decls or emitting 4070 /// diagnostics as appropriate. If there was an error, set New to be invalid. 4071 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 4072 LookupResult &OldDecls); 4073 4074 /// MergeFunctionDecl - We just parsed a function 'New' from 4075 /// declarator D which has the same name and scope as a previous 4076 /// declaration 'Old'. Figure out how to resolve this situation, 4077 /// merging decls or emitting diagnostics as appropriate. 4078 /// 4079 /// In C++, New and Old must be declarations that are not 4080 /// overloaded. Use IsOverload to determine whether New and Old are 4081 /// overloaded, and to select the Old declaration that New should be 4082 /// merged with. 4083 /// 4084 /// Returns true if there was an error, false otherwise. 4085 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 4086 bool MergeTypeWithOld, bool NewDeclIsDefn); 4087 4088 /// Completes the merge of two function declarations that are 4089 /// known to be compatible. 4090 /// 4091 /// This routine handles the merging of attributes and other 4092 /// properties of function declarations from the old declaration to 4093 /// the new declaration, once we know that New is in fact a 4094 /// redeclaration of Old. 4095 /// 4096 /// \returns false 4097 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4098 Scope *S, bool MergeTypeWithOld); 4099 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 4100 4101 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4102 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4103 /// situation, merging decls or emitting diagnostics as appropriate. 4104 /// 4105 /// Tentative definition rules (C99 6.9.2p2) are checked by 4106 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4107 /// definitions here, since the initializer hasn't been attached. 4108 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 4109 4110 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4111 /// scope as a previous declaration 'Old'. Figure out how to merge their 4112 /// types, emitting diagnostics as appropriate. 4113 /// 4114 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call 4115 /// back to here in AddInitializerToDecl. We can't check them before the 4116 /// initializer is attached. 4117 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 4118 4119 /// We've just determined that \p Old and \p New both appear to be definitions 4120 /// of the same variable. Either diagnose or fix the problem. 4121 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); 4122 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); 4123 4124 /// Filters out lookup results that don't fall within the given scope 4125 /// as determined by isDeclInScope. 4126 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 4127 bool ConsiderLinkage, bool AllowInlineNamespace); 4128 4129 /// We've determined that \p New is a redeclaration of \p Old. Check that they 4130 /// have compatible owning modules. 4131 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); 4132 4133 /// [module.interface]p6: 4134 /// A redeclaration of an entity X is implicitly exported if X was introduced 4135 /// by an exported declaration; otherwise it shall not be exported. 4136 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old); 4137 4138 /// A wrapper function for checking the semantic restrictions of 4139 /// a redeclaration within a module. 4140 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old); 4141 4142 /// Check the redefinition in C++20 Modules. 4143 /// 4144 /// [basic.def.odr]p14: 4145 /// For any definable item D with definitions in multiple translation units, 4146 /// - if D is a non-inline non-templated function or variable, or 4147 /// - if the definitions in different translation units do not satisfy the 4148 /// following requirements, 4149 /// the program is ill-formed; a diagnostic is required only if the 4150 /// definable item is attached to a named module and a prior definition is 4151 /// reachable at the point where a later definition occurs. 4152 /// - Each such definition shall not be attached to a named module 4153 /// ([module.unit]). 4154 /// - Each such definition shall consist of the same sequence of tokens, ... 4155 /// ... 4156 /// 4157 /// Return true if the redefinition is not allowed. Return false otherwise. 4158 bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const; 4159 4160 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 4161 4162 /// If it's a file scoped decl that must warn if not used, keep track 4163 /// of it. 4164 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 4165 4166 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)> 4167 DiagReceiverTy; 4168 4169 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 4170 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D, 4171 DiagReceiverTy DiagReceiver); 4172 void DiagnoseUnusedDecl(const NamedDecl *ND); 4173 4174 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 4175 /// unless they are marked attr(unused). 4176 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver); 4177 4178 /// If VD is set but not otherwise used, diagnose, for a parameter or a 4179 /// variable. 4180 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver); 4181 4182 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 4183 /// from S, where a non-field would be declared. This routine copes 4184 /// with the difference between C and C++ scoping rules in structs and 4185 /// unions. For example, the following code is well-formed in C but 4186 /// ill-formed in C++: 4187 /// @code 4188 /// struct S6 { 4189 /// enum { BAR } e; 4190 /// }; 4191 /// 4192 /// void test_S6() { 4193 /// struct S6 a; 4194 /// a.e = BAR; 4195 /// } 4196 /// @endcode 4197 /// For the declaration of BAR, this routine will return a different 4198 /// scope. The scope S will be the scope of the unnamed enumeration 4199 /// within S6. In C++, this routine will return the scope associated 4200 /// with S6, because the enumeration's scope is a transparent 4201 /// context but structures can contain non-field names. In C, this 4202 /// routine will return the translation unit scope, since the 4203 /// enumeration's scope is a transparent context and structures cannot 4204 /// contain non-field names. 4205 Scope *getNonFieldDeclScope(Scope *S); 4206 4207 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, 4208 SourceLocation Loc); 4209 4210 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 4211 /// file scope. lazily create a decl for it. ForRedeclaration is true 4212 /// if we're creating this built-in in anticipation of redeclaring the 4213 /// built-in. 4214 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, 4215 bool ForRedeclaration, SourceLocation Loc); 4216 4217 /// Get the outermost AttributedType node that sets a calling convention. 4218 /// Valid types should not have multiple attributes with different CCs. 4219 const AttributedType *getCallingConvAttributedType(QualType T) const; 4220 4221 /// GetNameForDeclarator - Determine the full declaration name for the 4222 /// given Declarator. 4223 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 4224 4225 /// Retrieves the declaration name from a parsed unqualified-id. 4226 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 4227 4228 /// ParsingInitForAutoVars - a set of declarations with auto types for which 4229 /// we are currently parsing the initializer. 4230 llvm::SmallPtrSet<const Decl *, 4> ParsingInitForAutoVars; 4231 4232 /// Look for a locally scoped extern "C" declaration by the given name. 4233 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 4234 4235 void deduceOpenCLAddressSpace(ValueDecl *decl); 4236 4237 /// Adjust the \c DeclContext for a function or variable that might be a 4238 /// function-local external declaration. 4239 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 4240 4241 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); 4242 4243 /// Checks if the variant/multiversion functions are compatible. 4244 bool areMultiversionVariantFunctionsCompatible( 4245 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 4246 const PartialDiagnostic &NoProtoDiagID, 4247 const PartialDiagnosticAt &NoteCausedDiagIDAt, 4248 const PartialDiagnosticAt &NoSupportDiagIDAt, 4249 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 4250 bool ConstexprSupported, bool CLinkageMayDiffer); 4251 4252 /// type checking declaration initializers (C99 6.7.8) 4253 bool CheckForConstantInitializer( 4254 Expr *Init, unsigned DiagID = diag::err_init_element_not_constant); 4255 4256 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, 4257 QualType Type, TypeSourceInfo *TSI, 4258 SourceRange Range, bool DirectInit, 4259 Expr *Init); 4260 4261 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 4262 Expr *Init); 4263 4264 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator); 4265 4266 // Heuristically tells if the function is `get_return_object` member of a 4267 // coroutine promise_type by matching the function name. 4268 static bool CanBeGetReturnObject(const FunctionDecl *FD); 4269 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD); 4270 4271 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 4272 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 4273 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 4274 Scope *S); 4275 4276 /// If this function is a C++ replaceable global allocation function 4277 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 4278 /// adds any function attributes that we know a priori based on the standard. 4279 /// 4280 /// We need to check for duplicate attributes both here and where user-written 4281 /// attributes are applied to declarations. 4282 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 4283 FunctionDecl *FD); 4284 4285 /// Adds any function attributes that we know a priori based on 4286 /// the declaration of this function. 4287 /// 4288 /// These attributes can apply both to implicitly-declared builtins 4289 /// (like __builtin___printf_chk) or to library-declared functions 4290 /// like NSLog or printf. 4291 /// 4292 /// We need to check for duplicate attributes both here and where user-written 4293 /// attributes are applied to declarations. 4294 void AddKnownFunctionAttributes(FunctionDecl *FD); 4295 4296 /// VerifyBitField - verifies that a bit field expression is an ICE and has 4297 /// the correct width, and that the field type is valid. 4298 /// Returns false on success. 4299 ExprResult VerifyBitField(SourceLocation FieldLoc, 4300 const IdentifierInfo *FieldName, QualType FieldTy, 4301 bool IsMsStruct, Expr *BitWidth); 4302 4303 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag 4304 /// enum. If AllowMask is true, then we also allow the complement of a valid 4305 /// value, to be used as a mask. 4306 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 4307 bool AllowMask) const; 4308 4309 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 4310 void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, 4311 SourceLocation WeakNameLoc); 4312 4313 /// ActOnPragmaRedefineExtname - Called on well formed 4314 /// \#pragma redefine_extname oldname newname. 4315 void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, 4316 IdentifierInfo *AliasName, 4317 SourceLocation PragmaLoc, 4318 SourceLocation WeakNameLoc, 4319 SourceLocation AliasNameLoc); 4320 4321 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 4322 void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, 4323 SourceLocation PragmaLoc, 4324 SourceLocation WeakNameLoc, 4325 SourceLocation AliasNameLoc); 4326 4327 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. 4328 enum class FunctionEmissionStatus { 4329 Emitted, 4330 CUDADiscarded, // Discarded due to CUDA/HIP hostness 4331 OMPDiscarded, // Discarded due to OpenMP hostness 4332 TemplateDiscarded, // Discarded due to uninstantiated templates 4333 Unknown, 4334 }; 4335 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, 4336 bool Final = false); 4337 4338 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. 4339 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); 4340 4341 private: 4342 /// Function or variable declarations to be checked for whether the deferred 4343 /// diagnostics should be emitted. 4344 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; 4345 4346 /// Map of current shadowing declarations to shadowed declarations. Warn if 4347 /// it looks like the user is trying to modify the shadowing declaration. 4348 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; 4349 4350 // We need this to handle 4351 // 4352 // typedef struct { 4353 // void *foo() { return 0; } 4354 // } A; 4355 // 4356 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 4357 // for example. If 'A', foo will have external linkage. If we have '*A', 4358 // foo will have no linkage. Since we can't know until we get to the end 4359 // of the typedef, this function finds out if D might have non-external 4360 // linkage. Callers should verify at the end of the TU if it D has external 4361 // linkage or not. 4362 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 4363 4364 ///@} 4365 4366 // 4367 // 4368 // ------------------------------------------------------------------------- 4369 // 4370 // 4371 4372 /// \name Declaration Attribute Handling 4373 /// Implementations are in SemaDeclAttr.cpp 4374 ///@{ 4375 4376 public: 4377 /// Describes the kind of priority given to an availability attribute. 4378 /// 4379 /// The sum of priorities deteremines the final priority of the attribute. 4380 /// The final priority determines how the attribute will be merged. 4381 /// An attribute with a lower priority will always remove higher priority 4382 /// attributes for the specified platform when it is being applied. An 4383 /// attribute with a higher priority will not be applied if the declaration 4384 /// already has an availability attribute with a lower priority for the 4385 /// specified platform. The final prirority values are not expected to match 4386 /// the values in this enumeration, but instead should be treated as a plain 4387 /// integer value. This enumeration just names the priority weights that are 4388 /// used to calculate that final vaue. 4389 enum AvailabilityPriority : int { 4390 /// The availability attribute was specified explicitly next to the 4391 /// declaration. 4392 AP_Explicit = 0, 4393 4394 /// The availability attribute was applied using '#pragma clang attribute'. 4395 AP_PragmaClangAttribute = 1, 4396 4397 /// The availability attribute for a specific platform was inferred from 4398 /// an availability attribute for another platform. 4399 AP_InferredFromOtherPlatform = 2 4400 }; 4401 4402 /// Describes the reason a calling convention specification was ignored, used 4403 /// for diagnostics. 4404 enum class CallingConventionIgnoredReason { 4405 ForThisTarget = 0, 4406 VariadicFunction, 4407 ConstructorDestructor, 4408 BuiltinFunction 4409 }; 4410 4411 /// A helper function to provide Attribute Location for the Attr types 4412 /// AND the ParsedAttr. 4413 template <typename AttrInfo> 4414 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation> 4415 getAttrLoc(const AttrInfo &AL) { 4416 return AL.getLocation(); 4417 } 4418 SourceLocation getAttrLoc(const ParsedAttr &AL); 4419 4420 /// If Expr is a valid integer constant, get the value of the integer 4421 /// expression and return success or failure. May output an error. 4422 /// 4423 /// Negative argument is implicitly converted to unsigned, unless 4424 /// \p StrictlyUnsigned is true. 4425 template <typename AttrInfo> 4426 bool checkUInt32Argument(const AttrInfo &AI, const Expr *Expr, uint32_t &Val, 4427 unsigned Idx = UINT_MAX, 4428 bool StrictlyUnsigned = false) { 4429 std::optional<llvm::APSInt> I = llvm::APSInt(32); 4430 if (Expr->isTypeDependent() || 4431 !(I = Expr->getIntegerConstantExpr(Context))) { 4432 if (Idx != UINT_MAX) 4433 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) 4434 << &AI << Idx << AANT_ArgumentIntegerConstant 4435 << Expr->getSourceRange(); 4436 else 4437 Diag(getAttrLoc(AI), diag::err_attribute_argument_type) 4438 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange(); 4439 return false; 4440 } 4441 4442 if (!I->isIntN(32)) { 4443 Diag(Expr->getExprLoc(), diag::err_ice_too_large) 4444 << toString(*I, 10, false) << 32 << /* Unsigned */ 1; 4445 return false; 4446 } 4447 4448 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) { 4449 Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer) 4450 << &AI << /*non-negative*/ 1; 4451 return false; 4452 } 4453 4454 Val = (uint32_t)I->getZExtValue(); 4455 return true; 4456 } 4457 4458 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 4459 /// \#pragma weak during processing of other Decls. 4460 /// I couldn't figure out a clean way to generate these in-line, so 4461 /// we store them here and handle separately -- which is a hack. 4462 /// It would be best to refactor this. 4463 SmallVector<Decl *, 2> WeakTopLevelDecl; 4464 4465 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls 4466 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 4467 4468 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 4469 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 4470 ExtVectorDeclsType; 4471 4472 /// ExtVectorDecls - This is a list all the extended vector types. This allows 4473 /// us to associate a raw vector type with one of the ext_vector type names. 4474 /// This is only necessary for issuing pretty diagnostics. 4475 ExtVectorDeclsType ExtVectorDecls; 4476 4477 /// Check if the argument \p E is a ASCII string literal. If not emit an error 4478 /// and return false, otherwise set \p Str to the value of the string literal 4479 /// and return true. 4480 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, 4481 const Expr *E, StringRef &Str, 4482 SourceLocation *ArgLocation = nullptr); 4483 4484 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 4485 /// If not emit an error and return false. If the argument is an identifier it 4486 /// will emit an error with a fixit hint and treat it as if it was a string 4487 /// literal. 4488 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, 4489 StringRef &Str, 4490 SourceLocation *ArgLocation = nullptr); 4491 4492 /// Determine if type T is a valid subject for a nonnull and similar 4493 /// attributes. Dependent types are considered valid so they can be checked 4494 /// during instantiation time. By default, we look through references (the 4495 /// behavior used by nonnull), but if the second parameter is true, then we 4496 /// treat a reference type as valid. 4497 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 4498 4499 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 4500 /// declaration. 4501 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 4502 Expr *OE); 4503 4504 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular 4505 /// declaration. 4506 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, 4507 Expr *ParamExpr); 4508 4509 bool CheckAttrTarget(const ParsedAttr &CurrAttr); 4510 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); 4511 4512 AvailabilityAttr *mergeAvailabilityAttr( 4513 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, 4514 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, 4515 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, 4516 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, 4517 int Priority, IdentifierInfo *IIEnvironment); 4518 4519 TypeVisibilityAttr * 4520 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 4521 TypeVisibilityAttr::VisibilityType Vis); 4522 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 4523 VisibilityAttr::VisibilityType Vis); 4524 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 4525 StringRef Name); 4526 4527 /// Used to implement to perform semantic checking on 4528 /// attribute((section("foo"))) specifiers. 4529 /// 4530 /// In this case, "foo" is passed in to be checked. If the section 4531 /// specifier is invalid, return an Error that indicates the problem. 4532 /// 4533 /// This is a simple quality of implementation feature to catch errors 4534 /// and give good diagnostics in cases when the assembler or code generator 4535 /// would otherwise reject the section specifier. 4536 llvm::Error isValidSectionSpecifier(StringRef Str); 4537 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); 4538 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 4539 StringRef Name); 4540 4541 // Check for things we'd like to warn about. Multiversioning issues are 4542 // handled later in the process, once we know how many exist. 4543 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); 4544 4545 /// Check Target Version attrs 4546 bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str); 4547 bool checkTargetClonesAttrString( 4548 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, 4549 Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault, 4550 SmallVectorImpl<SmallString<64>> &StringsBuffer); 4551 4552 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, 4553 StringRef NewUserDiagnostic); 4554 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 4555 IdentifierInfo *Format, int FormatIdx, 4556 int FirstArg); 4557 4558 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 4559 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 4560 bool IsPackExpansion); 4561 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, 4562 bool IsPackExpansion); 4563 4564 /// AddAlignValueAttr - Adds an align_value attribute to a particular 4565 /// declaration. 4566 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); 4567 4568 /// CreateAnnotationAttr - Creates an annotation Annot with Args arguments. 4569 Attr *CreateAnnotationAttr(const AttributeCommonInfo &CI, StringRef Annot, 4570 MutableArrayRef<Expr *> Args); 4571 Attr *CreateAnnotationAttr(const ParsedAttr &AL); 4572 4573 bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, 4574 bool BestCase, 4575 MSInheritanceModel SemanticSpelling); 4576 4577 void CheckAlignasUnderalignment(Decl *D); 4578 4579 /// AddModeAttr - Adds a mode attribute to a particular declaration. 4580 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, 4581 bool InInstantiation = false); 4582 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, 4583 const AttributeCommonInfo &CI, 4584 const IdentifierInfo *Ident); 4585 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); 4586 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, 4587 const AttributeCommonInfo &CI); 4588 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); 4589 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, 4590 const InternalLinkageAttr &AL); 4591 4592 /// Check validaty of calling convention attribute \p attr. If \p FD 4593 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device 4594 /// target. Otherwise, it is specified by \p CFT. 4595 bool CheckCallingConvAttr( 4596 const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr, 4597 CUDAFunctionTarget CFT = CUDAFunctionTarget::InvalidTarget); 4598 4599 /// Checks a regparm attribute, returning true if it is ill-formed and 4600 /// otherwise setting numParams to the appropriate value. 4601 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); 4602 4603 /// Create an CUDALaunchBoundsAttr attribute. 4604 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, 4605 Expr *MaxThreads, 4606 Expr *MinBlocks, 4607 Expr *MaxBlocks); 4608 4609 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular 4610 /// declaration. 4611 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 4612 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks); 4613 4614 enum class RetainOwnershipKind { NS, CF, OS }; 4615 4616 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 4617 StringRef UuidAsWritten, MSGuidDecl *GuidDecl); 4618 4619 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL); 4620 4621 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); 4622 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); 4623 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, 4624 const AttributeCommonInfo &CI, 4625 bool BestCase, 4626 MSInheritanceModel Model); 4627 4628 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); 4629 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, 4630 const EnforceTCBLeafAttr &AL); 4631 4632 /// Helper for delayed processing TransparentUnion or 4633 /// BPFPreserveAccessIndexAttr attribute. 4634 void ProcessDeclAttributeDelayed(Decl *D, 4635 const ParsedAttributesView &AttrList); 4636 4637 // Options for ProcessDeclAttributeList(). 4638 struct ProcessDeclAttributeOptions { 4639 ProcessDeclAttributeOptions() 4640 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {} 4641 4642 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) { 4643 ProcessDeclAttributeOptions Result = *this; 4644 Result.IncludeCXX11Attributes = Val; 4645 return Result; 4646 } 4647 4648 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) { 4649 ProcessDeclAttributeOptions Result = *this; 4650 Result.IgnoreTypeAttributes = Val; 4651 return Result; 4652 } 4653 4654 // Should C++11 attributes be processed? 4655 bool IncludeCXX11Attributes; 4656 4657 // Should any type attributes encountered be ignored? 4658 // If this option is false, a diagnostic will be emitted for any type 4659 // attributes of a kind that does not "slide" from the declaration to 4660 // the decl-specifier-seq. 4661 bool IgnoreTypeAttributes; 4662 }; 4663 4664 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 4665 /// attribute list to the specified decl, ignoring any type attributes. 4666 void ProcessDeclAttributeList(Scope *S, Decl *D, 4667 const ParsedAttributesView &AttrList, 4668 const ProcessDeclAttributeOptions &Options = 4669 ProcessDeclAttributeOptions()); 4670 4671 /// Annotation attributes are the only attributes allowed after an access 4672 /// specifier. 4673 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 4674 const ParsedAttributesView &AttrList); 4675 4676 /// checkUnusedDeclAttributes - Given a declarator which is not being 4677 /// used to build a declaration, complain about any decl attributes 4678 /// which might be lying around on it. 4679 void checkUnusedDeclAttributes(Declarator &D); 4680 4681 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 4682 /// \#pragma weak needs a non-definition decl and source may not have one. 4683 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II, 4684 SourceLocation Loc); 4685 4686 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 4687 /// applied to it, possibly with an alias. 4688 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W); 4689 4690 void ProcessPragmaWeak(Scope *S, Decl *D); 4691 // Decl attributes - this routine is the top level dispatcher. 4692 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 4693 4694 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 4695 4696 /// Given a set of delayed diagnostics, re-emit them as if they had 4697 /// been delayed in the current context instead of in the given pool. 4698 /// Essentially, this just moves them to the current pool. 4699 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 4700 4701 /// Check if IdxExpr is a valid parameter index for a function or 4702 /// instance method D. May output an error. 4703 /// 4704 /// \returns true if IdxExpr is a valid index. 4705 template <typename AttrInfo> 4706 bool checkFunctionOrMethodParameterIndex(const Decl *D, const AttrInfo &AI, 4707 unsigned AttrArgNum, 4708 const Expr *IdxExpr, ParamIdx &Idx, 4709 bool CanIndexImplicitThis = false) { 4710 assert(isFunctionOrMethodOrBlockForAttrSubject(D)); 4711 4712 // In C++ the implicit 'this' function parameter also counts. 4713 // Parameters are counted from one. 4714 bool HP = hasFunctionProto(D); 4715 bool HasImplicitThisParam = isInstanceMethod(D); 4716 bool IV = HP && isFunctionOrMethodVariadic(D); 4717 unsigned NumParams = 4718 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 4719 4720 std::optional<llvm::APSInt> IdxInt; 4721 if (IdxExpr->isTypeDependent() || 4722 !(IdxInt = IdxExpr->getIntegerConstantExpr(Context))) { 4723 Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) 4724 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant 4725 << IdxExpr->getSourceRange(); 4726 return false; 4727 } 4728 4729 unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX); 4730 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) { 4731 Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds) 4732 << &AI << AttrArgNum << IdxExpr->getSourceRange(); 4733 return false; 4734 } 4735 if (HasImplicitThisParam && !CanIndexImplicitThis) { 4736 if (IdxSource == 1) { 4737 Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument) 4738 << &AI << IdxExpr->getSourceRange(); 4739 return false; 4740 } 4741 } 4742 4743 Idx = ParamIdx(IdxSource, D); 4744 return true; 4745 } 4746 4747 ///@} 4748 4749 // 4750 // 4751 // ------------------------------------------------------------------------- 4752 // 4753 // 4754 4755 /// \name C++ Declarations 4756 /// Implementations are in SemaDeclCXX.cpp 4757 ///@{ 4758 4759 public: 4760 void CheckDelegatingCtorCycles(); 4761 4762 /// Called before parsing a function declarator belonging to a function 4763 /// declaration. 4764 void ActOnStartFunctionDeclarationDeclarator(Declarator &D, 4765 unsigned TemplateParameterDepth); 4766 4767 /// Called after parsing a function declarator belonging to a function 4768 /// declaration. 4769 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); 4770 4771 // Act on C++ namespaces 4772 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 4773 SourceLocation NamespaceLoc, 4774 SourceLocation IdentLoc, IdentifierInfo *Ident, 4775 SourceLocation LBrace, 4776 const ParsedAttributesView &AttrList, 4777 UsingDirectiveDecl *&UsingDecl, bool IsNested); 4778 4779 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 4780 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 4781 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 4782 4783 NamespaceDecl *getStdNamespace() const; 4784 4785 /// Retrieve the special "std" namespace, which may require us to 4786 /// implicitly define the namespace. 4787 NamespaceDecl *getOrCreateStdNamespace(); 4788 4789 CXXRecordDecl *getStdBadAlloc() const; 4790 EnumDecl *getStdAlignValT() const; 4791 4792 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, 4793 const IdentifierInfo *MemberOrBase); 4794 4795 enum class ComparisonCategoryUsage { 4796 /// The '<=>' operator was used in an expression and a builtin operator 4797 /// was selected. 4798 OperatorInExpression, 4799 /// A defaulted 'operator<=>' needed the comparison category. This 4800 /// typically only applies to 'std::strong_ordering', due to the implicit 4801 /// fallback return value. 4802 DefaultedOperator, 4803 }; 4804 4805 /// Lookup the specified comparison category types in the standard 4806 /// library, an check the VarDecls possibly returned by the operator<=> 4807 /// builtins for that type. 4808 /// 4809 /// \return The type of the comparison category type corresponding to the 4810 /// specified Kind, or a null type if an error occurs 4811 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, 4812 SourceLocation Loc, 4813 ComparisonCategoryUsage Usage); 4814 4815 /// Tests whether Ty is an instance of std::initializer_list and, if 4816 /// it is and Element is not NULL, assigns the element type to Element. 4817 bool isStdInitializerList(QualType Ty, QualType *Element); 4818 4819 /// Looks for the std::initializer_list template and instantiates it 4820 /// with Element, or emits an error if it's not found. 4821 /// 4822 /// \returns The instantiated template, or null on error. 4823 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 4824 4825 /// Determine whether Ctor is an initializer-list constructor, as 4826 /// defined in [dcl.init.list]p2. 4827 bool isInitListConstructor(const FunctionDecl *Ctor); 4828 4829 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, 4830 SourceLocation NamespcLoc, CXXScopeSpec &SS, 4831 SourceLocation IdentLoc, 4832 IdentifierInfo *NamespcName, 4833 const ParsedAttributesView &AttrList); 4834 4835 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 4836 4837 Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, 4838 SourceLocation AliasLoc, IdentifierInfo *Alias, 4839 CXXScopeSpec &SS, SourceLocation IdentLoc, 4840 IdentifierInfo *Ident); 4841 4842 /// Remove decls we can't actually see from a lookup being used to declare 4843 /// shadow using decls. 4844 /// 4845 /// \param S - The scope of the potential shadow decl 4846 /// \param Previous - The lookup of a potential shadow decl's name. 4847 void FilterUsingLookup(Scope *S, LookupResult &lookup); 4848 4849 /// Hides a using shadow declaration. This is required by the current 4850 /// using-decl implementation when a resolvable using declaration in a 4851 /// class is followed by a declaration which would hide or override 4852 /// one or more of the using decl's targets; for example: 4853 /// 4854 /// struct Base { void foo(int); }; 4855 /// struct Derived : Base { 4856 /// using Base::foo; 4857 /// void foo(int); 4858 /// }; 4859 /// 4860 /// The governing language is C++03 [namespace.udecl]p12: 4861 /// 4862 /// When a using-declaration brings names from a base class into a 4863 /// derived class scope, member functions in the derived class 4864 /// override and/or hide member functions with the same name and 4865 /// parameter types in a base class (rather than conflicting). 4866 /// 4867 /// There are two ways to implement this: 4868 /// (1) optimistically create shadow decls when they're not hidden 4869 /// by existing declarations, or 4870 /// (2) don't create any shadow decls (or at least don't make them 4871 /// visible) until we've fully parsed/instantiated the class. 4872 /// The problem with (1) is that we might have to retroactively remove 4873 /// a shadow decl, which requires several O(n) operations because the 4874 /// decl structures are (very reasonably) not designed for removal. 4875 /// (2) avoids this but is very fiddly and phase-dependent. 4876 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 4877 4878 /// Determines whether to create a using shadow decl for a particular 4879 /// decl, given the set of decls existing prior to this using lookup. 4880 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, 4881 const LookupResult &PreviousDecls, 4882 UsingShadowDecl *&PrevShadow); 4883 4884 /// Builds a shadow declaration corresponding to a 'using' declaration. 4885 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 4886 NamedDecl *Target, 4887 UsingShadowDecl *PrevDecl); 4888 4889 /// Checks that the given using declaration is not an invalid 4890 /// redeclaration. Note that this is checking only for the using decl 4891 /// itself, not for any ill-formedness among the UsingShadowDecls. 4892 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 4893 bool HasTypenameKeyword, 4894 const CXXScopeSpec &SS, 4895 SourceLocation NameLoc, 4896 const LookupResult &Previous); 4897 4898 /// Checks that the given nested-name qualifier used in a using decl 4899 /// in the current context is appropriately related to the current 4900 /// scope. If an error is found, diagnoses it and returns true. 4901 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's 4902 /// the result of that lookup. UD is likewise nullptr, except when we have an 4903 /// already-populated UsingDecl whose shadow decls contain the same 4904 /// information (i.e. we're instantiating a UsingDecl with non-dependent 4905 /// scope). 4906 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 4907 const CXXScopeSpec &SS, 4908 const DeclarationNameInfo &NameInfo, 4909 SourceLocation NameLoc, 4910 const LookupResult *R = nullptr, 4911 const UsingDecl *UD = nullptr); 4912 4913 /// Builds a using declaration. 4914 /// 4915 /// \param IsInstantiation - Whether this call arises from an 4916 /// instantiation of an unresolved using declaration. We treat 4917 /// the lookup differently for these declarations. 4918 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 4919 SourceLocation UsingLoc, 4920 bool HasTypenameKeyword, 4921 SourceLocation TypenameLoc, CXXScopeSpec &SS, 4922 DeclarationNameInfo NameInfo, 4923 SourceLocation EllipsisLoc, 4924 const ParsedAttributesView &AttrList, 4925 bool IsInstantiation, bool IsUsingIfExists); 4926 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 4927 SourceLocation UsingLoc, 4928 SourceLocation EnumLoc, 4929 SourceLocation NameLoc, 4930 TypeSourceInfo *EnumType, EnumDecl *ED); 4931 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 4932 ArrayRef<NamedDecl *> Expansions); 4933 4934 /// Additional checks for a using declaration referring to a constructor name. 4935 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 4936 4937 /// Given a derived-class using shadow declaration for a constructor and the 4938 /// correspnding base class constructor, find or create the implicit 4939 /// synthesized derived class constructor to use for this initialization. 4940 CXXConstructorDecl * 4941 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, 4942 ConstructorUsingShadowDecl *DerivedShadow); 4943 4944 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, 4945 SourceLocation UsingLoc, 4946 SourceLocation TypenameLoc, CXXScopeSpec &SS, 4947 UnqualifiedId &Name, SourceLocation EllipsisLoc, 4948 const ParsedAttributesView &AttrList); 4949 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, 4950 SourceLocation UsingLoc, 4951 SourceLocation EnumLoc, SourceRange TyLoc, 4952 const IdentifierInfo &II, ParsedType Ty, 4953 CXXScopeSpec *SS = nullptr); 4954 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, 4955 MultiTemplateParamsArg TemplateParams, 4956 SourceLocation UsingLoc, UnqualifiedId &Name, 4957 const ParsedAttributesView &AttrList, 4958 TypeResult Type, Decl *DeclFromDeclSpec); 4959 4960 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 4961 /// including handling of its default argument expressions. 4962 /// 4963 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 4964 ExprResult BuildCXXConstructExpr( 4965 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, 4966 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 4967 bool HadMultipleCandidates, bool IsListInitialization, 4968 bool IsStdInitListInitialization, bool RequiresZeroInit, 4969 CXXConstructionKind ConstructKind, SourceRange ParenRange); 4970 4971 /// Build a CXXConstructExpr whose constructor has already been resolved if 4972 /// it denotes an inherited constructor. 4973 ExprResult BuildCXXConstructExpr( 4974 SourceLocation ConstructLoc, QualType DeclInitType, 4975 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, 4976 bool HadMultipleCandidates, bool IsListInitialization, 4977 bool IsStdInitListInitialization, bool RequiresZeroInit, 4978 CXXConstructionKind ConstructKind, SourceRange ParenRange); 4979 4980 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 4981 // the constructor can be elidable? 4982 ExprResult BuildCXXConstructExpr( 4983 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, 4984 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, 4985 bool HadMultipleCandidates, bool IsListInitialization, 4986 bool IsStdInitListInitialization, bool RequiresZeroInit, 4987 CXXConstructionKind ConstructKind, SourceRange ParenRange); 4988 4989 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, 4990 SourceLocation InitLoc); 4991 4992 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 4993 /// constructed variable. 4994 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 4995 4996 /// Helper class that collects exception specifications for 4997 /// implicitly-declared special member functions. 4998 class ImplicitExceptionSpecification { 4999 // Pointer to allow copying 5000 Sema *Self; 5001 // We order exception specifications thus: 5002 // noexcept is the most restrictive, but is only used in C++11. 5003 // throw() comes next. 5004 // Then a throw(collected exceptions) 5005 // Finally no specification, which is expressed as noexcept(false). 5006 // throw(...) is used instead if any called function uses it. 5007 ExceptionSpecificationType ComputedEST; 5008 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 5009 SmallVector<QualType, 4> Exceptions; 5010 5011 void ClearExceptions() { 5012 ExceptionsSeen.clear(); 5013 Exceptions.clear(); 5014 } 5015 5016 public: 5017 explicit ImplicitExceptionSpecification(Sema &Self) 5018 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 5019 if (!Self.getLangOpts().CPlusPlus11) 5020 ComputedEST = EST_DynamicNone; 5021 } 5022 5023 /// Get the computed exception specification type. 5024 ExceptionSpecificationType getExceptionSpecType() const { 5025 assert(!isComputedNoexcept(ComputedEST) && 5026 "noexcept(expr) should not be a possible result"); 5027 return ComputedEST; 5028 } 5029 5030 /// The number of exceptions in the exception specification. 5031 unsigned size() const { return Exceptions.size(); } 5032 5033 /// The set of exceptions in the exception specification. 5034 const QualType *data() const { return Exceptions.data(); } 5035 5036 /// Integrate another called method into the collected data. 5037 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 5038 5039 /// Integrate an invoked expression into the collected data. 5040 void CalledExpr(Expr *E) { CalledStmt(E); } 5041 5042 /// Integrate an invoked statement into the collected data. 5043 void CalledStmt(Stmt *S); 5044 5045 /// Overwrite an EPI's exception specification with this 5046 /// computed exception specification. 5047 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 5048 FunctionProtoType::ExceptionSpecInfo ESI; 5049 ESI.Type = getExceptionSpecType(); 5050 if (ESI.Type == EST_Dynamic) { 5051 ESI.Exceptions = Exceptions; 5052 } else if (ESI.Type == EST_None) { 5053 /// C++11 [except.spec]p14: 5054 /// The exception-specification is noexcept(false) if the set of 5055 /// potential exceptions of the special member function contains "any" 5056 ESI.Type = EST_NoexceptFalse; 5057 ESI.NoexceptExpr = 5058 Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); 5059 } 5060 return ESI; 5061 } 5062 }; 5063 5064 /// Evaluate the implicit exception specification for a defaulted 5065 /// special member function. 5066 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); 5067 5068 /// Check the given exception-specification and update the 5069 /// exception specification information with the results. 5070 void checkExceptionSpecification(bool IsTopLevel, 5071 ExceptionSpecificationType EST, 5072 ArrayRef<ParsedType> DynamicExceptions, 5073 ArrayRef<SourceRange> DynamicExceptionRanges, 5074 Expr *NoexceptExpr, 5075 SmallVectorImpl<QualType> &Exceptions, 5076 FunctionProtoType::ExceptionSpecInfo &ESI); 5077 5078 /// Add an exception-specification to the given member or friend function 5079 /// (or function template). The exception-specification was parsed 5080 /// after the function itself was declared. 5081 void actOnDelayedExceptionSpecification( 5082 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange, 5083 ArrayRef<ParsedType> DynamicExceptions, 5084 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); 5085 5086 class InheritedConstructorInfo; 5087 5088 /// Determine if a special member function should have a deleted 5089 /// definition when it is defaulted. 5090 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, 5091 InheritedConstructorInfo *ICI = nullptr, 5092 bool Diagnose = false); 5093 5094 /// Produce notes explaining why a defaulted function was defined as deleted. 5095 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); 5096 5097 /// Declare the implicit default constructor for the given class. 5098 /// 5099 /// \param ClassDecl The class declaration into which the implicit 5100 /// default constructor will be added. 5101 /// 5102 /// \returns The implicitly-declared default constructor. 5103 CXXConstructorDecl * 5104 DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl); 5105 5106 /// DefineImplicitDefaultConstructor - Checks for feasibility of 5107 /// defining this constructor as the default constructor. 5108 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 5109 CXXConstructorDecl *Constructor); 5110 5111 /// Declare the implicit destructor for the given class. 5112 /// 5113 /// \param ClassDecl The class declaration into which the implicit 5114 /// destructor will be added. 5115 /// 5116 /// \returns The implicitly-declared destructor. 5117 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 5118 5119 /// DefineImplicitDestructor - Checks for feasibility of 5120 /// defining this destructor as the default destructor. 5121 void DefineImplicitDestructor(SourceLocation CurrentLocation, 5122 CXXDestructorDecl *Destructor); 5123 5124 /// Build an exception spec for destructors that don't have one. 5125 /// 5126 /// C++11 says that user-defined destructors with no exception spec get one 5127 /// that looks as if the destructor was implicitly declared. 5128 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); 5129 5130 /// Define the specified inheriting constructor. 5131 void DefineInheritingConstructor(SourceLocation UseLoc, 5132 CXXConstructorDecl *Constructor); 5133 5134 /// Declare the implicit copy constructor for the given class. 5135 /// 5136 /// \param ClassDecl The class declaration into which the implicit 5137 /// copy constructor will be added. 5138 /// 5139 /// \returns The implicitly-declared copy constructor. 5140 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 5141 5142 /// DefineImplicitCopyConstructor - Checks for feasibility of 5143 /// defining this constructor as the copy constructor. 5144 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5145 CXXConstructorDecl *Constructor); 5146 5147 /// Declare the implicit move constructor for the given class. 5148 /// 5149 /// \param ClassDecl The Class declaration into which the implicit 5150 /// move constructor will be added. 5151 /// 5152 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 5153 /// declared. 5154 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 5155 5156 /// DefineImplicitMoveConstructor - Checks for feasibility of 5157 /// defining this constructor as the move constructor. 5158 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 5159 CXXConstructorDecl *Constructor); 5160 5161 /// Declare the implicit copy assignment operator for the given class. 5162 /// 5163 /// \param ClassDecl The class declaration into which the implicit 5164 /// copy assignment operator will be added. 5165 /// 5166 /// \returns The implicitly-declared copy assignment operator. 5167 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 5168 5169 /// Defines an implicitly-declared copy assignment operator. 5170 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5171 CXXMethodDecl *MethodDecl); 5172 5173 /// Declare the implicit move assignment operator for the given class. 5174 /// 5175 /// \param ClassDecl The Class declaration into which the implicit 5176 /// move assignment operator will be added. 5177 /// 5178 /// \returns The implicitly-declared move assignment operator, or NULL if it 5179 /// wasn't declared. 5180 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 5181 5182 /// Defines an implicitly-declared move assignment operator. 5183 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 5184 CXXMethodDecl *MethodDecl); 5185 5186 /// Check a completed declaration of an implicit special member. 5187 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); 5188 5189 /// Determine whether the given function is an implicitly-deleted 5190 /// special member function. 5191 bool isImplicitlyDeleted(FunctionDecl *FD); 5192 5193 /// Check whether 'this' shows up in the type of a static member 5194 /// function after the (naturally empty) cv-qualifier-seq would be. 5195 /// 5196 /// \returns true if an error occurred. 5197 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 5198 5199 /// Whether this' shows up in the exception specification of a static 5200 /// member function. 5201 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 5202 5203 /// Check whether 'this' shows up in the attributes of the given 5204 /// static member function. 5205 /// 5206 /// \returns true if an error occurred. 5207 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 5208 5209 bool CheckImmediateEscalatingFunctionDefinition( 5210 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI); 5211 5212 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD); 5213 5214 /// Given a constructor and the set of arguments provided for the 5215 /// constructor, convert the arguments and add any required default arguments 5216 /// to form a proper call to this constructor. 5217 /// 5218 /// \returns true if an error occurred, false otherwise. 5219 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 5220 QualType DeclInitType, MultiExprArg ArgsPtr, 5221 SourceLocation Loc, 5222 SmallVectorImpl<Expr *> &ConvertedArgs, 5223 bool AllowExplicit = false, 5224 bool IsListInitialization = false); 5225 5226 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 5227 /// initializer for the declaration 'Dcl'. 5228 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 5229 /// static data member of class X, names should be looked up in the scope of 5230 /// class X. 5231 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 5232 5233 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 5234 /// initializer for the declaration 'Dcl'. 5235 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 5236 5237 /// Define the "body" of the conversion from a lambda object to a 5238 /// function pointer. 5239 /// 5240 /// This routine doesn't actually define a sensible body; rather, it fills 5241 /// in the initialization expression needed to copy the lambda object into 5242 /// the block, and IR generation actually generates the real body of the 5243 /// block pointer conversion. 5244 void 5245 DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, 5246 CXXConversionDecl *Conv); 5247 5248 /// Define the "body" of the conversion from a lambda object to a 5249 /// block pointer. 5250 /// 5251 /// This routine doesn't actually define a sensible body; rather, it fills 5252 /// in the initialization expression needed to copy the lambda object into 5253 /// the block, and IR generation actually generates the real body of the 5254 /// block pointer conversion. 5255 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 5256 CXXConversionDecl *Conv); 5257 5258 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 5259 /// linkage specification, including the language and (if present) 5260 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 5261 /// language string literal. LBraceLoc, if valid, provides the location of 5262 /// the '{' brace. Otherwise, this linkage specification does not 5263 /// have any braces. 5264 Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 5265 Expr *LangStr, SourceLocation LBraceLoc); 5266 5267 /// ActOnFinishLinkageSpecification - Complete the definition of 5268 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 5269 /// valid, it's the position of the closing '}' brace in a linkage 5270 /// specification that uses braces. 5271 Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, 5272 SourceLocation RBraceLoc); 5273 5274 //===--------------------------------------------------------------------===// 5275 // C++ Classes 5276 // 5277 5278 /// Get the class that is directly named by the current context. This is the 5279 /// class for which an unqualified-id in this scope could name a constructor 5280 /// or destructor. 5281 /// 5282 /// If the scope specifier denotes a class, this will be that class. 5283 /// If the scope specifier is empty, this will be the class whose 5284 /// member-specification we are currently within. Otherwise, there 5285 /// is no such class. 5286 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); 5287 5288 /// isCurrentClassName - Determine whether the identifier II is the 5289 /// name of the class type currently being defined. In the case of 5290 /// nested classes, this will only return true if II is the name of 5291 /// the innermost class. 5292 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 5293 const CXXScopeSpec *SS = nullptr); 5294 5295 /// Determine whether the identifier II is a typo for the name of 5296 /// the class type currently being defined. If so, update it to the identifier 5297 /// that should have been used. 5298 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 5299 5300 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 5301 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 5302 SourceLocation ColonLoc, 5303 const ParsedAttributesView &Attrs); 5304 5305 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 5306 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 5307 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 5308 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 5309 /// present (but parsing it has been deferred). 5310 NamedDecl * 5311 ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 5312 MultiTemplateParamsArg TemplateParameterLists, 5313 Expr *BitfieldWidth, const VirtSpecifiers &VS, 5314 InClassInitStyle InitStyle); 5315 5316 /// Enter a new C++ default initializer scope. After calling this, the 5317 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 5318 /// parsing or instantiating the initializer failed. 5319 void ActOnStartCXXInClassMemberInitializer(); 5320 5321 /// This is invoked after parsing an in-class initializer for a 5322 /// non-static C++ class member, and after instantiating an in-class 5323 /// initializer in a class template. Such actions are deferred until the class 5324 /// is complete. 5325 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 5326 SourceLocation EqualLoc, 5327 ExprResult Init); 5328 5329 /// Handle a C++ member initializer using parentheses syntax. 5330 MemInitResult 5331 ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, 5332 IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, 5333 const DeclSpec &DS, SourceLocation IdLoc, 5334 SourceLocation LParenLoc, ArrayRef<Expr *> Args, 5335 SourceLocation RParenLoc, SourceLocation EllipsisLoc); 5336 5337 /// Handle a C++ member initializer using braced-init-list syntax. 5338 MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, 5339 CXXScopeSpec &SS, 5340 IdentifierInfo *MemberOrBase, 5341 ParsedType TemplateTypeTy, 5342 const DeclSpec &DS, SourceLocation IdLoc, 5343 Expr *InitList, SourceLocation EllipsisLoc); 5344 5345 /// Handle a C++ member initializer. 5346 MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, 5347 CXXScopeSpec &SS, 5348 IdentifierInfo *MemberOrBase, 5349 ParsedType TemplateTypeTy, 5350 const DeclSpec &DS, SourceLocation IdLoc, 5351 Expr *Init, SourceLocation EllipsisLoc); 5352 5353 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, 5354 SourceLocation IdLoc); 5355 5356 MemInitResult BuildBaseInitializer(QualType BaseType, 5357 TypeSourceInfo *BaseTInfo, Expr *Init, 5358 CXXRecordDecl *ClassDecl, 5359 SourceLocation EllipsisLoc); 5360 5361 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 5362 CXXRecordDecl *ClassDecl); 5363 5364 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5365 CXXCtorInitializer *Initializer); 5366 5367 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5368 ArrayRef<CXXCtorInitializer *> Initializers = {}); 5369 5370 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 5371 /// mark all the non-trivial destructors of its members and bases as 5372 /// referenced. 5373 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 5374 CXXRecordDecl *Record); 5375 5376 /// Mark destructors of virtual bases of this class referenced. In the Itanium 5377 /// C++ ABI, this is done when emitting a destructor for any non-abstract 5378 /// class. In the Microsoft C++ ABI, this is done any time a class's 5379 /// destructor is referenced. 5380 void MarkVirtualBaseDestructorsReferenced( 5381 SourceLocation Location, CXXRecordDecl *ClassDecl, 5382 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); 5383 5384 /// Do semantic checks to allow the complete destructor variant to be emitted 5385 /// when the destructor is defined in another translation unit. In the Itanium 5386 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they 5387 /// can be emitted in separate TUs. To emit the complete variant, run a subset 5388 /// of the checks performed when emitting a regular destructor. 5389 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 5390 CXXDestructorDecl *Dtor); 5391 5392 /// The list of classes whose vtables have been used within 5393 /// this translation unit, and the source locations at which the 5394 /// first use occurred. 5395 typedef std::pair<CXXRecordDecl *, SourceLocation> VTableUse; 5396 5397 /// The list of vtables that are required but have not yet been 5398 /// materialized. 5399 SmallVector<VTableUse, 16> VTableUses; 5400 5401 /// The set of classes whose vtables have been used within 5402 /// this translation unit, and a bit that will be true if the vtable is 5403 /// required to be emitted (otherwise, it should be emitted only if needed 5404 /// by code generation). 5405 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 5406 5407 /// Load any externally-stored vtable uses. 5408 void LoadExternalVTableUses(); 5409 5410 /// Note that the vtable for the given class was used at the 5411 /// given location. 5412 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 5413 bool DefinitionRequired = false); 5414 5415 /// Mark the exception specifications of all virtual member functions 5416 /// in the given class as needed. 5417 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 5418 const CXXRecordDecl *RD); 5419 5420 /// MarkVirtualMembersReferenced - Will mark all members of the given 5421 /// CXXRecordDecl referenced. 5422 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, 5423 bool ConstexprOnly = false); 5424 5425 /// Define all of the vtables that have been used in this 5426 /// translation unit and reference any virtual members used by those 5427 /// vtables. 5428 /// 5429 /// \returns true if any work was done, false otherwise. 5430 bool DefineUsedVTables(); 5431 5432 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5433 /// special functions, such as the default constructor, copy 5434 /// constructor, or destructor, to the given C++ class (C++ 5435 /// [special]p1). This routine can only be executed just before the 5436 /// definition of the class is complete. 5437 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 5438 5439 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5440 void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, 5441 ArrayRef<CXXCtorInitializer *> MemInits, 5442 bool AnyErrors); 5443 5444 /// Check class-level dllimport/dllexport attribute. The caller must 5445 /// ensure that referenceDLLExportedClassMethods is called some point later 5446 /// when all outer classes of Class are complete. 5447 void checkClassLevelDLLAttribute(CXXRecordDecl *Class); 5448 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); 5449 5450 void referenceDLLExportedClassMethods(); 5451 5452 /// Perform propagation of DLL attributes from a derived class to a 5453 /// templated base class for MS compatibility. 5454 void propagateDLLAttrToBaseClassTemplate( 5455 CXXRecordDecl *Class, Attr *ClassAttr, 5456 ClassTemplateSpecializationDecl *BaseTemplateSpec, 5457 SourceLocation BaseLoc); 5458 5459 /// Perform semantic checks on a class definition that has been 5460 /// completing, introducing implicitly-declared members, checking for 5461 /// abstract types, etc. 5462 /// 5463 /// \param S The scope in which the class was parsed. Null if we didn't just 5464 /// parse a class definition. 5465 /// \param Record The completed class. 5466 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); 5467 5468 /// Check that the C++ class annoated with "trivial_abi" satisfies all the 5469 /// conditions that are needed for the attribute to have an effect. 5470 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); 5471 5472 /// Check that VTable Pointer authentication is only being set on the first 5473 /// first instantiation of the vtable 5474 void checkIncorrectVTablePointerAuthenticationAttribute(CXXRecordDecl &RD); 5475 5476 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, 5477 Decl *TagDecl, SourceLocation LBrac, 5478 SourceLocation RBrac, 5479 const ParsedAttributesView &AttrList); 5480 5481 /// Perform any semantic analysis which needs to be delayed until all 5482 /// pending class member declarations have been parsed. 5483 void ActOnFinishCXXMemberDecls(); 5484 void ActOnFinishCXXNonNestedClass(); 5485 5486 /// This is used to implement the constant expression evaluation part of the 5487 /// attribute enable_if extension. There is nothing in standard C++ which 5488 /// would require reentering parameters. 5489 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 5490 unsigned ActOnReenterTemplateScope(Decl *Template, 5491 llvm::function_ref<Scope *()> EnterScope); 5492 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 5493 5494 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 5495 /// parsing a top-level (non-nested) C++ class, and we are now 5496 /// parsing those parts of the given Method declaration that could 5497 /// not be parsed earlier (C++ [class.mem]p2), such as default 5498 /// arguments. This action should enter the scope of the given 5499 /// Method declaration as if we had just parsed the qualified method 5500 /// name. However, it should not bring the parameters into scope; 5501 /// that will be performed by ActOnDelayedCXXMethodParameter. 5502 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 5503 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 5504 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 5505 5506 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5507 /// processing the delayed method declaration for Method. The method 5508 /// declaration is now considered finished. There may be a separate 5509 /// ActOnStartOfFunctionDef action later (not necessarily 5510 /// immediately!) for this method, if it was also defined inside the 5511 /// class body. 5512 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 5513 void ActOnFinishDelayedMemberInitializers(Decl *Record); 5514 5515 bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, 5516 ASTContext &Ctx, 5517 bool ErrorOnInvalidMessage); 5518 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 5519 Expr *AssertExpr, Expr *AssertMessageExpr, 5520 SourceLocation RParenLoc); 5521 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 5522 Expr *AssertExpr, Expr *AssertMessageExpr, 5523 SourceLocation RParenLoc, bool Failed); 5524 5525 /// Try to print more useful information about a failed static_assert 5526 /// with expression \E 5527 void DiagnoseStaticAssertDetails(const Expr *E); 5528 5529 /// Handle a friend type declaration. This works in tandem with 5530 /// ActOnTag. 5531 /// 5532 /// Notes on friend class templates: 5533 /// 5534 /// We generally treat friend class declarations as if they were 5535 /// declaring a class. So, for example, the elaborated type specifier 5536 /// in a friend declaration is required to obey the restrictions of a 5537 /// class-head (i.e. no typedefs in the scope chain), template 5538 /// parameters are required to match up with simple template-ids, &c. 5539 /// However, unlike when declaring a template specialization, it's 5540 /// okay to refer to a template specialization without an empty 5541 /// template parameter declaration, e.g. 5542 /// friend class A<T>::B<unsigned>; 5543 /// We permit this as a special case; if there are any template 5544 /// parameters present at all, require proper matching, i.e. 5545 /// template <> template \<class T> friend class A<int>::B; 5546 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 5547 MultiTemplateParamsArg TemplateParams, 5548 SourceLocation EllipsisLoc); 5549 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 5550 MultiTemplateParamsArg TemplateParams); 5551 5552 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5553 /// the well-formedness of the constructor declarator @p D with type @p 5554 /// R. If there are any errors in the declarator, this routine will 5555 /// emit diagnostics and set the invalid bit to true. In any case, the type 5556 /// will be updated to reflect a well-formed type for the constructor and 5557 /// returned. 5558 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 5559 StorageClass &SC); 5560 5561 /// CheckConstructor - Checks a fully-formed constructor for 5562 /// well-formedness, issuing any diagnostics required. Returns true if 5563 /// the constructor declarator is invalid. 5564 void CheckConstructor(CXXConstructorDecl *Constructor); 5565 5566 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5567 /// the well-formednes of the destructor declarator @p D with type @p 5568 /// R. If there are any errors in the declarator, this routine will 5569 /// emit diagnostics and set the declarator to invalid. Even if this happens, 5570 /// will be updated to reflect a well-formed type for the destructor and 5571 /// returned. 5572 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 5573 StorageClass &SC); 5574 5575 /// CheckDestructor - Checks a fully-formed destructor definition for 5576 /// well-formedness, issuing any diagnostics required. Returns true 5577 /// on error. 5578 bool CheckDestructor(CXXDestructorDecl *Destructor); 5579 5580 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5581 /// well-formednes of the conversion function declarator @p D with 5582 /// type @p R. If there are any errors in the declarator, this routine 5583 /// will emit diagnostics and return true. Otherwise, it will return 5584 /// false. Either way, the type @p R will be updated to reflect a 5585 /// well-formed type for the conversion operator. 5586 void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC); 5587 5588 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5589 /// the declaration of the given C++ conversion function. This routine 5590 /// is responsible for recording the conversion function in the C++ 5591 /// class, if possible. 5592 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 5593 5594 /// Check the validity of a declarator that we parsed for a deduction-guide. 5595 /// These aren't actually declarators in the grammar, so we need to check that 5596 /// the user didn't specify any pieces that are not part of the 5597 /// deduction-guide grammar. Return true on invalid deduction-guide. 5598 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 5599 StorageClass &SC); 5600 5601 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); 5602 5603 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 5604 CXXSpecialMemberKind CSM, 5605 SourceLocation DefaultLoc); 5606 void CheckDelayedMemberExceptionSpecs(); 5607 5608 /// Kinds of defaulted comparison operator functions. 5609 enum class DefaultedComparisonKind : unsigned char { 5610 /// This is not a defaultable comparison operator. 5611 None, 5612 /// This is an operator== that should be implemented as a series of 5613 /// subobject comparisons. 5614 Equal, 5615 /// This is an operator<=> that should be implemented as a series of 5616 /// subobject comparisons. 5617 ThreeWay, 5618 /// This is an operator!= that should be implemented as a rewrite in terms 5619 /// of a == comparison. 5620 NotEqual, 5621 /// This is an <, <=, >, or >= that should be implemented as a rewrite in 5622 /// terms of a <=> comparison. 5623 Relational, 5624 }; 5625 5626 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, 5627 DefaultedComparisonKind DCK); 5628 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 5629 FunctionDecl *Spaceship); 5630 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, 5631 DefaultedComparisonKind DCK); 5632 5633 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, 5634 QualType R, bool IsLambda, 5635 DeclContext *DC = nullptr); 5636 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D, 5637 DeclarationName Name, QualType R); 5638 void CheckExplicitObjectLambda(Declarator &D); 5639 5640 //===--------------------------------------------------------------------===// 5641 // C++ Derived Classes 5642 // 5643 5644 /// Check the validity of a C++ base class specifier. 5645 /// 5646 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 5647 /// and returns NULL otherwise. 5648 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 5649 SourceRange SpecifierRange, bool Virtual, 5650 AccessSpecifier Access, 5651 TypeSourceInfo *TInfo, 5652 SourceLocation EllipsisLoc); 5653 5654 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 5655 /// one entry in the base class list of a class specifier, for 5656 /// example: 5657 /// class foo : public bar, virtual private baz { 5658 /// 'public bar' and 'virtual private baz' are each base-specifiers. 5659 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 5660 const ParsedAttributesView &Attrs, bool Virtual, 5661 AccessSpecifier Access, ParsedType basetype, 5662 SourceLocation BaseLoc, 5663 SourceLocation EllipsisLoc); 5664 5665 /// Performs the actual work of attaching the given base class 5666 /// specifiers to a C++ class. 5667 bool AttachBaseSpecifiers(CXXRecordDecl *Class, 5668 MutableArrayRef<CXXBaseSpecifier *> Bases); 5669 5670 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 5671 /// class, after checking whether there are any duplicate base 5672 /// classes. 5673 void ActOnBaseSpecifiers(Decl *ClassDecl, 5674 MutableArrayRef<CXXBaseSpecifier *> Bases); 5675 5676 /// Determine whether the type \p Derived is a C++ class that is 5677 /// derived from the type \p Base. 5678 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); 5679 5680 /// Determine whether the type \p Derived is a C++ class that is 5681 /// derived from the type \p Base. 5682 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 5683 CXXBasePaths &Paths); 5684 5685 // FIXME: I don't like this name. 5686 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 5687 5688 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 5689 SourceLocation Loc, SourceRange Range, 5690 CXXCastPath *BasePath = nullptr, 5691 bool IgnoreAccess = false); 5692 5693 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 5694 /// conversion (where Derived and Base are class types) is 5695 /// well-formed, meaning that the conversion is unambiguous (and 5696 /// that all of the base classes are accessible). Returns true 5697 /// and emits a diagnostic if the code is ill-formed, returns false 5698 /// otherwise. Loc is the location where this routine should point to 5699 /// if there is an error, and Range is the source range to highlight 5700 /// if there is an error. 5701 /// 5702 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 5703 /// diagnostic for the respective type of error will be suppressed, but the 5704 /// check for ill-formed code will still be performed. 5705 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 5706 unsigned InaccessibleBaseID, 5707 unsigned AmbiguousBaseConvID, 5708 SourceLocation Loc, SourceRange Range, 5709 DeclarationName Name, CXXCastPath *BasePath, 5710 bool IgnoreAccess = false); 5711 5712 /// Builds a string representing ambiguous paths from a 5713 /// specific derived class to different subobjects of the same base 5714 /// class. 5715 /// 5716 /// This function builds a string that can be used in error messages 5717 /// to show the different paths that one can take through the 5718 /// inheritance hierarchy to go from the derived class to different 5719 /// subobjects of a base class. The result looks something like this: 5720 /// @code 5721 /// struct D -> struct B -> struct A 5722 /// struct D -> struct C -> struct A 5723 /// @endcode 5724 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 5725 5726 bool CheckOverridingFunctionAttributes(CXXMethodDecl *New, 5727 const CXXMethodDecl *Old); 5728 5729 /// CheckOverridingFunctionReturnType - Checks whether the return types are 5730 /// covariant, according to C++ [class.virtual]p5. 5731 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 5732 const CXXMethodDecl *Old); 5733 5734 // Check that the overriding method has no explicit object parameter. 5735 bool CheckExplicitObjectOverride(CXXMethodDecl *New, 5736 const CXXMethodDecl *Old); 5737 5738 /// Mark the given method pure. 5739 /// 5740 /// \param Method the method to be marked pure. 5741 /// 5742 /// \param InitRange the source range that covers the "0" initializer. 5743 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 5744 5745 /// CheckOverrideControl - Check C++11 override control semantics. 5746 void CheckOverrideControl(NamedDecl *D); 5747 5748 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 5749 /// not used in the declaration of an overriding method. 5750 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); 5751 5752 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 5753 /// function overrides a virtual member function marked 'final', according to 5754 /// C++11 [class.virtual]p4. 5755 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 5756 const CXXMethodDecl *Old); 5757 5758 enum AbstractDiagSelID { 5759 AbstractNone = -1, 5760 AbstractReturnType, 5761 AbstractParamType, 5762 AbstractVariableType, 5763 AbstractFieldType, 5764 AbstractIvarType, 5765 AbstractSynthesizedIvarType, 5766 AbstractArrayType 5767 }; 5768 5769 struct TypeDiagnoser; 5770 5771 bool isAbstractType(SourceLocation Loc, QualType T); 5772 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 5773 TypeDiagnoser &Diagnoser); 5774 template <typename... Ts> 5775 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 5776 const Ts &...Args) { 5777 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 5778 return RequireNonAbstractType(Loc, T, Diagnoser); 5779 } 5780 5781 void DiagnoseAbstractType(const CXXRecordDecl *RD); 5782 5783 //===--------------------------------------------------------------------===// 5784 // C++ Overloaded Operators [C++ 13.5] 5785 // 5786 5787 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 5788 /// of this overloaded operator is well-formed. If so, returns false; 5789 /// otherwise, emits appropriate diagnostics and returns true. 5790 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 5791 5792 /// CheckLiteralOperatorDeclaration - Check whether the declaration 5793 /// of this literal operator function is well-formed. If so, returns 5794 /// false; otherwise, emits appropriate diagnostics and returns true. 5795 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 5796 5797 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression 5798 /// found in an explicit(bool) specifier. 5799 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); 5800 5801 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. 5802 /// Returns true if the explicit specifier is now resolved. 5803 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); 5804 5805 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 5806 /// C++ if/switch/while/for statement. 5807 /// e.g: "if (int x = f()) {...}" 5808 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 5809 5810 // Emitting members of dllexported classes is delayed until the class 5811 // (including field initializers) is fully parsed. 5812 SmallVector<CXXRecordDecl *, 4> DelayedDllExportClasses; 5813 SmallVector<CXXMethodDecl *, 4> DelayedDllExportMemberFunctions; 5814 5815 /// Merge the exception specifications of two variable declarations. 5816 /// 5817 /// This is called when there's a redeclaration of a VarDecl. The function 5818 /// checks if the redeclaration might have an exception specification and 5819 /// validates compatibility and merges the specs if necessary. 5820 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 5821 5822 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 5823 /// function, once we already know that they have the same 5824 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 5825 /// error, false otherwise. 5826 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 5827 5828 /// Helpers for dealing with blocks and functions. 5829 void CheckCXXDefaultArguments(FunctionDecl *FD); 5830 5831 /// CheckExtraCXXDefaultArguments - Check for any extra default 5832 /// arguments in the declarator, which is not a function declaration 5833 /// or definition and therefore is not permitted to have default 5834 /// arguments. This routine should be invoked for every declarator 5835 /// that is not a function declaration or definition. 5836 void CheckExtraCXXDefaultArguments(Declarator &D); 5837 5838 CXXSpecialMemberKind getSpecialMember(const CXXMethodDecl *MD) { 5839 return getDefaultedFunctionKind(MD).asSpecialMember(); 5840 } 5841 5842 /// Perform semantic analysis for the variable declaration that 5843 /// occurs within a C++ catch clause, returning the newly-created 5844 /// variable. 5845 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 5846 SourceLocation StartLoc, 5847 SourceLocation IdLoc, 5848 const IdentifierInfo *Id); 5849 5850 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 5851 /// handler. 5852 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 5853 5854 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 5855 5856 /// Handle a friend tag declaration where the scope specifier was 5857 /// templated. 5858 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 5859 unsigned TagSpec, SourceLocation TagLoc, 5860 CXXScopeSpec &SS, IdentifierInfo *Name, 5861 SourceLocation NameLoc, 5862 SourceLocation EllipsisLoc, 5863 const ParsedAttributesView &Attr, 5864 MultiTemplateParamsArg TempParamLists); 5865 5866 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 5867 SourceLocation DeclStart, Declarator &D, 5868 Expr *BitfieldWidth, 5869 InClassInitStyle InitStyle, 5870 AccessSpecifier AS, 5871 const ParsedAttr &MSPropertyAttr); 5872 5873 /// Diagnose why the specified class does not have a trivial special member of 5874 /// the given kind. 5875 void DiagnoseNontrivial(const CXXRecordDecl *Record, 5876 CXXSpecialMemberKind CSM); 5877 5878 enum TrivialABIHandling { 5879 /// The triviality of a method unaffected by "trivial_abi". 5880 TAH_IgnoreTrivialABI, 5881 5882 /// The triviality of a method affected by "trivial_abi". 5883 TAH_ConsiderTrivialABI 5884 }; 5885 5886 /// Determine whether a defaulted or deleted special member function is 5887 /// trivial, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5888 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5889 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, 5890 TrivialABIHandling TAH = TAH_IgnoreTrivialABI, 5891 bool Diagnose = false); 5892 5893 /// For a defaulted function, the kind of defaulted function that it is. 5894 class DefaultedFunctionKind { 5895 LLVM_PREFERRED_TYPE(CXXSpecialMemberKind) 5896 unsigned SpecialMember : 8; 5897 unsigned Comparison : 8; 5898 5899 public: 5900 DefaultedFunctionKind() 5901 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)), 5902 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {} 5903 DefaultedFunctionKind(CXXSpecialMemberKind CSM) 5904 : SpecialMember(llvm::to_underlying(CSM)), 5905 Comparison(llvm::to_underlying(DefaultedComparisonKind::None)) {} 5906 DefaultedFunctionKind(DefaultedComparisonKind Comp) 5907 : SpecialMember(llvm::to_underlying(CXXSpecialMemberKind::Invalid)), 5908 Comparison(llvm::to_underlying(Comp)) {} 5909 5910 bool isSpecialMember() const { 5911 return static_cast<CXXSpecialMemberKind>(SpecialMember) != 5912 CXXSpecialMemberKind::Invalid; 5913 } 5914 bool isComparison() const { 5915 return static_cast<DefaultedComparisonKind>(Comparison) != 5916 DefaultedComparisonKind::None; 5917 } 5918 5919 explicit operator bool() const { 5920 return isSpecialMember() || isComparison(); 5921 } 5922 5923 CXXSpecialMemberKind asSpecialMember() const { 5924 return static_cast<CXXSpecialMemberKind>(SpecialMember); 5925 } 5926 DefaultedComparisonKind asComparison() const { 5927 return static_cast<DefaultedComparisonKind>(Comparison); 5928 } 5929 5930 /// Get the index of this function kind for use in diagnostics. 5931 unsigned getDiagnosticIndex() const { 5932 static_assert(llvm::to_underlying(CXXSpecialMemberKind::Invalid) > 5933 llvm::to_underlying(CXXSpecialMemberKind::Destructor), 5934 "invalid should have highest index"); 5935 static_assert((unsigned)DefaultedComparisonKind::None == 0, 5936 "none should be equal to zero"); 5937 return SpecialMember + Comparison; 5938 } 5939 }; 5940 5941 /// Determine the kind of defaulting that would be done for a given function. 5942 /// 5943 /// If the function is both a default constructor and a copy / move 5944 /// constructor (due to having a default argument for the first parameter), 5945 /// this picks CXXSpecialMemberKind::DefaultConstructor. 5946 /// 5947 /// FIXME: Check that case is properly handled by all callers. 5948 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); 5949 5950 /// Handle a C++11 empty-declaration and attribute-declaration. 5951 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, 5952 SourceLocation SemiLoc); 5953 5954 enum class CheckConstexprKind { 5955 /// Diagnose issues that are non-constant or that are extensions. 5956 Diagnose, 5957 /// Identify whether this function satisfies the formal rules for constexpr 5958 /// functions in the current lanugage mode (with no extensions). 5959 CheckValid 5960 }; 5961 5962 // Check whether a function declaration satisfies the requirements of a 5963 // constexpr function definition or a constexpr constructor definition. If so, 5964 // return true. If not, produce appropriate diagnostics (unless asked not to 5965 // by Kind) and return false. 5966 // 5967 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 5968 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, 5969 CheckConstexprKind Kind); 5970 5971 /// Diagnose methods which overload virtual methods in a base class 5972 /// without overriding any. 5973 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 5974 5975 /// Check if a method overloads virtual methods in a base class without 5976 /// overriding any. 5977 void 5978 FindHiddenVirtualMethods(CXXMethodDecl *MD, 5979 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods); 5980 void 5981 NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5982 SmallVectorImpl<CXXMethodDecl *> &OverloadedMethods); 5983 5984 /// ActOnParamDefaultArgument - Check whether the default argument 5985 /// provided for a function parameter is well-formed. If so, attach it 5986 /// to the parameter declaration. 5987 void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 5988 Expr *defarg); 5989 5990 /// ActOnParamUnparsedDefaultArgument - We've seen a default 5991 /// argument for a function parameter, but we can't parse it yet 5992 /// because we're inside a class definition. Note that this default 5993 /// argument will be parsed later. 5994 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, 5995 SourceLocation ArgLoc); 5996 5997 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 5998 /// the default argument for the parameter param failed. 5999 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, 6000 Expr *DefaultArg); 6001 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 6002 SourceLocation EqualLoc); 6003 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 6004 SourceLocation EqualLoc); 6005 6006 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); 6007 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc, 6008 StringLiteral *Message = nullptr); 6009 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 6010 6011 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, 6012 StringLiteral *DeletedMessage = nullptr); 6013 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); 6014 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); 6015 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); 6016 6017 NamedDecl * 6018 ActOnDecompositionDeclarator(Scope *S, Declarator &D, 6019 MultiTemplateParamsArg TemplateParamLists); 6020 void DiagPlaceholderVariableDefinition(SourceLocation Loc); 6021 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, 6022 RecordDecl *ClassDecl, 6023 const IdentifierInfo *Name); 6024 6025 unsigned GetDecompositionElementCount(QualType DecompType); 6026 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); 6027 6028 /// Stack containing information needed when in C++2a an 'auto' is encountered 6029 /// in a function declaration parameter type specifier in order to invent a 6030 /// corresponding template parameter in the enclosing abbreviated function 6031 /// template. This information is also present in LambdaScopeInfo, stored in 6032 /// the FunctionScopes stack. 6033 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; 6034 6035 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 6036 std::unique_ptr<CXXFieldCollector> FieldCollector; 6037 6038 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType; 6039 /// Set containing all declared private fields that are not used. 6040 NamedDeclSetType UnusedPrivateFields; 6041 6042 typedef llvm::SmallPtrSet<const CXXRecordDecl *, 8> RecordDeclSetTy; 6043 6044 /// PureVirtualClassDiagSet - a set of class declarations which we have 6045 /// emitted a list of pure virtual functions. Used to prevent emitting the 6046 /// same list more than once. 6047 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 6048 6049 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 6050 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 6051 DelegatingCtorDeclsType; 6052 6053 /// All the delegating constructors seen so far in the file, used for 6054 /// cycle detection at the end of the TU. 6055 DelegatingCtorDeclsType DelegatingCtorDecls; 6056 6057 /// The C++ "std" namespace, where the standard library resides. 6058 LazyDeclPtr StdNamespace; 6059 6060 /// The C++ "std::initializer_list" template, which is defined in 6061 /// \<initializer_list>. 6062 ClassTemplateDecl *StdInitializerList; 6063 6064 // Contains the locations of the beginning of unparsed default 6065 // argument locations. 6066 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 6067 6068 /// UndefinedInternals - all the used, undefined objects which require a 6069 /// definition in this translation unit. 6070 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; 6071 6072 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMemberKind> 6073 SpecialMemberDecl; 6074 6075 /// The C++ special members which we are currently in the process of 6076 /// declaring. If this process recursively triggers the declaration of the 6077 /// same special member, we should act as if it is not yet declared. 6078 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 6079 6080 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); 6081 6082 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 6083 6084 typedef ProcessingContextState ParsingClassState; 6085 ParsingClassState PushParsingClass() { 6086 ParsingClassDepth++; 6087 return DelayedDiagnostics.pushUndelayed(); 6088 } 6089 void PopParsingClass(ParsingClassState state) { 6090 ParsingClassDepth--; 6091 DelayedDiagnostics.popUndelayed(state); 6092 } 6093 6094 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 6095 CXXScopeSpec &SS, 6096 ParsedType TemplateTypeTy, 6097 IdentifierInfo *MemberOrBase); 6098 6099 private: 6100 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 6101 QualType ResultTy, 6102 ArrayRef<QualType> Args); 6103 6104 // A cache representing if we've fully checked the various comparison category 6105 // types stored in ASTContext. The bit-index corresponds to the integer value 6106 // of a ComparisonCategoryType enumerator. 6107 llvm::SmallBitVector FullyCheckedComparisonCategories; 6108 6109 /// Check if there is a field shadowing. 6110 void CheckShadowInheritedFields(const SourceLocation &Loc, 6111 DeclarationName FieldName, 6112 const CXXRecordDecl *RD, 6113 bool DeclIsField = true); 6114 6115 ///@} 6116 6117 // 6118 // 6119 // ------------------------------------------------------------------------- 6120 // 6121 // 6122 6123 /// \name C++ Exception Specifications 6124 /// Implementations are in SemaExceptionSpec.cpp 6125 ///@{ 6126 6127 public: 6128 /// All the overriding functions seen during a class definition 6129 /// that had their exception spec checks delayed, plus the overridden 6130 /// function. 6131 SmallVector<std::pair<const CXXMethodDecl *, const CXXMethodDecl *>, 2> 6132 DelayedOverridingExceptionSpecChecks; 6133 6134 /// All the function redeclarations seen during a class definition that had 6135 /// their exception spec checks delayed, plus the prior declaration they 6136 /// should be checked against. Except during error recovery, the new decl 6137 /// should always be a friend declaration, as that's the only valid way to 6138 /// redeclare a special member before its class is complete. 6139 SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 2> 6140 DelayedEquivalentExceptionSpecChecks; 6141 6142 /// Determine if we're in a case where we need to (incorrectly) eagerly 6143 /// parse an exception specification to work around a libstdc++ bug. 6144 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 6145 6146 /// Check the given noexcept-specifier, convert its expression, and compute 6147 /// the appropriate ExceptionSpecificationType. 6148 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr, 6149 ExceptionSpecificationType &EST); 6150 6151 CanThrowResult canThrow(const Stmt *E); 6152 /// Determine whether the callee of a particular function call can throw. 6153 /// E, D and Loc are all optional. 6154 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, 6155 SourceLocation Loc = SourceLocation()); 6156 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 6157 const FunctionProtoType *FPT); 6158 void UpdateExceptionSpec(FunctionDecl *FD, 6159 const FunctionProtoType::ExceptionSpecInfo &ESI); 6160 6161 /// CheckSpecifiedExceptionType - Check if the given type is valid in an 6162 /// exception specification. Incomplete types, or pointers to incomplete types 6163 /// other than void are not allowed. 6164 /// 6165 /// \param[in,out] T The exception type. This will be decayed to a pointer 6166 /// type 6167 /// when the input is an array or a function type. 6168 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); 6169 6170 /// CheckDistantExceptionSpec - Check if the given type is a pointer or 6171 /// pointer to member to a function with an exception specification. This 6172 /// means that it is invalid to add another level of indirection. 6173 bool CheckDistantExceptionSpec(QualType T); 6174 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 6175 6176 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent 6177 /// exception specifications. Exception specifications are equivalent if 6178 /// they allow exactly the same set of exception types. It does not matter how 6179 /// that is achieved. See C++ [except.spec]p2. 6180 bool CheckEquivalentExceptionSpec(const FunctionProtoType *Old, 6181 SourceLocation OldLoc, 6182 const FunctionProtoType *New, 6183 SourceLocation NewLoc); 6184 bool CheckEquivalentExceptionSpec(const PartialDiagnostic &DiagID, 6185 const PartialDiagnostic &NoteID, 6186 const FunctionProtoType *Old, 6187 SourceLocation OldLoc, 6188 const FunctionProtoType *New, 6189 SourceLocation NewLoc); 6190 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); 6191 6192 /// CheckExceptionSpecSubset - Check whether the second function type's 6193 /// exception specification is a subset (or equivalent) of the first function 6194 /// type. This is used by override and pointer assignment checks. 6195 bool CheckExceptionSpecSubset( 6196 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, 6197 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, 6198 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter, 6199 SourceLocation SuperLoc, const FunctionProtoType *Subset, 6200 bool SkipSubsetFirstParameter, SourceLocation SubLoc); 6201 6202 /// CheckParamExceptionSpec - Check if the parameter and return types of the 6203 /// two functions have equivalent exception specs. This is part of the 6204 /// assignment and override compatibility check. We do not check the 6205 /// parameters of parameter function pointers recursively, as no sane 6206 /// programmer would even be able to write such a function type. 6207 bool CheckParamExceptionSpec( 6208 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, 6209 const FunctionProtoType *Target, bool SkipTargetFirstParameter, 6210 SourceLocation TargetLoc, const FunctionProtoType *Source, 6211 bool SkipSourceFirstParameter, SourceLocation SourceLoc); 6212 6213 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 6214 6215 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 6216 /// spec is a subset of base spec. 6217 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 6218 const CXXMethodDecl *Old); 6219 6220 ///@} 6221 6222 // 6223 // 6224 // ------------------------------------------------------------------------- 6225 // 6226 // 6227 6228 /// \name Expressions 6229 /// Implementations are in SemaExpr.cpp 6230 ///@{ 6231 6232 public: 6233 /// Describes how the expressions currently being parsed are 6234 /// evaluated at run-time, if at all. 6235 enum class ExpressionEvaluationContext { 6236 /// The current expression and its subexpressions occur within an 6237 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 6238 /// \c sizeof, where the type of the expression may be significant but 6239 /// no code will be generated to evaluate the value of the expression at 6240 /// run time. 6241 Unevaluated, 6242 6243 /// The current expression occurs within a braced-init-list within 6244 /// an unevaluated operand. This is mostly like a regular unevaluated 6245 /// context, except that we still instantiate constexpr functions that are 6246 /// referenced here so that we can perform narrowing checks correctly. 6247 UnevaluatedList, 6248 6249 /// The current expression occurs within a discarded statement. 6250 /// This behaves largely similarly to an unevaluated operand in preventing 6251 /// definitions from being required, but not in other ways. 6252 DiscardedStatement, 6253 6254 /// The current expression occurs within an unevaluated 6255 /// operand that unconditionally permits abstract references to 6256 /// fields, such as a SIZE operator in MS-style inline assembly. 6257 UnevaluatedAbstract, 6258 6259 /// The current context is "potentially evaluated" in C++11 terms, 6260 /// but the expression is evaluated at compile-time (like the values of 6261 /// cases in a switch statement). 6262 ConstantEvaluated, 6263 6264 /// In addition of being constant evaluated, the current expression 6265 /// occurs in an immediate function context - either a consteval function 6266 /// or a consteval if statement. 6267 ImmediateFunctionContext, 6268 6269 /// The current expression is potentially evaluated at run time, 6270 /// which means that code may be generated to evaluate the value of the 6271 /// expression at run time. 6272 PotentiallyEvaluated, 6273 6274 /// The current expression is potentially evaluated, but any 6275 /// declarations referenced inside that expression are only used if 6276 /// in fact the current expression is used. 6277 /// 6278 /// This value is used when parsing default function arguments, for which 6279 /// we would like to provide diagnostics (e.g., passing non-POD arguments 6280 /// through varargs) but do not want to mark declarations as "referenced" 6281 /// until the default argument is used. 6282 PotentiallyEvaluatedIfUsed 6283 }; 6284 6285 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference 6286 /// to a variable (constant) that may or may not be odr-used in this Expr, and 6287 /// we won't know until all lvalue-to-rvalue and discarded value conversions 6288 /// have been applied to all subexpressions of the enclosing full expression. 6289 /// This is cleared at the end of each full expression. 6290 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>; 6291 MaybeODRUseExprSet MaybeODRUseExprs; 6292 6293 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; 6294 6295 /// Data structure used to record current or nested 6296 /// expression evaluation contexts. 6297 struct ExpressionEvaluationContextRecord { 6298 /// The expression evaluation context. 6299 ExpressionEvaluationContext Context; 6300 6301 /// Whether the enclosing context needed a cleanup. 6302 CleanupInfo ParentCleanup; 6303 6304 /// The number of active cleanup objects when we entered 6305 /// this expression evaluation context. 6306 unsigned NumCleanupObjects; 6307 6308 /// The number of typos encountered during this expression evaluation 6309 /// context (i.e. the number of TypoExprs created). 6310 unsigned NumTypos; 6311 6312 MaybeODRUseExprSet SavedMaybeODRUseExprs; 6313 6314 /// The lambdas that are present within this context, if it 6315 /// is indeed an unevaluated context. 6316 SmallVector<LambdaExpr *, 2> Lambdas; 6317 6318 /// The declaration that provides context for lambda expressions 6319 /// and block literals if the normal declaration context does not 6320 /// suffice, e.g., in a default function argument. 6321 Decl *ManglingContextDecl; 6322 6323 /// If we are processing a decltype type, a set of call expressions 6324 /// for which we have deferred checking the completeness of the return type. 6325 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 6326 6327 /// If we are processing a decltype type, a set of temporary binding 6328 /// expressions for which we have deferred checking the destructor. 6329 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 6330 6331 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; 6332 6333 /// Expressions appearing as the LHS of a volatile assignment in this 6334 /// context. We produce a warning for these when popping the context if 6335 /// they are not discarded-value expressions nor unevaluated operands. 6336 SmallVector<Expr *, 2> VolatileAssignmentLHSs; 6337 6338 /// Set of candidates for starting an immediate invocation. 6339 llvm::SmallVector<ImmediateInvocationCandidate, 4> 6340 ImmediateInvocationCandidates; 6341 6342 /// Set of DeclRefExprs referencing a consteval function when used in a 6343 /// context not already known to be immediately invoked. 6344 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; 6345 6346 /// P2718R0 - Lifetime extension in range-based for loops. 6347 /// MaterializeTemporaryExprs in for-range-init expressions which need to 6348 /// extend lifetime. Add MaterializeTemporaryExpr* if the value of 6349 /// InLifetimeExtendingContext is true. 6350 SmallVector<MaterializeTemporaryExpr *, 8> ForRangeLifetimeExtendTemps; 6351 6352 /// \brief Describes whether we are in an expression constext which we have 6353 /// to handle differently. 6354 enum ExpressionKind { 6355 EK_Decltype, 6356 EK_TemplateArgument, 6357 EK_AttrArgument, 6358 EK_Other 6359 } ExprContext; 6360 6361 // A context can be nested in both a discarded statement context and 6362 // an immediate function context, so they need to be tracked independently. 6363 bool InDiscardedStatement; 6364 bool InImmediateFunctionContext; 6365 bool InImmediateEscalatingFunctionContext; 6366 6367 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false; 6368 6369 // We are in a constant context, but we also allow 6370 // non constant expressions, for example for array bounds (which may be 6371 // VLAs). 6372 bool InConditionallyConstantEvaluateContext = false; 6373 6374 /// Whether we are currently in a context in which all temporaries must be 6375 /// lifetime-extended, even if they're not bound to a reference (for 6376 /// example, in a for-range initializer). 6377 bool InLifetimeExtendingContext = false; 6378 6379 /// Whether we should rebuild CXXDefaultArgExpr and CXXDefaultInitExpr. 6380 bool RebuildDefaultArgOrDefaultInit = false; 6381 6382 // When evaluating immediate functions in the initializer of a default 6383 // argument or default member initializer, this is the declaration whose 6384 // default initializer is being evaluated and the location of the call 6385 // or constructor definition. 6386 struct InitializationContext { 6387 InitializationContext(SourceLocation Loc, ValueDecl *Decl, 6388 DeclContext *Context) 6389 : Loc(Loc), Decl(Decl), Context(Context) { 6390 assert(Decl && Context && "invalid initialization context"); 6391 } 6392 6393 SourceLocation Loc; 6394 ValueDecl *Decl = nullptr; 6395 DeclContext *Context = nullptr; 6396 }; 6397 std::optional<InitializationContext> DelayedDefaultInitializationContext; 6398 6399 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 6400 unsigned NumCleanupObjects, 6401 CleanupInfo ParentCleanup, 6402 Decl *ManglingContextDecl, 6403 ExpressionKind ExprContext) 6404 : Context(Context), ParentCleanup(ParentCleanup), 6405 NumCleanupObjects(NumCleanupObjects), NumTypos(0), 6406 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext), 6407 InDiscardedStatement(false), InImmediateFunctionContext(false), 6408 InImmediateEscalatingFunctionContext(false) {} 6409 6410 bool isUnevaluated() const { 6411 return Context == ExpressionEvaluationContext::Unevaluated || 6412 Context == ExpressionEvaluationContext::UnevaluatedAbstract || 6413 Context == ExpressionEvaluationContext::UnevaluatedList; 6414 } 6415 6416 bool isPotentiallyEvaluated() const { 6417 return Context == ExpressionEvaluationContext::PotentiallyEvaluated || 6418 Context == 6419 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed || 6420 Context == ExpressionEvaluationContext::ConstantEvaluated; 6421 } 6422 6423 bool isConstantEvaluated() const { 6424 return Context == ExpressionEvaluationContext::ConstantEvaluated || 6425 Context == ExpressionEvaluationContext::ImmediateFunctionContext; 6426 } 6427 6428 bool isImmediateFunctionContext() const { 6429 return Context == ExpressionEvaluationContext::ImmediateFunctionContext || 6430 (Context == ExpressionEvaluationContext::DiscardedStatement && 6431 InImmediateFunctionContext) || 6432 // C++23 [expr.const]p14: 6433 // An expression or conversion is in an immediate function 6434 // context if it is potentially evaluated and either: 6435 // * its innermost enclosing non-block scope is a function 6436 // parameter scope of an immediate function, or 6437 // * its enclosing statement is enclosed by the compound- 6438 // statement of a consteval if statement. 6439 (Context == ExpressionEvaluationContext::PotentiallyEvaluated && 6440 InImmediateFunctionContext); 6441 } 6442 6443 bool isDiscardedStatementContext() const { 6444 return Context == ExpressionEvaluationContext::DiscardedStatement || 6445 (Context == 6446 ExpressionEvaluationContext::ImmediateFunctionContext && 6447 InDiscardedStatement); 6448 } 6449 }; 6450 6451 const ExpressionEvaluationContextRecord ¤tEvaluationContext() const { 6452 assert(!ExprEvalContexts.empty() && 6453 "Must be in an expression evaluation context"); 6454 return ExprEvalContexts.back(); 6455 }; 6456 6457 ExpressionEvaluationContextRecord ¤tEvaluationContext() { 6458 assert(!ExprEvalContexts.empty() && 6459 "Must be in an expression evaluation context"); 6460 return ExprEvalContexts.back(); 6461 }; 6462 6463 ExpressionEvaluationContextRecord &parentEvaluationContext() { 6464 assert(ExprEvalContexts.size() >= 2 && 6465 "Must be in an expression evaluation context"); 6466 return ExprEvalContexts[ExprEvalContexts.size() - 2]; 6467 }; 6468 6469 const ExpressionEvaluationContextRecord &parentEvaluationContext() const { 6470 return const_cast<Sema *>(this)->parentEvaluationContext(); 6471 }; 6472 6473 bool isAttrContext() const { 6474 return ExprEvalContexts.back().ExprContext == 6475 ExpressionEvaluationContextRecord::ExpressionKind::EK_AttrArgument; 6476 } 6477 6478 /// Increment when we find a reference; decrement when we find an ignored 6479 /// assignment. Ultimately the value is 0 if every reference is an ignored 6480 /// assignment. 6481 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; 6482 6483 /// Used to control the generation of ExprWithCleanups. 6484 CleanupInfo Cleanup; 6485 6486 /// ExprCleanupObjects - This is the stack of objects requiring 6487 /// cleanup that are created by the current full expression. 6488 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; 6489 6490 /// Determine whether the use of this declaration is valid, without 6491 /// emitting diagnostics. 6492 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); 6493 // A version of DiagnoseUseOfDecl that should be used if overload resolution 6494 // has been used to find this declaration, which means we don't have to bother 6495 // checking the trailing requires clause. 6496 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) { 6497 return DiagnoseUseOfDecl( 6498 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false, 6499 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr, 6500 /*SkipTrailingRequiresClause=*/true); 6501 } 6502 6503 /// Determine whether the use of this declaration is valid, and 6504 /// emit any corresponding diagnostics. 6505 /// 6506 /// This routine diagnoses various problems with referencing 6507 /// declarations that can occur when using a declaration. For example, 6508 /// it might warn if a deprecated or unavailable declaration is being 6509 /// used, or produce an error (and return true) if a C++0x deleted 6510 /// function is being used. 6511 /// 6512 /// \returns true if there was an error (this declaration cannot be 6513 /// referenced), false otherwise. 6514 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 6515 const ObjCInterfaceDecl *UnknownObjCClass = nullptr, 6516 bool ObjCPropertyAccess = false, 6517 bool AvoidPartialAvailabilityChecks = false, 6518 ObjCInterfaceDecl *ClassReciever = nullptr, 6519 bool SkipTrailingRequiresClause = false); 6520 6521 /// Emit a note explaining that this function is deleted. 6522 void NoteDeletedFunction(FunctionDecl *FD); 6523 6524 /// DiagnoseSentinelCalls - This routine checks whether a call or 6525 /// message-send is to a declaration with the sentinel attribute, and 6526 /// if so, it checks that the requirements of the sentinel are 6527 /// satisfied. 6528 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, 6529 ArrayRef<Expr *> Args); 6530 6531 void PushExpressionEvaluationContext( 6532 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, 6533 ExpressionEvaluationContextRecord::ExpressionKind Type = 6534 ExpressionEvaluationContextRecord::EK_Other); 6535 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 6536 void PushExpressionEvaluationContext( 6537 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 6538 ExpressionEvaluationContextRecord::ExpressionKind Type = 6539 ExpressionEvaluationContextRecord::EK_Other); 6540 void PopExpressionEvaluationContext(); 6541 6542 void DiscardCleanupsInEvaluationContext(); 6543 6544 ExprResult TransformToPotentiallyEvaluated(Expr *E); 6545 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo); 6546 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 6547 6548 /// Check whether E, which is either a discarded-value expression or an 6549 /// unevaluated operand, is a simple-assignment to a volatlie-qualified 6550 /// lvalue, and if so, remove it from the list of volatile-qualified 6551 /// assignments that we are going to warn are deprecated. 6552 void CheckUnusedVolatileAssignment(Expr *E); 6553 6554 ExprResult ActOnConstantExpression(ExprResult Res); 6555 6556 // Functions for marking a declaration referenced. These functions also 6557 // contain the relevant logic for marking if a reference to a function or 6558 // variable is an odr-use (in the C++11 sense). There are separate variants 6559 // for expressions referring to a decl; these exist because odr-use marking 6560 // needs to be delayed for some constant variables when we build one of the 6561 // named expressions. 6562 // 6563 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and 6564 // should usually be true. This only needs to be set to false if the lack of 6565 // odr-use cannot be determined from the current context (for instance, 6566 // because the name denotes a virtual function and was written without an 6567 // explicit nested-name-specifier). 6568 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); 6569 6570 /// Mark a function referenced, and check whether it is odr-used 6571 /// (C++ [basic.def.odr]p2, C99 6.9p3) 6572 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 6573 bool MightBeOdrUse = true); 6574 6575 /// Mark a variable referenced, and check whether it is odr-used 6576 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 6577 /// used directly for normal expressions referring to VarDecl. 6578 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 6579 6580 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 6581 /// 6582 /// Note, this may change the dependence of the DeclRefExpr, and so needs to 6583 /// be handled with care if the DeclRefExpr is not newly-created. 6584 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); 6585 6586 /// Perform reference-marking and odr-use handling for a MemberExpr. 6587 void MarkMemberReferenced(MemberExpr *E); 6588 6589 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 6590 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); 6591 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, 6592 unsigned CapturingScopeIndex); 6593 6594 ExprResult CheckLValueToRValueConversionOperand(Expr *E); 6595 void CleanupVarDeclMarking(); 6596 6597 enum TryCaptureKind { 6598 TryCapture_Implicit, 6599 TryCapture_ExplicitByVal, 6600 TryCapture_ExplicitByRef 6601 }; 6602 6603 /// Try to capture the given variable. 6604 /// 6605 /// \param Var The variable to capture. 6606 /// 6607 /// \param Loc The location at which the capture occurs. 6608 /// 6609 /// \param Kind The kind of capture, which may be implicit (for either a 6610 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 6611 /// 6612 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 6613 /// an explicit lambda capture. 6614 /// 6615 /// \param BuildAndDiagnose Whether we are actually supposed to add the 6616 /// captures or diagnose errors. If false, this routine merely check whether 6617 /// the capture can occur without performing the capture itself or complaining 6618 /// if the variable cannot be captured. 6619 /// 6620 /// \param CaptureType Will be set to the type of the field used to capture 6621 /// this variable in the innermost block or lambda. Only valid when the 6622 /// variable can be captured. 6623 /// 6624 /// \param DeclRefType Will be set to the type of a reference to the capture 6625 /// from within the current scope. Only valid when the variable can be 6626 /// captured. 6627 /// 6628 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 6629 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 6630 /// This is useful when enclosing lambdas must speculatively capture 6631 /// variables that may or may not be used in certain specializations of 6632 /// a nested generic lambda. 6633 /// 6634 /// \returns true if an error occurred (i.e., the variable cannot be 6635 /// captured) and false if the capture succeeded. 6636 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, 6637 TryCaptureKind Kind, SourceLocation EllipsisLoc, 6638 bool BuildAndDiagnose, QualType &CaptureType, 6639 QualType &DeclRefType, 6640 const unsigned *const FunctionScopeIndexToStopAt); 6641 6642 /// Try to capture the given variable. 6643 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, 6644 TryCaptureKind Kind = TryCapture_Implicit, 6645 SourceLocation EllipsisLoc = SourceLocation()); 6646 6647 /// Checks if the variable must be captured. 6648 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc); 6649 6650 /// Given a variable, determine the type that a reference to that 6651 /// variable will have in the given scope. 6652 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc); 6653 6654 /// Mark all of the declarations referenced within a particular AST node as 6655 /// referenced. Used when template instantiation instantiates a non-dependent 6656 /// type -- entities referenced by the type are now referenced. 6657 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 6658 6659 /// Mark any declarations that appear within this expression or any 6660 /// potentially-evaluated subexpressions as "referenced". 6661 /// 6662 /// \param SkipLocalVariables If true, don't mark local variables as 6663 /// 'referenced'. 6664 /// \param StopAt Subexpressions that we shouldn't recurse into. 6665 void MarkDeclarationsReferencedInExpr(Expr *E, 6666 bool SkipLocalVariables = false, 6667 ArrayRef<const Expr *> StopAt = {}); 6668 6669 /// Try to convert an expression \p E to type \p Ty. Returns the result of the 6670 /// conversion. 6671 ExprResult tryConvertExprToType(Expr *E, QualType Ty); 6672 6673 /// Conditionally issue a diagnostic based on the statements's reachability 6674 /// analysis. 6675 /// 6676 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until 6677 /// the function body is parsed, and then do a basic reachability analysis to 6678 /// determine if the statement is reachable. If it is unreachable, the 6679 /// diagnostic will not be emitted. 6680 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 6681 const PartialDiagnostic &PD); 6682 6683 /// Conditionally issue a diagnostic based on the current 6684 /// evaluation context. 6685 /// 6686 /// \param Statement If Statement is non-null, delay reporting the 6687 /// diagnostic until the function body is parsed, and then do a basic 6688 /// reachability analysis to determine if the statement is reachable. 6689 /// If it is unreachable, the diagnostic will not be emitted. 6690 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 6691 const PartialDiagnostic &PD); 6692 /// Similar, but diagnostic is only produced if all the specified statements 6693 /// are reachable. 6694 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 6695 const PartialDiagnostic &PD); 6696 6697 // Primary Expressions. 6698 SourceRange getExprRange(Expr *E) const; 6699 6700 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 6701 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 6702 bool HasTrailingLParen, bool IsAddressOfOperand, 6703 CorrectionCandidateCallback *CCC = nullptr, 6704 bool IsInlineAsmIdentifier = false, 6705 Token *KeywordReplacement = nullptr); 6706 6707 /// Decomposes the given name into a DeclarationNameInfo, its location, and 6708 /// possibly a list of template arguments. 6709 /// 6710 /// If this produces template arguments, it is permitted to call 6711 /// DecomposeTemplateName. 6712 /// 6713 /// This actually loses a lot of source location information for 6714 /// non-standard name kinds; we should consider preserving that in 6715 /// some way. 6716 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 6717 TemplateArgumentListInfo &Buffer, 6718 DeclarationNameInfo &NameInfo, 6719 const TemplateArgumentListInfo *&TemplateArgs); 6720 6721 /// Diagnose a lookup that found results in an enclosing class during error 6722 /// recovery. This usually indicates that the results were found in a 6723 /// dependent base class that could not be searched as part of a template 6724 /// definition. Always issues a diagnostic (though this may be only a warning 6725 /// in MS compatibility mode). 6726 /// 6727 /// Return \c true if the error is unrecoverable, or \c false if the caller 6728 /// should attempt to recover using these lookup results. 6729 bool DiagnoseDependentMemberLookup(const LookupResult &R); 6730 6731 /// Diagnose an empty lookup. 6732 /// 6733 /// \return false if new lookup candidates were found 6734 bool 6735 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 6736 CorrectionCandidateCallback &CCC, 6737 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 6738 ArrayRef<Expr *> Args = {}, 6739 DeclContext *LookupCtx = nullptr, 6740 TypoExpr **Out = nullptr); 6741 6742 /// If \p D cannot be odr-used in the current expression evaluation context, 6743 /// return a reason explaining why. Otherwise, return NOUR_None. 6744 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); 6745 6746 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 6747 SourceLocation Loc, 6748 const CXXScopeSpec *SS = nullptr); 6749 DeclRefExpr * 6750 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 6751 const DeclarationNameInfo &NameInfo, 6752 const CXXScopeSpec *SS = nullptr, 6753 NamedDecl *FoundD = nullptr, 6754 SourceLocation TemplateKWLoc = SourceLocation(), 6755 const TemplateArgumentListInfo *TemplateArgs = nullptr); 6756 6757 /// BuildDeclRefExpr - Build an expression that references a 6758 /// declaration that does not require a closure capture. 6759 DeclRefExpr * 6760 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 6761 const DeclarationNameInfo &NameInfo, 6762 NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, 6763 SourceLocation TemplateKWLoc = SourceLocation(), 6764 const TemplateArgumentListInfo *TemplateArgs = nullptr); 6765 6766 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, 6767 bool HasTrailingLParen); 6768 6769 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 6770 /// declaration name, generally during template instantiation. 6771 /// There's a large number of things which don't need to be done along 6772 /// this path. 6773 ExprResult BuildQualifiedDeclarationNameExpr( 6774 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 6775 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr); 6776 6777 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, 6778 bool NeedsADL, 6779 bool AcceptInvalidDecl = false); 6780 6781 /// Complete semantic analysis for a reference to the given declaration. 6782 ExprResult BuildDeclarationNameExpr( 6783 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 6784 NamedDecl *FoundD = nullptr, 6785 const TemplateArgumentListInfo *TemplateArgs = nullptr, 6786 bool AcceptInvalidDecl = false); 6787 6788 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens, 6789 // where Tokens representing function local predefined macros (such as 6790 // __FUNCTION__) are replaced (expanded) with string-literal Tokens. 6791 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks); 6792 6793 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK); 6794 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 6795 ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val); 6796 6797 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero); 6798 6799 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 6800 ExprResult ActOnCharacterConstant(const Token &Tok, 6801 Scope *UDLScope = nullptr); 6802 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 6803 ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, 6804 MultiExprArg Val); 6805 6806 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 6807 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle 6808 /// string concatenation ([C99 5.1.1.2, translation phase #6]), so it may come 6809 /// from multiple tokens. However, the common case is that StringToks points 6810 /// to one string. 6811 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 6812 Scope *UDLScope = nullptr); 6813 6814 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks); 6815 6816 /// ControllingExprOrType is either an opaque pointer coming out of a 6817 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface 6818 /// into two so we don't take a void *, but that's awkward because one of 6819 /// the operands is either a ParsedType or an Expr *, which doesn't lend 6820 /// itself to generic code very well. 6821 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 6822 SourceLocation DefaultLoc, 6823 SourceLocation RParenLoc, 6824 bool PredicateIsExpr, 6825 void *ControllingExprOrType, 6826 ArrayRef<ParsedType> ArgTypes, 6827 ArrayRef<Expr *> ArgExprs); 6828 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME: 6829 /// it'd be better to split this interface into two so we don't take a 6830 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that 6831 /// isn't a trivial change. 6832 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 6833 SourceLocation DefaultLoc, 6834 SourceLocation RParenLoc, 6835 bool PredicateIsExpr, 6836 void *ControllingExprOrType, 6837 ArrayRef<TypeSourceInfo *> Types, 6838 ArrayRef<Expr *> Exprs); 6839 6840 // Binary/Unary Operators. 'Tok' is the token for the operator. 6841 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 6842 Expr *InputExpr, bool IsAfterAmp = false); 6843 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, 6844 Expr *Input, bool IsAfterAmp = false); 6845 6846 /// Unary Operators. 'Tok' is the token for the operator. 6847 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, 6848 Expr *Input, bool IsAfterAmp = false); 6849 6850 /// Determine whether the given expression is a qualified member 6851 /// access expression, of a form that could be turned into a pointer to member 6852 /// with the address-of operator. 6853 bool isQualifiedMemberAccess(Expr *E); 6854 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, 6855 const Expr *Op, 6856 const CXXMethodDecl *MD); 6857 6858 /// CheckAddressOfOperand - The operand of & must be either a function 6859 /// designator or an lvalue designating an object. If it is an lvalue, the 6860 /// object cannot be declared with storage class register or be a bit field. 6861 /// Note: The usual conversions are *not* applied to the operand of the & 6862 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 6863 /// In C++, the operand might be an overloaded function name, in which case 6864 /// we allow the '&' but retain the overloaded-function type. 6865 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 6866 6867 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c 6868 /// _Alignas(type-name) . 6869 /// [dcl.align] An alignment-specifier of the form 6870 /// alignas(type-id) has the same effect as alignas(alignof(type-id)). 6871 /// 6872 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to 6873 /// _Alignas(_Alignof(type-name)). 6874 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, 6875 SourceLocation OpLoc, SourceRange R); 6876 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, 6877 SourceLocation OpLoc, SourceRange R); 6878 6879 /// Build a sizeof or alignof expression given a type operand. 6880 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 6881 SourceLocation OpLoc, 6882 UnaryExprOrTypeTrait ExprKind, 6883 SourceRange R); 6884 6885 /// Build a sizeof or alignof expression given an expression 6886 /// operand. 6887 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 6888 UnaryExprOrTypeTrait ExprKind); 6889 6890 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 6891 /// expr and the same for @c alignof and @c __alignof 6892 /// Note that the ArgRange is invalid if isType is false. 6893 ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 6894 UnaryExprOrTypeTrait ExprKind, 6895 bool IsType, void *TyOrEx, 6896 SourceRange ArgRange); 6897 6898 /// Check for operands with placeholder types and complain if found. 6899 /// Returns ExprError() if there was an error and no recovery was possible. 6900 ExprResult CheckPlaceholderExpr(Expr *E); 6901 bool CheckVecStepExpr(Expr *E); 6902 6903 /// Check the constraints on expression operands to unary type expression 6904 /// and type traits. 6905 /// 6906 /// Completes any types necessary and validates the constraints on the operand 6907 /// expression. The logic mostly mirrors the type-based overload, but may 6908 /// modify the expression as it completes the type for that expression through 6909 /// template instantiation, etc. 6910 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 6911 6912 /// Check the constraints on operands to unary expression and type 6913 /// traits. 6914 /// 6915 /// This will complete any types necessary, and validate the various 6916 /// constraints on those operands. 6917 /// 6918 /// The UsualUnaryConversions() function is *not* called by this routine. 6919 /// C99 6.3.2.1p[2-4] all state: 6920 /// Except when it is the operand of the sizeof operator ... 6921 /// 6922 /// C++ [expr.sizeof]p4 6923 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 6924 /// standard conversions are not applied to the operand of sizeof. 6925 /// 6926 /// This policy is followed for all of the unary trait expressions. 6927 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 6928 SourceRange ExprRange, 6929 UnaryExprOrTypeTrait ExprKind, 6930 StringRef KWName); 6931 6932 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 6933 tok::TokenKind Kind, Expr *Input); 6934 6935 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 6936 MultiExprArg ArgExprs, 6937 SourceLocation RLoc); 6938 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 6939 Expr *Idx, SourceLocation RLoc); 6940 6941 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 6942 Expr *ColumnIdx, 6943 SourceLocation RBLoc); 6944 6945 /// ConvertArgumentsForCall - Converts the arguments specified in 6946 /// Args/NumArgs to the parameter types of the function FDecl with 6947 /// function prototype Proto. Call is the call expression itself, and 6948 /// Fn is the function expression. For a C++ member function, this 6949 /// routine does not attempt to convert the object argument. Returns 6950 /// true if the call is ill-formed. 6951 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, 6952 const FunctionProtoType *Proto, 6953 ArrayRef<Expr *> Args, SourceLocation RParenLoc, 6954 bool ExecConfig = false); 6955 6956 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6957 /// array parameter, check that it is non-null, and that if it is formed by 6958 /// array-to-pointer decay, the underlying array is sufficiently large. 6959 /// 6960 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of 6961 /// the array type derivation, then for each call to the function, the value 6962 /// of the corresponding actual argument shall provide access to the first 6963 /// element of an array with at least as many elements as specified by the 6964 /// size expression. 6965 void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, 6966 const Expr *ArgExpr); 6967 6968 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 6969 /// This provides the location of the left/right parens and a list of comma 6970 /// locations. 6971 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 6972 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6973 Expr *ExecConfig = nullptr); 6974 6975 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6976 /// This provides the location of the left/right parens and a list of comma 6977 /// locations. 6978 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 6979 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6980 Expr *ExecConfig = nullptr, 6981 bool IsExecConfig = false, 6982 bool AllowRecovery = false); 6983 6984 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 6985 // with the specified CallArgs 6986 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6987 MultiExprArg CallArgs); 6988 6989 using ADLCallKind = CallExpr::ADLCallKind; 6990 6991 /// BuildResolvedCallExpr - Build a call to a resolved expression, 6992 /// i.e. an expression not of \p OverloadTy. The expression should 6993 /// unary-convert to an expression of function-pointer or 6994 /// block-pointer type. 6995 /// 6996 /// \param NDecl the declaration being called, if available 6997 ExprResult 6998 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, 6999 ArrayRef<Expr *> Arg, SourceLocation RParenLoc, 7000 Expr *Config = nullptr, bool IsExecConfig = false, 7001 ADLCallKind UsesADL = ADLCallKind::NotADL); 7002 7003 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, 7004 ParsedType &Ty, SourceLocation RParenLoc, 7005 Expr *CastExpr); 7006 7007 /// Prepares for a scalar cast, performing all the necessary stages 7008 /// except the final cast and returning the kind required. 7009 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 7010 7011 /// Build an altivec or OpenCL literal. 7012 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 7013 SourceLocation RParenLoc, Expr *E, 7014 TypeSourceInfo *TInfo); 7015 7016 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 7017 /// the ParenListExpr into a sequence of comma binary operators. 7018 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 7019 7020 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7021 SourceLocation RParenLoc, Expr *InitExpr); 7022 7023 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 7024 TypeSourceInfo *TInfo, 7025 SourceLocation RParenLoc, 7026 Expr *LiteralExpr); 7027 7028 ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7029 SourceLocation RBraceLoc); 7030 7031 ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7032 SourceLocation RBraceLoc); 7033 7034 /// Binary Operators. 'Tok' is the token for the operator. 7035 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, 7036 Expr *LHSExpr, Expr *RHSExpr); 7037 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 7038 Expr *LHSExpr, Expr *RHSExpr); 7039 7040 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 7041 /// operator @p Opc at location @c TokLoc. This routine only supports 7042 /// built-in operations; ActOnBinOp handles overloaded operators. 7043 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 7044 Expr *LHSExpr, Expr *RHSExpr); 7045 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 7046 UnresolvedSetImpl &Functions); 7047 7048 /// Look for instances where it is likely the comma operator is confused with 7049 /// another operator. There is an explicit list of acceptable expressions for 7050 /// the left hand side of the comma operator, otherwise emit a warning. 7051 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); 7052 7053 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7054 /// in the case of a the GNU conditional expr extension. 7055 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 7056 SourceLocation ColonLoc, Expr *CondExpr, 7057 Expr *LHSExpr, Expr *RHSExpr); 7058 7059 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 7060 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 7061 LabelDecl *TheDecl); 7062 7063 void ActOnStartStmtExpr(); 7064 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 7065 SourceLocation RPLoc); 7066 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 7067 SourceLocation RPLoc, unsigned TemplateDepth); 7068 // Handle the final expression in a statement expression. 7069 ExprResult ActOnStmtExprResult(ExprResult E); 7070 void ActOnStmtExprError(); 7071 7072 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 7073 struct OffsetOfComponent { 7074 SourceLocation LocStart, LocEnd; 7075 bool isBrackets; // true if [expr], false if .ident 7076 union { 7077 IdentifierInfo *IdentInfo; 7078 Expr *E; 7079 } U; 7080 }; 7081 7082 /// __builtin_offsetof(type, a.b[123][456].c) 7083 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 7084 TypeSourceInfo *TInfo, 7085 ArrayRef<OffsetOfComponent> Components, 7086 SourceLocation RParenLoc); 7087 ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, 7088 SourceLocation TypeLoc, 7089 ParsedType ParsedArgTy, 7090 ArrayRef<OffsetOfComponent> Components, 7091 SourceLocation RParenLoc); 7092 7093 // __builtin_choose_expr(constExpr, expr1, expr2) 7094 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, 7095 Expr *LHSExpr, Expr *RHSExpr, 7096 SourceLocation RPLoc); 7097 7098 // __builtin_va_arg(expr, type) 7099 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 7100 SourceLocation RPLoc); 7101 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 7102 TypeSourceInfo *TInfo, SourceLocation RPLoc); 7103 7104 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(), 7105 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location() 7106 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, 7107 SourceLocation BuiltinLoc, 7108 SourceLocation RPLoc); 7109 7110 // #embed 7111 ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, 7112 StringLiteral *BinaryData); 7113 7114 // Build a potentially resolved SourceLocExpr. 7115 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, 7116 SourceLocation BuiltinLoc, SourceLocation RPLoc, 7117 DeclContext *ParentContext); 7118 7119 // __null 7120 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 7121 7122 bool CheckCaseExpression(Expr *E); 7123 7124 //===------------------------- "Block" Extension ------------------------===// 7125 7126 /// ActOnBlockStart - This callback is invoked when a block literal is 7127 /// started. 7128 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 7129 7130 /// ActOnBlockArguments - This callback allows processing of block arguments. 7131 /// If there are no arguments, this is still invoked. 7132 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 7133 Scope *CurScope); 7134 7135 /// ActOnBlockError - If there is an error parsing a block, this callback 7136 /// is invoked to pop the information about the block from the action impl. 7137 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 7138 7139 /// ActOnBlockStmtExpr - This is called when the body of a block statement 7140 /// literal was successfully completed. ^(int x){...} 7141 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 7142 Scope *CurScope); 7143 7144 //===---------------------------- Clang Extensions ----------------------===// 7145 7146 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 7147 /// provided arguments. 7148 /// 7149 /// __builtin_convertvector( value, dst type ) 7150 /// 7151 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 7152 SourceLocation BuiltinLoc, 7153 SourceLocation RParenLoc); 7154 7155 //===---------------------------- OpenCL Features -----------------------===// 7156 7157 /// Parse a __builtin_astype expression. 7158 /// 7159 /// __builtin_astype( value, dst type ) 7160 /// 7161 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 7162 SourceLocation BuiltinLoc, 7163 SourceLocation RParenLoc); 7164 7165 /// Create a new AsTypeExpr node (bitcast) from the arguments. 7166 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, 7167 SourceLocation BuiltinLoc, 7168 SourceLocation RParenLoc); 7169 7170 /// Attempts to produce a RecoveryExpr after some AST node cannot be created. 7171 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 7172 ArrayRef<Expr *> SubExprs, 7173 QualType T = QualType()); 7174 7175 /// Cast a base object to a member's actual type. 7176 /// 7177 /// There are two relevant checks: 7178 /// 7179 /// C++ [class.access.base]p7: 7180 /// 7181 /// If a class member access operator [...] is used to access a non-static 7182 /// data member or non-static member function, the reference is ill-formed 7183 /// if the left operand [...] cannot be implicitly converted to a pointer to 7184 /// the naming class of the right operand. 7185 /// 7186 /// C++ [expr.ref]p7: 7187 /// 7188 /// If E2 is a non-static data member or a non-static member function, the 7189 /// program is ill-formed if the class of which E2 is directly a member is 7190 /// an ambiguous base (11.8) of the naming class (11.9.3) of E2. 7191 /// 7192 /// Note that the latter check does not consider access; the access of the 7193 /// "real" base class is checked as appropriate when checking the access of 7194 /// the member name. 7195 ExprResult PerformObjectMemberConversion(Expr *From, 7196 NestedNameSpecifier *Qualifier, 7197 NamedDecl *FoundDecl, 7198 NamedDecl *Member); 7199 7200 /// CheckCallReturnType - Checks that a call expression's return type is 7201 /// complete. Returns true on failure. The location passed in is the location 7202 /// that best represents the call. 7203 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 7204 CallExpr *CE, FunctionDecl *FD); 7205 7206 /// Emit a warning for all pending noderef expressions that we recorded. 7207 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); 7208 7209 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 7210 7211 /// Instantiate or parse a C++ default argument expression as necessary. 7212 /// Return true on error. 7213 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 7214 ParmVarDecl *Param, Expr *Init = nullptr, 7215 bool SkipImmediateInvocations = true); 7216 7217 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 7218 /// the default expr if needed. 7219 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 7220 ParmVarDecl *Param, Expr *Init = nullptr); 7221 7222 /// Wrap the expression in a ConstantExpr if it is a potential immediate 7223 /// invocation. 7224 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); 7225 7226 void MarkExpressionAsImmediateEscalating(Expr *E); 7227 7228 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible. 7229 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType); 7230 7231 /// Abstract base class used for diagnosing integer constant 7232 /// expression violations. 7233 class VerifyICEDiagnoser { 7234 public: 7235 bool Suppress; 7236 7237 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) {} 7238 7239 virtual SemaDiagnosticBuilder 7240 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); 7241 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 7242 SourceLocation Loc) = 0; 7243 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); 7244 virtual ~VerifyICEDiagnoser() {} 7245 }; 7246 7247 enum AllowFoldKind { 7248 NoFold, 7249 AllowFold, 7250 }; 7251 7252 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 7253 /// and reports the appropriate diagnostics. Returns false on success. 7254 /// Can optionally return the value of the expression. 7255 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 7256 VerifyICEDiagnoser &Diagnoser, 7257 AllowFoldKind CanFold = NoFold); 7258 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 7259 unsigned DiagID, 7260 AllowFoldKind CanFold = NoFold); 7261 ExprResult VerifyIntegerConstantExpression(Expr *E, 7262 llvm::APSInt *Result = nullptr, 7263 AllowFoldKind CanFold = NoFold); 7264 ExprResult VerifyIntegerConstantExpression(Expr *E, 7265 AllowFoldKind CanFold = NoFold) { 7266 return VerifyIntegerConstantExpression(E, nullptr, CanFold); 7267 } 7268 7269 /// DiagnoseAssignmentAsCondition - Given that an expression is 7270 /// being used as a boolean condition, warn if it's an assignment. 7271 void DiagnoseAssignmentAsCondition(Expr *E); 7272 7273 /// Redundant parentheses over an equality comparison can indicate 7274 /// that the user intended an assignment used as condition. 7275 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 7276 7277 class FullExprArg { 7278 public: 7279 FullExprArg() : E(nullptr) {} 7280 FullExprArg(Sema &actions) : E(nullptr) {} 7281 7282 ExprResult release() { return E; } 7283 7284 Expr *get() const { return E; } 7285 7286 Expr *operator->() { return E; } 7287 7288 private: 7289 // FIXME: No need to make the entire Sema class a friend when it's just 7290 // Sema::MakeFullExpr that needs access to the constructor below. 7291 friend class Sema; 7292 7293 explicit FullExprArg(Expr *expr) : E(expr) {} 7294 7295 Expr *E; 7296 }; 7297 7298 FullExprArg MakeFullExpr(Expr *Arg) { 7299 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 7300 } 7301 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 7302 return FullExprArg( 7303 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); 7304 } 7305 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 7306 ExprResult FE = 7307 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 7308 /*DiscardedValue*/ true); 7309 return FullExprArg(FE.get()); 7310 } 7311 7312 class ConditionResult { 7313 Decl *ConditionVar; 7314 FullExprArg Condition; 7315 bool Invalid; 7316 std::optional<bool> KnownValue; 7317 7318 friend class Sema; 7319 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, 7320 bool IsConstexpr) 7321 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) { 7322 if (IsConstexpr && Condition.get()) { 7323 if (std::optional<llvm::APSInt> Val = 7324 Condition.get()->getIntegerConstantExpr(S.Context)) { 7325 KnownValue = !!(*Val); 7326 } 7327 } 7328 } 7329 explicit ConditionResult(bool Invalid) 7330 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), 7331 KnownValue(std::nullopt) {} 7332 7333 public: 7334 ConditionResult() : ConditionResult(false) {} 7335 bool isInvalid() const { return Invalid; } 7336 std::pair<VarDecl *, Expr *> get() const { 7337 return std::make_pair(cast_or_null<VarDecl>(ConditionVar), 7338 Condition.get()); 7339 } 7340 std::optional<bool> getKnownValue() const { return KnownValue; } 7341 }; 7342 static ConditionResult ConditionError() { return ConditionResult(true); } 7343 7344 /// CheckBooleanCondition - Diagnose problems involving the use of 7345 /// the given expression as a boolean condition (e.g. in an if 7346 /// statement). Also performs the standard function and array 7347 /// decays, possibly changing the input variable. 7348 /// 7349 /// \param Loc - A location associated with the condition, e.g. the 7350 /// 'if' keyword. 7351 /// \return true iff there were any errors 7352 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, 7353 bool IsConstexpr = false); 7354 7355 enum class ConditionKind { 7356 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. 7357 ConstexprIf, ///< A constant boolean condition from 'if constexpr'. 7358 Switch ///< An integral condition for a 'switch' statement. 7359 }; 7360 7361 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, 7362 ConditionKind CK, bool MissingOK = false); 7363 7364 QualType CheckConditionalOperands( // C99 6.5.15 7365 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 7366 ExprObjectKind &OK, SourceLocation QuestionLoc); 7367 7368 /// Emit a specialized diagnostic when one expression is a null pointer 7369 /// constant and the other is not a pointer. Returns true if a diagnostic is 7370 /// emitted. 7371 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, 7372 SourceLocation QuestionLoc); 7373 7374 /// type checking for vector binary operators. 7375 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7376 SourceLocation Loc, bool IsCompAssign, 7377 bool AllowBothBool, bool AllowBoolConversion, 7378 bool AllowBoolOperation, bool ReportInvalid); 7379 7380 /// Return a signed ext_vector_type that is of identical size and number of 7381 /// elements. For floating point vectors, return an integer type of identical 7382 /// size and number of elements. In the non ext_vector_type case, search from 7383 /// the largest type to the smallest type to avoid cases where long long == 7384 /// long, where long gets picked over long long. 7385 QualType GetSignedVectorType(QualType V); 7386 QualType GetSignedSizelessVectorType(QualType V); 7387 7388 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7389 /// operates on extended vector types. Instead of producing an IntTy result, 7390 /// like a scalar comparison, a vector comparison produces a vector of integer 7391 /// types. 7392 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7393 SourceLocation Loc, 7394 BinaryOperatorKind Opc); 7395 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7396 SourceLocation Loc, 7397 BinaryOperatorKind Opc); 7398 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7399 SourceLocation Loc, 7400 BinaryOperatorKind Opc); 7401 7402 /// Context in which we're performing a usual arithmetic conversion. 7403 enum ArithConvKind { 7404 /// An arithmetic operation. 7405 ACK_Arithmetic, 7406 /// A bitwise operation. 7407 ACK_BitwiseOp, 7408 /// A comparison. 7409 ACK_Comparison, 7410 /// A conditional (?:) operator. 7411 ACK_Conditional, 7412 /// A compound assignment expression. 7413 ACK_CompAssign, 7414 }; 7415 7416 // type checking for sizeless vector binary operators. 7417 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 7418 SourceLocation Loc, bool IsCompAssign, 7419 ArithConvKind OperationKind); 7420 7421 /// Type checking for matrix binary operators. 7422 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 7423 SourceLocation Loc, 7424 bool IsCompAssign); 7425 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 7426 SourceLocation Loc, bool IsCompAssign); 7427 7428 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from 7429 /// the first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE 7430 /// VLST) allowed? 7431 /// 7432 /// This will also return false if the two given types do not make sense from 7433 /// the perspective of SVE bitcasts. 7434 bool isValidSveBitcast(QualType srcType, QualType destType); 7435 7436 /// Are the two types matrix types and do they have the same dimensions i.e. 7437 /// do they have the same number of rows and the same number of columns? 7438 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); 7439 7440 bool areVectorTypesSameSize(QualType srcType, QualType destType); 7441 7442 /// Are the two types lax-compatible vector types? That is, given 7443 /// that one of them is a vector, do they have equal storage sizes, 7444 /// where the storage size is the number of elements times the element 7445 /// size? 7446 /// 7447 /// This will also return false if either of the types is neither a 7448 /// vector nor a real type. 7449 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); 7450 7451 /// Is this a legal conversion between two types, one of which is 7452 /// known to be a vector type? 7453 bool isLaxVectorConversion(QualType srcType, QualType destType); 7454 7455 // This returns true if at least one of the types is an altivec vector. 7456 bool anyAltivecTypes(QualType srcType, QualType destType); 7457 7458 // type checking C++ declaration initializers (C++ [dcl.init]). 7459 7460 /// Check a cast of an unknown-any type. We intentionally only 7461 /// trigger this for C-style casts. 7462 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 7463 Expr *CastExpr, CastKind &CastKind, 7464 ExprValueKind &VK, CXXCastPath &Path); 7465 7466 /// Force an expression with unknown-type to an expression of the 7467 /// given type. 7468 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 7469 7470 /// Type-check an expression that's being passed to an 7471 /// __unknown_anytype parameter. 7472 ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, 7473 QualType ¶mType); 7474 7475 // CheckMatrixCast - Check type constraints for matrix casts. 7476 // We allow casting between matrixes of the same dimensions i.e. when they 7477 // have the same number of rows and column. Returns true if the cast is 7478 // invalid. 7479 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 7480 CastKind &Kind); 7481 7482 // CheckVectorCast - check type constraints for vectors. 7483 // Since vectors are an extension, there are no C standard reference for this. 7484 // We allow casting between vectors and integer datatypes of the same size. 7485 // returns true if the cast is invalid 7486 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 7487 CastKind &Kind); 7488 7489 /// Prepare `SplattedExpr` for a vector splat operation, adding 7490 /// implicit casts if necessary. 7491 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); 7492 7493 // CheckExtVectorCast - check type constraints for extended vectors. 7494 // Since vectors are an extension, there are no C standard reference for this. 7495 // We allow casting between vectors and integer datatypes of the same size, 7496 // or vectors and the element type of that vector. 7497 // returns the cast expr 7498 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 7499 CastKind &Kind); 7500 7501 QualType PreferredConditionType(ConditionKind K) const { 7502 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy; 7503 } 7504 7505 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2), converts 7506 // functions and arrays to their respective pointers (C99 6.3.2.1), and 7507 // promotes floating-piont types according to the language semantics. 7508 ExprResult UsualUnaryConversions(Expr *E); 7509 7510 // UsualUnaryFPConversions - promotes floating-point types according to the 7511 // current language semantics. 7512 ExprResult UsualUnaryFPConversions(Expr *E); 7513 7514 /// CallExprUnaryConversions - a special case of an unary conversion 7515 /// performed on a function designator of a call expression. 7516 ExprResult CallExprUnaryConversions(Expr *E); 7517 7518 // DefaultFunctionArrayConversion - converts functions and arrays 7519 // to their respective pointers (C99 6.3.2.1). 7520 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); 7521 7522 // DefaultFunctionArrayLvalueConversion - converts functions and 7523 // arrays to their respective pointers and performs the 7524 // lvalue-to-rvalue conversion. 7525 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, 7526 bool Diagnose = true); 7527 7528 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 7529 // the operand. This function is a no-op if the operand has a function type 7530 // or an array type. 7531 ExprResult DefaultLvalueConversion(Expr *E); 7532 7533 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 7534 // do not have a prototype. Integer promotions are performed on each 7535 // argument, and arguments that have type float are promoted to double. 7536 ExprResult DefaultArgumentPromotion(Expr *E); 7537 7538 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 7539 const FunctionProtoType *Proto, 7540 Expr *Fn); 7541 7542 // Used for determining in which context a type is allowed to be passed to a 7543 // vararg function. 7544 enum VarArgKind { 7545 VAK_Valid, 7546 VAK_ValidInCXX11, 7547 VAK_Undefined, 7548 VAK_MSVCUndefined, 7549 VAK_Invalid 7550 }; 7551 7552 /// Determine the degree of POD-ness for an expression. 7553 /// Incomplete types are considered POD, since this check can be performed 7554 /// when we're in an unevaluated context. 7555 VarArgKind isValidVarArgType(const QualType &Ty); 7556 7557 /// Check to see if the given expression is a valid argument to a variadic 7558 /// function, issuing a diagnostic if not. 7559 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 7560 7561 /// GatherArgumentsForCall - Collector argument expressions for various 7562 /// form of call prototypes. 7563 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 7564 const FunctionProtoType *Proto, 7565 unsigned FirstParam, ArrayRef<Expr *> Args, 7566 SmallVectorImpl<Expr *> &AllArgs, 7567 VariadicCallType CallType = VariadicDoesNotApply, 7568 bool AllowExplicit = false, 7569 bool IsListInitialization = false); 7570 7571 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 7572 // will create a runtime trap if the resulting type is not a POD type. 7573 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 7574 FunctionDecl *FDecl); 7575 7576 // Check that the usual arithmetic conversions can be performed on this pair 7577 // of expressions that might be of enumeration type. 7578 void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, 7579 Sema::ArithConvKind ACK); 7580 7581 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 7582 // operands and then handles various conversions that are common to binary 7583 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 7584 // routine returns the first non-arithmetic type found. The client is 7585 // responsible for emitting appropriate error diagnostics. 7586 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 7587 SourceLocation Loc, ArithConvKind ACK); 7588 7589 /// AssignConvertType - All of the 'assignment' semantic checks return this 7590 /// enum to indicate whether the assignment was allowed. These checks are 7591 /// done for simple assignments, as well as initialization, return from 7592 /// function, argument passing, etc. The query is phrased in terms of a 7593 /// source and destination type. 7594 enum AssignConvertType { 7595 /// Compatible - the types are compatible according to the standard. 7596 Compatible, 7597 7598 /// PointerToInt - The assignment converts a pointer to an int, which we 7599 /// accept as an extension. 7600 PointerToInt, 7601 7602 /// IntToPointer - The assignment converts an int to a pointer, which we 7603 /// accept as an extension. 7604 IntToPointer, 7605 7606 /// FunctionVoidPointer - The assignment is between a function pointer and 7607 /// void*, which the standard doesn't allow, but we accept as an extension. 7608 FunctionVoidPointer, 7609 7610 /// IncompatiblePointer - The assignment is between two pointers types that 7611 /// are not compatible, but we accept them as an extension. 7612 IncompatiblePointer, 7613 7614 /// IncompatibleFunctionPointer - The assignment is between two function 7615 /// pointers types that are not compatible, but we accept them as an 7616 /// extension. 7617 IncompatibleFunctionPointer, 7618 7619 /// IncompatibleFunctionPointerStrict - The assignment is between two 7620 /// function pointer types that are not identical, but are compatible, 7621 /// unless compiled with -fsanitize=cfi, in which case the type mismatch 7622 /// may trip an indirect call runtime check. 7623 IncompatibleFunctionPointerStrict, 7624 7625 /// IncompatiblePointerSign - The assignment is between two pointers types 7626 /// which point to integers which have a different sign, but are otherwise 7627 /// identical. This is a subset of the above, but broken out because it's by 7628 /// far the most common case of incompatible pointers. 7629 IncompatiblePointerSign, 7630 7631 /// CompatiblePointerDiscardsQualifiers - The assignment discards 7632 /// c/v/r qualifiers, which we accept as an extension. 7633 CompatiblePointerDiscardsQualifiers, 7634 7635 /// IncompatiblePointerDiscardsQualifiers - The assignment 7636 /// discards qualifiers that we don't permit to be discarded, 7637 /// like address spaces. 7638 IncompatiblePointerDiscardsQualifiers, 7639 7640 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment 7641 /// changes address spaces in nested pointer types which is not allowed. 7642 /// For instance, converting __private int ** to __generic int ** is 7643 /// illegal even though __private could be converted to __generic. 7644 IncompatibleNestedPointerAddressSpaceMismatch, 7645 7646 /// IncompatibleNestedPointerQualifiers - The assignment is between two 7647 /// nested pointer types, and the qualifiers other than the first two 7648 /// levels differ e.g. char ** -> const char **, but we accept them as an 7649 /// extension. 7650 IncompatibleNestedPointerQualifiers, 7651 7652 /// IncompatibleVectors - The assignment is between two vector types that 7653 /// have the same size, which we accept as an extension. 7654 IncompatibleVectors, 7655 7656 /// IntToBlockPointer - The assignment converts an int to a block 7657 /// pointer. We disallow this. 7658 IntToBlockPointer, 7659 7660 /// IncompatibleBlockPointer - The assignment is between two block 7661 /// pointers types that are not compatible. 7662 IncompatibleBlockPointer, 7663 7664 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 7665 /// id type and something else (that is incompatible with it). For example, 7666 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 7667 IncompatibleObjCQualifiedId, 7668 7669 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 7670 /// object with __weak qualifier. 7671 IncompatibleObjCWeakRef, 7672 7673 /// Incompatible - We reject this conversion outright, it is invalid to 7674 /// represent it in the AST. 7675 Incompatible 7676 }; 7677 7678 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 7679 /// assignment conversion type specified by ConvTy. This returns true if the 7680 /// conversion was invalid or false if the conversion was accepted. 7681 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, 7682 QualType DstType, QualType SrcType, 7683 Expr *SrcExpr, AssignmentAction Action, 7684 bool *Complained = nullptr); 7685 7686 /// CheckAssignmentConstraints - Perform type checking for assignment, 7687 /// argument passing, variable initialization, and function return values. 7688 /// C99 6.5.16. 7689 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 7690 QualType LHSType, 7691 QualType RHSType); 7692 7693 /// Check assignment constraints and optionally prepare for a conversion of 7694 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS 7695 /// is true. 7696 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 7697 ExprResult &RHS, CastKind &Kind, 7698 bool ConvertRHS = true); 7699 7700 /// Check assignment constraints for an assignment of RHS to LHSType. 7701 /// 7702 /// \param LHSType The destination type for the assignment. 7703 /// \param RHS The source expression for the assignment. 7704 /// \param Diagnose If \c true, diagnostics may be produced when checking 7705 /// for assignability. If a diagnostic is produced, \p RHS will be 7706 /// set to ExprError(). Note that this function may still return 7707 /// without producing a diagnostic, even for an invalid assignment. 7708 /// \param DiagnoseCFAudited If \c true, the target is a function parameter 7709 /// in an audited Core Foundation API and does not need to be checked 7710 /// for ARC retain issues. 7711 /// \param ConvertRHS If \c true, \p RHS will be updated to model the 7712 /// conversions necessary to perform the assignment. If \c false, 7713 /// \p Diagnose must also be \c false. 7714 AssignConvertType CheckSingleAssignmentConstraints( 7715 QualType LHSType, ExprResult &RHS, bool Diagnose = true, 7716 bool DiagnoseCFAudited = false, bool ConvertRHS = true); 7717 7718 // If the lhs type is a transparent union, check whether we 7719 // can initialize the transparent union with the given expression. 7720 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 7721 ExprResult &RHS); 7722 7723 /// the following "Check" methods will return a valid/converted QualType 7724 /// or a null QualType (indicating an error diagnostic was issued). 7725 7726 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 7727 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7728 ExprResult &RHS); 7729 7730 /// Diagnose cases where a scalar was implicitly converted to a vector and 7731 /// diagnose the underlying types. Otherwise, diagnose the error 7732 /// as invalid vector logical operands for non-C++ cases. 7733 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 7734 ExprResult &RHS); 7735 7736 QualType CheckMultiplyDivideOperands( // C99 6.5.5 7737 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 7738 bool IsDivide); 7739 QualType CheckRemainderOperands( // C99 6.5.5 7740 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7741 bool IsCompAssign = false); 7742 QualType CheckAdditionOperands( // C99 6.5.6 7743 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7744 BinaryOperatorKind Opc, QualType *CompLHSTy = nullptr); 7745 QualType CheckSubtractionOperands( // C99 6.5.6 7746 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7747 QualType *CompLHSTy = nullptr); 7748 QualType CheckShiftOperands( // C99 6.5.7 7749 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7750 BinaryOperatorKind Opc, bool IsCompAssign = false); 7751 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); 7752 QualType CheckCompareOperands( // C99 6.5.8/9 7753 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7754 BinaryOperatorKind Opc); 7755 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 7756 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7757 BinaryOperatorKind Opc); 7758 QualType CheckLogicalOperands( // C99 6.5.[13,14] 7759 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7760 BinaryOperatorKind Opc); 7761 // CheckAssignmentOperands is used for both simple and compound assignment. 7762 // For simple assignment, pass both expressions and a null converted type. 7763 // For compound assignment, pass both expressions and the converted type. 7764 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 7765 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, 7766 BinaryOperatorKind Opc); 7767 7768 /// To be used for checking whether the arguments being passed to 7769 /// function exceeds the number of parameters expected for it. 7770 static bool TooManyArguments(size_t NumParams, size_t NumArgs, 7771 bool PartialOverloading = false) { 7772 // We check whether we're just after a comma in code-completion. 7773 if (NumArgs > 0 && PartialOverloading) 7774 return NumArgs + 1 > NumParams; // If so, we view as an extra argument. 7775 return NumArgs > NumParams; 7776 } 7777 7778 /// Whether the AST is currently being rebuilt to correct immediate 7779 /// invocations. Immediate invocation candidates and references to consteval 7780 /// functions aren't tracked when this is set. 7781 bool RebuildingImmediateInvocation = false; 7782 7783 bool isAlwaysConstantEvaluatedContext() const { 7784 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext(); 7785 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) && 7786 !Ctx.InConditionallyConstantEvaluateContext; 7787 } 7788 7789 /// Determines whether we are currently in a context that 7790 /// is not evaluated as per C++ [expr] p5. 7791 bool isUnevaluatedContext() const { 7792 return currentEvaluationContext().isUnevaluated(); 7793 } 7794 7795 bool isImmediateFunctionContext() const { 7796 return currentEvaluationContext().isImmediateFunctionContext(); 7797 } 7798 7799 bool isInLifetimeExtendingContext() const { 7800 return currentEvaluationContext().InLifetimeExtendingContext; 7801 } 7802 7803 bool needsRebuildOfDefaultArgOrInit() const { 7804 return currentEvaluationContext().RebuildDefaultArgOrDefaultInit; 7805 } 7806 7807 bool isCheckingDefaultArgumentOrInitializer() const { 7808 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext(); 7809 return (Ctx.Context == 7810 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) || 7811 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer; 7812 } 7813 7814 std::optional<ExpressionEvaluationContextRecord::InitializationContext> 7815 InnermostDeclarationWithDelayedImmediateInvocations() const { 7816 assert(!ExprEvalContexts.empty() && 7817 "Must be in an expression evaluation context"); 7818 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) { 7819 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && 7820 Ctx.DelayedDefaultInitializationContext) 7821 return Ctx.DelayedDefaultInitializationContext; 7822 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() || 7823 Ctx.isUnevaluated()) 7824 break; 7825 } 7826 return std::nullopt; 7827 } 7828 7829 std::optional<ExpressionEvaluationContextRecord::InitializationContext> 7830 OutermostDeclarationWithDelayedImmediateInvocations() const { 7831 assert(!ExprEvalContexts.empty() && 7832 "Must be in an expression evaluation context"); 7833 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res; 7834 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) { 7835 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && 7836 !Ctx.DelayedDefaultInitializationContext && Res) 7837 break; 7838 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() || 7839 Ctx.isUnevaluated()) 7840 break; 7841 Res = Ctx.DelayedDefaultInitializationContext; 7842 } 7843 return Res; 7844 } 7845 7846 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { 7847 return getDefaultedFunctionKind(FD).asComparison(); 7848 } 7849 7850 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p 7851 /// SelfAssigned when inside a CXXMethodDecl. 7852 const FieldDecl * 7853 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned); 7854 7855 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 7856 7857 template <typename... Ts> 7858 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, 7859 const Ts &...Args) { 7860 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 7861 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); 7862 } 7863 7864 template <typename... Ts> 7865 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, 7866 const Ts &...Args) { 7867 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 7868 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); 7869 } 7870 7871 /// Abstract class used to diagnose incomplete types. 7872 struct TypeDiagnoser { 7873 TypeDiagnoser() {} 7874 7875 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; 7876 virtual ~TypeDiagnoser() {} 7877 }; 7878 7879 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { 7880 protected: 7881 unsigned DiagID; 7882 std::tuple<const Ts &...> Args; 7883 7884 template <std::size_t... Is> 7885 void emit(const SemaDiagnosticBuilder &DB, 7886 std::index_sequence<Is...>) const { 7887 // Apply all tuple elements to the builder in order. 7888 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; 7889 (void)Dummy; 7890 } 7891 7892 public: 7893 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) 7894 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { 7895 assert(DiagID != 0 && "no diagnostic for type diagnoser"); 7896 } 7897 7898 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 7899 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); 7900 emit(DB, std::index_sequence_for<Ts...>()); 7901 DB << T; 7902 } 7903 }; 7904 7905 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type 7906 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. 7907 /// For example, a diagnostic with no other parameters would generally have 7908 /// the form "...%select{incomplete|sizeless}0 type %1...". 7909 template <typename... Ts> 7910 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { 7911 public: 7912 SizelessTypeDiagnoser(unsigned DiagID, const Ts &...Args) 7913 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} 7914 7915 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 7916 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); 7917 this->emit(DB, std::index_sequence_for<Ts...>()); 7918 DB << T->isSizelessType() << T; 7919 } 7920 }; 7921 7922 /// Check an argument list for placeholders that we won't try to 7923 /// handle later. 7924 bool CheckArgsForPlaceholders(MultiExprArg args); 7925 7926 /// The C++ "std::source_location::__impl" struct, defined in 7927 /// \<source_location>. 7928 RecordDecl *StdSourceLocationImplDecl; 7929 7930 /// A stack of expression evaluation contexts. 7931 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 7932 7933 // Set of failed immediate invocations to avoid double diagnosing. 7934 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations; 7935 7936 /// List of SourceLocations where 'self' is implicitly retained inside a 7937 /// block. 7938 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> 7939 ImplicitlyRetainedSelfLocs; 7940 7941 /// Do an explicit extend of the given block pointer if we're in ARC. 7942 void maybeExtendBlockObject(ExprResult &E); 7943 7944 std::vector<std::pair<QualType, unsigned>> ExcessPrecisionNotSatisfied; 7945 SourceLocation LocationOfExcessPrecisionNotSatisfied; 7946 void DiagnosePrecisionLossInComplexDivision(); 7947 7948 private: 7949 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 7950 7951 /// Methods for marking which expressions involve dereferencing a pointer 7952 /// marked with the 'noderef' attribute. Expressions are checked bottom up as 7953 /// they are parsed, meaning that a noderef pointer may not be accessed. For 7954 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the 7955 /// `*p`, but need to check that `address of` is called on it. This requires 7956 /// keeping a container of all pending expressions and checking if the address 7957 /// of them are eventually taken. 7958 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); 7959 void CheckAddressOfNoDeref(const Expr *E); 7960 7961 ///@} 7962 7963 // 7964 // 7965 // ------------------------------------------------------------------------- 7966 // 7967 // 7968 7969 /// \name C++ Expressions 7970 /// Implementations are in SemaExprCXX.cpp 7971 ///@{ 7972 7973 public: 7974 /// The C++ "std::bad_alloc" class, which is defined by the C++ 7975 /// standard library. 7976 LazyDeclPtr StdBadAlloc; 7977 7978 /// The C++ "std::align_val_t" enum class, which is defined by the C++ 7979 /// standard library. 7980 LazyDeclPtr StdAlignValT; 7981 7982 /// The C++ "type_info" declaration, which is defined in \<typeinfo>. 7983 RecordDecl *CXXTypeInfoDecl; 7984 7985 /// A flag to remember whether the implicit forms of operator new and delete 7986 /// have been declared. 7987 bool GlobalNewDeleteDeclared; 7988 7989 /// Delete-expressions to be analyzed at the end of translation unit 7990 /// 7991 /// This list contains class members, and locations of delete-expressions 7992 /// that could not be proven as to whether they mismatch with new-expression 7993 /// used in initializer of the field. 7994 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; 7995 7996 /// Handle the result of the special case name lookup for inheriting 7997 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as 7998 /// constructor names in member using declarations, even if 'X' is not the 7999 /// name of the corresponding type. 8000 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 8001 SourceLocation NameLoc, 8002 const IdentifierInfo &Name); 8003 8004 ParsedType getConstructorName(const IdentifierInfo &II, 8005 SourceLocation NameLoc, Scope *S, 8006 CXXScopeSpec &SS, bool EnteringContext); 8007 ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, 8008 Scope *S, CXXScopeSpec &SS, 8009 ParsedType ObjectType, bool EnteringContext); 8010 8011 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, 8012 ParsedType ObjectType); 8013 8014 /// Build a C++ typeid expression with a type operand. 8015 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, 8016 TypeSourceInfo *Operand, SourceLocation RParenLoc); 8017 8018 /// Build a C++ typeid expression with an expression operand. 8019 ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, 8020 Expr *Operand, SourceLocation RParenLoc); 8021 8022 /// ActOnCXXTypeid - Parse typeid( something ). 8023 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 8024 bool isType, void *TyOrExpr, 8025 SourceLocation RParenLoc); 8026 8027 /// Build a Microsoft __uuidof expression with a type operand. 8028 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, 8029 TypeSourceInfo *Operand, SourceLocation RParenLoc); 8030 8031 /// Build a Microsoft __uuidof expression with an expression operand. 8032 ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, 8033 Expr *Operand, SourceLocation RParenLoc); 8034 8035 /// ActOnCXXUuidof - Parse __uuidof( something ). 8036 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 8037 bool isType, void *TyOrExpr, 8038 SourceLocation RParenLoc); 8039 8040 //// ActOnCXXThis - Parse 'this' pointer. 8041 ExprResult ActOnCXXThis(SourceLocation Loc); 8042 8043 /// Check whether the type of 'this' is valid in the current context. 8044 bool CheckCXXThisType(SourceLocation Loc, QualType Type); 8045 8046 /// Build a CXXThisExpr and mark it referenced in the current context. 8047 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); 8048 void MarkThisReferenced(CXXThisExpr *This); 8049 8050 /// Try to retrieve the type of the 'this' pointer. 8051 /// 8052 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 8053 QualType getCurrentThisType(); 8054 8055 /// When non-NULL, the C++ 'this' expression is allowed despite the 8056 /// current context not being a non-static member function. In such cases, 8057 /// this provides the type used for 'this'. 8058 QualType CXXThisTypeOverride; 8059 8060 /// RAII object used to temporarily allow the C++ 'this' expression 8061 /// to be used, with the given qualifiers on the current class type. 8062 class CXXThisScopeRAII { 8063 Sema &S; 8064 QualType OldCXXThisTypeOverride; 8065 bool Enabled; 8066 8067 public: 8068 /// Introduce a new scope where 'this' may be allowed (when enabled), 8069 /// using the given declaration (which is either a class template or a 8070 /// class) along with the given qualifiers. 8071 /// along with the qualifiers placed on '*this'. 8072 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, 8073 bool Enabled = true); 8074 8075 ~CXXThisScopeRAII(); 8076 }; 8077 8078 /// Make sure the value of 'this' is actually available in the current 8079 /// context, if it is a potentially evaluated context. 8080 /// 8081 /// \param Loc The location at which the capture of 'this' occurs. 8082 /// 8083 /// \param Explicit Whether 'this' is explicitly captured in a lambda 8084 /// capture list. 8085 /// 8086 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 8087 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 8088 /// This is useful when enclosing lambdas must speculatively capture 8089 /// 'this' that may or may not be used in certain specializations of 8090 /// a nested generic lambda (depending on whether the name resolves to 8091 /// a non-static member function or a static function). 8092 /// \return returns 'true' if failed, 'false' if success. 8093 bool CheckCXXThisCapture( 8094 SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, 8095 const unsigned *const FunctionScopeIndexToStopAt = nullptr, 8096 bool ByCopy = false); 8097 8098 /// Determine whether the given type is the type of *this that is used 8099 /// outside of the body of a member function for a type that is currently 8100 /// being defined. 8101 bool isThisOutsideMemberFunctionBody(QualType BaseType); 8102 8103 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 8104 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 8105 8106 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 8107 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 8108 8109 //// ActOnCXXThrow - Parse throw expressions. 8110 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 8111 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 8112 bool IsThrownVarInScope); 8113 8114 /// CheckCXXThrowOperand - Validate the operand of a throw. 8115 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); 8116 8117 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 8118 /// Can be interpreted either as function-style casting ("int(x)") 8119 /// or class type construction ("ClassType(x,y,z)") 8120 /// or creation of a value-initialized type ("int()"). 8121 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 8122 SourceLocation LParenOrBraceLoc, 8123 MultiExprArg Exprs, 8124 SourceLocation RParenOrBraceLoc, 8125 bool ListInitialization); 8126 8127 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 8128 SourceLocation LParenLoc, 8129 MultiExprArg Exprs, 8130 SourceLocation RParenLoc, 8131 bool ListInitialization); 8132 8133 /// Parsed a C++ 'new' expression (C++ 5.3.4). 8134 /// 8135 /// E.g.: 8136 /// @code new (memory) int[size][4] @endcode 8137 /// or 8138 /// @code ::new Foo(23, "hello") @endcode 8139 /// 8140 /// \param StartLoc The first location of the expression. 8141 /// \param UseGlobal True if 'new' was prefixed with '::'. 8142 /// \param PlacementLParen Opening paren of the placement arguments. 8143 /// \param PlacementArgs Placement new arguments. 8144 /// \param PlacementRParen Closing paren of the placement arguments. 8145 /// \param TypeIdParens If the type is in parens, the source range. 8146 /// \param D The type to be allocated, as well as array dimensions. 8147 /// \param Initializer The initializing expression or initializer-list, or 8148 /// null if there is none. 8149 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 8150 SourceLocation PlacementLParen, 8151 MultiExprArg PlacementArgs, 8152 SourceLocation PlacementRParen, 8153 SourceRange TypeIdParens, Declarator &D, 8154 Expr *Initializer); 8155 ExprResult 8156 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, 8157 MultiExprArg PlacementArgs, SourceLocation PlacementRParen, 8158 SourceRange TypeIdParens, QualType AllocType, 8159 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize, 8160 SourceRange DirectInitRange, Expr *Initializer); 8161 8162 /// Determine whether \p FD is an aligned allocation or deallocation 8163 /// function that is unavailable. 8164 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; 8165 8166 /// Produce diagnostics if \p FD is an aligned allocation or deallocation 8167 /// function that is unavailable. 8168 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 8169 SourceLocation Loc); 8170 8171 /// Checks that a type is suitable as the allocated type 8172 /// in a new-expression. 8173 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 8174 SourceRange R); 8175 8176 /// The scope in which to find allocation functions. 8177 enum AllocationFunctionScope { 8178 /// Only look for allocation functions in the global scope. 8179 AFS_Global, 8180 /// Only look for allocation functions in the scope of the 8181 /// allocated class. 8182 AFS_Class, 8183 /// Look for allocation functions in both the global scope 8184 /// and in the scope of the allocated class. 8185 AFS_Both 8186 }; 8187 8188 /// Finds the overloads of operator new and delete that are appropriate 8189 /// for the allocation. 8190 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 8191 AllocationFunctionScope NewScope, 8192 AllocationFunctionScope DeleteScope, 8193 QualType AllocType, bool IsArray, 8194 bool &PassAlignment, MultiExprArg PlaceArgs, 8195 FunctionDecl *&OperatorNew, 8196 FunctionDecl *&OperatorDelete, 8197 bool Diagnose = true); 8198 8199 /// DeclareGlobalNewDelete - Declare the global forms of operator new and 8200 /// delete. These are: 8201 /// @code 8202 /// // C++03: 8203 /// void* operator new(std::size_t) throw(std::bad_alloc); 8204 /// void* operator new[](std::size_t) throw(std::bad_alloc); 8205 /// void operator delete(void *) throw(); 8206 /// void operator delete[](void *) throw(); 8207 /// // C++11: 8208 /// void* operator new(std::size_t); 8209 /// void* operator new[](std::size_t); 8210 /// void operator delete(void *) noexcept; 8211 /// void operator delete[](void *) noexcept; 8212 /// // C++1y: 8213 /// void* operator new(std::size_t); 8214 /// void* operator new[](std::size_t); 8215 /// void operator delete(void *) noexcept; 8216 /// void operator delete[](void *) noexcept; 8217 /// void operator delete(void *, std::size_t) noexcept; 8218 /// void operator delete[](void *, std::size_t) noexcept; 8219 /// @endcode 8220 /// Note that the placement and nothrow forms of new are *not* implicitly 8221 /// declared. Their use requires including \<new\>. 8222 void DeclareGlobalNewDelete(); 8223 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 8224 ArrayRef<QualType> Params); 8225 8226 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 8227 DeclarationName Name, FunctionDecl *&Operator, 8228 bool Diagnose = true, bool WantSize = false, 8229 bool WantAligned = false); 8230 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 8231 bool CanProvideSize, 8232 bool Overaligned, 8233 DeclarationName Name); 8234 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, 8235 CXXRecordDecl *RD); 8236 8237 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 8238 /// @code ::delete ptr; @endcode 8239 /// or 8240 /// @code delete [] ptr; @endcode 8241 ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 8242 bool ArrayForm, Expr *Operand); 8243 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 8244 bool IsDelete, bool CallCanBeVirtual, 8245 bool WarnOnNonAbstractTypes, 8246 SourceLocation DtorLoc); 8247 8248 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 8249 Expr *Operand, SourceLocation RParen); 8250 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 8251 SourceLocation RParen); 8252 8253 ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, 8254 SourceLocation OpLoc, 8255 tok::TokenKind OpKind, 8256 ParsedType &ObjectType, 8257 bool &MayBePseudoDestructor); 8258 8259 ExprResult BuildPseudoDestructorExpr( 8260 Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, 8261 const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, 8262 SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); 8263 8264 ExprResult ActOnPseudoDestructorExpr( 8265 Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, 8266 CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, 8267 SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); 8268 8269 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 8270 SourceLocation OpLoc, 8271 tok::TokenKind OpKind, 8272 SourceLocation TildeLoc, 8273 const DeclSpec &DS); 8274 8275 /// MaybeCreateExprWithCleanups - If the current full-expression 8276 /// requires any cleanups, surround it with a ExprWithCleanups node. 8277 /// Otherwise, just returns the passed-in expression. 8278 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 8279 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 8280 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 8281 8282 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { 8283 return ActOnFinishFullExpr( 8284 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); 8285 } 8286 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 8287 bool DiscardedValue, bool IsConstexpr = false, 8288 bool IsTemplateArgument = false); 8289 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 8290 8291 /// Process the expression contained within a decltype. For such expressions, 8292 /// certain semantic checks on temporaries are delayed until this point, and 8293 /// are omitted for the 'topmost' call in the decltype expression. If the 8294 /// topmost call bound a temporary, strip that temporary off the expression. 8295 ExprResult ActOnDecltypeExpression(Expr *E); 8296 8297 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, 8298 bool IsUDSuffix); 8299 8300 bool isUsualDeallocationFunction(const CXXMethodDecl *FD); 8301 8302 ConditionResult ActOnConditionVariable(Decl *ConditionVar, 8303 SourceLocation StmtLoc, 8304 ConditionKind CK); 8305 8306 /// Check the use of the given variable as a C++ condition in an if, 8307 /// while, do-while, or switch statement. 8308 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 8309 SourceLocation StmtLoc, ConditionKind CK); 8310 8311 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 8312 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); 8313 8314 /// Helper function to determine whether this is the (deprecated) C++ 8315 /// conversion from a string literal to a pointer to non-const char or 8316 /// non-const wchar_t (for narrow and wide string literals, 8317 /// respectively). 8318 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 8319 8320 /// PerformImplicitConversion - Perform an implicit conversion of the 8321 /// expression From to the type ToType using the pre-computed implicit 8322 /// conversion sequence ICS. Returns the converted 8323 /// expression. Action is the kind of conversion we're performing, 8324 /// used in the error message. 8325 ExprResult PerformImplicitConversion( 8326 Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, 8327 AssignmentAction Action, 8328 CheckedConversionKind CCK = CheckedConversionKind::Implicit); 8329 8330 /// PerformImplicitConversion - Perform an implicit conversion of the 8331 /// expression From to the type ToType by following the standard 8332 /// conversion sequence SCS. Returns the converted 8333 /// expression. Flavor is the context in which we're performing this 8334 /// conversion, for use in error messages. 8335 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 8336 const StandardConversionSequence &SCS, 8337 AssignmentAction Action, 8338 CheckedConversionKind CCK); 8339 8340 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N); 8341 8342 /// Parsed one of the type trait support pseudo-functions. 8343 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 8344 ArrayRef<ParsedType> Args, 8345 SourceLocation RParenLoc); 8346 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 8347 ArrayRef<TypeSourceInfo *> Args, 8348 SourceLocation RParenLoc); 8349 8350 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support 8351 /// pseudo-functions. 8352 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, 8353 ParsedType LhsTy, Expr *DimExpr, 8354 SourceLocation RParen); 8355 8356 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, 8357 TypeSourceInfo *TSInfo, Expr *DimExpr, 8358 SourceLocation RParen); 8359 8360 /// ActOnExpressionTrait - Parsed one of the unary type trait support 8361 /// pseudo-functions. 8362 ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, 8363 Expr *Queried, SourceLocation RParen); 8364 8365 ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, 8366 Expr *Queried, SourceLocation RParen); 8367 8368 QualType CheckPointerToMemberOperands( // C++ 5.5 8369 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, 8370 bool isIndirect); 8371 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 8372 ExprResult &RHS, 8373 SourceLocation QuestionLoc); 8374 8375 QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond, 8376 ExprResult &LHS, ExprResult &RHS, 8377 SourceLocation QuestionLoc); 8378 8379 /// Check the operands of ?: under C++ semantics. 8380 /// 8381 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 8382 /// extension. In this case, LHS == Cond. (But they're not aliases.) 8383 /// 8384 /// This function also implements GCC's vector extension and the 8385 /// OpenCL/ext_vector_type extension for conditionals. The vector extensions 8386 /// permit the use of a?b:c where the type of a is that of a integer vector 8387 /// with the same number of elements and size as the vectors of b and c. If 8388 /// one of either b or c is a scalar it is implicitly converted to match the 8389 /// type of the vector. Otherwise the expression is ill-formed. If both b and 8390 /// c are scalars, then b and c are checked and converted to the type of a if 8391 /// possible. 8392 /// 8393 /// The expressions are evaluated differently for GCC's and OpenCL's 8394 /// extensions. For the GCC extension, the ?: operator is evaluated as 8395 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). 8396 /// For the OpenCL extensions, the ?: operator is evaluated as 8397 /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. , 8398 /// most-significant-bit-set(a[n]) ? b[n] : c[n]). 8399 QualType CXXCheckConditionalOperands( // C++ 5.16 8400 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, 8401 ExprObjectKind &OK, SourceLocation questionLoc); 8402 8403 /// Find a merged pointer type and convert the two expressions to it. 8404 /// 8405 /// This finds the composite pointer type for \p E1 and \p E2 according to 8406 /// C++2a [expr.type]p3. It converts both expressions to this type and returns 8407 /// it. It does not emit diagnostics (FIXME: that's not true if \p 8408 /// ConvertArgs is \c true). 8409 /// 8410 /// \param Loc The location of the operator requiring these two expressions to 8411 /// be converted to the composite pointer type. 8412 /// 8413 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target 8414 /// type. 8415 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 8416 bool ConvertArgs = true); 8417 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, 8418 ExprResult &E2, bool ConvertArgs = true) { 8419 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 8420 QualType Composite = 8421 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); 8422 E1 = E1Tmp; 8423 E2 = E2Tmp; 8424 return Composite; 8425 } 8426 8427 /// MaybeBindToTemporary - If the passed in expression has a record type with 8428 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 8429 /// it simply returns the passed in expression. 8430 ExprResult MaybeBindToTemporary(Expr *E); 8431 8432 /// IgnoredValueConversions - Given that an expression's result is 8433 /// syntactically ignored, perform any conversions that are 8434 /// required. 8435 ExprResult IgnoredValueConversions(Expr *E); 8436 8437 ExprResult CheckUnevaluatedOperand(Expr *E); 8438 8439 /// Process any TypoExprs in the given Expr and its children, 8440 /// generating diagnostics as appropriate and returning a new Expr if there 8441 /// were typos that were all successfully corrected and ExprError if one or 8442 /// more typos could not be corrected. 8443 /// 8444 /// \param E The Expr to check for TypoExprs. 8445 /// 8446 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its 8447 /// initializer. 8448 /// 8449 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it 8450 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. 8451 /// 8452 /// \param Filter A function applied to a newly rebuilt Expr to determine if 8453 /// it is an acceptable/usable result from a single combination of typo 8454 /// corrections. As long as the filter returns ExprError, different 8455 /// combinations of corrections will be tried until all are exhausted. 8456 ExprResult CorrectDelayedTyposInExpr( 8457 Expr *E, VarDecl *InitDecl = nullptr, 8458 bool RecoverUncorrectedTypos = false, 8459 llvm::function_ref<ExprResult(Expr *)> Filter = 8460 [](Expr *E) -> ExprResult { return E; }); 8461 8462 ExprResult CorrectDelayedTyposInExpr( 8463 ExprResult ER, VarDecl *InitDecl = nullptr, 8464 bool RecoverUncorrectedTypos = false, 8465 llvm::function_ref<ExprResult(Expr *)> Filter = 8466 [](Expr *E) -> ExprResult { return E; }) { 8467 return ER.isInvalid() 8468 ? ER 8469 : CorrectDelayedTyposInExpr(ER.get(), InitDecl, 8470 RecoverUncorrectedTypos, Filter); 8471 } 8472 8473 /// Describes the result of an "if-exists" condition check. 8474 enum IfExistsResult { 8475 /// The symbol exists. 8476 IER_Exists, 8477 8478 /// The symbol does not exist. 8479 IER_DoesNotExist, 8480 8481 /// The name is a dependent name, so the results will differ 8482 /// from one instantiation to the next. 8483 IER_Dependent, 8484 8485 /// An error occurred. 8486 IER_Error 8487 }; 8488 8489 IfExistsResult 8490 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 8491 const DeclarationNameInfo &TargetNameInfo); 8492 8493 IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, 8494 SourceLocation KeywordLoc, 8495 bool IsIfExists, CXXScopeSpec &SS, 8496 UnqualifiedId &Name); 8497 8498 RequiresExprBodyDecl * 8499 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 8500 ArrayRef<ParmVarDecl *> LocalParameters, 8501 Scope *BodyScope); 8502 void ActOnFinishRequiresExpr(); 8503 concepts::Requirement *ActOnSimpleRequirement(Expr *E); 8504 concepts::Requirement *ActOnTypeRequirement(SourceLocation TypenameKWLoc, 8505 CXXScopeSpec &SS, 8506 SourceLocation NameLoc, 8507 const IdentifierInfo *TypeName, 8508 TemplateIdAnnotation *TemplateId); 8509 concepts::Requirement *ActOnCompoundRequirement(Expr *E, 8510 SourceLocation NoexceptLoc); 8511 concepts::Requirement *ActOnCompoundRequirement( 8512 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 8513 TemplateIdAnnotation *TypeConstraint, unsigned Depth); 8514 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); 8515 concepts::ExprRequirement *BuildExprRequirement( 8516 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, 8517 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 8518 concepts::ExprRequirement *BuildExprRequirement( 8519 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, 8520 bool IsSatisfied, SourceLocation NoexceptLoc, 8521 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 8522 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); 8523 concepts::TypeRequirement *BuildTypeRequirement( 8524 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 8525 concepts::NestedRequirement *BuildNestedRequirement(Expr *E); 8526 concepts::NestedRequirement * 8527 BuildNestedRequirement(StringRef InvalidConstraintEntity, 8528 const ASTConstraintSatisfaction &Satisfaction); 8529 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, 8530 RequiresExprBodyDecl *Body, 8531 SourceLocation LParenLoc, 8532 ArrayRef<ParmVarDecl *> LocalParameters, 8533 SourceLocation RParenLoc, 8534 ArrayRef<concepts::Requirement *> Requirements, 8535 SourceLocation ClosingBraceLoc); 8536 8537 private: 8538 ExprResult BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 8539 bool IsDelete); 8540 8541 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); 8542 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 8543 bool DeleteWasArrayForm); 8544 8545 ///@} 8546 8547 // 8548 // 8549 // ------------------------------------------------------------------------- 8550 // 8551 // 8552 8553 /// \name Member Access Expressions 8554 /// Implementations are in SemaExprMember.cpp 8555 ///@{ 8556 8557 public: 8558 /// Check whether an expression might be an implicit class member access. 8559 bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, 8560 bool IsAddressOfOperand); 8561 8562 /// Builds an expression which might be an implicit member expression. 8563 ExprResult BuildPossibleImplicitMemberExpr( 8564 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, 8565 const TemplateArgumentListInfo *TemplateArgs, const Scope *S); 8566 8567 /// Builds an implicit member access expression. The current context 8568 /// is known to be an instance method, and the given unqualified lookup 8569 /// set is known to contain only instance members, at least one of which 8570 /// is from an appropriate type. 8571 ExprResult 8572 BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 8573 LookupResult &R, 8574 const TemplateArgumentListInfo *TemplateArgs, 8575 bool IsDefiniteInstance, const Scope *S); 8576 8577 ExprResult ActOnDependentMemberExpr( 8578 Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, 8579 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 8580 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 8581 const TemplateArgumentListInfo *TemplateArgs); 8582 8583 /// The main callback when the parser finds something like 8584 /// expression . [nested-name-specifier] identifier 8585 /// expression -> [nested-name-specifier] identifier 8586 /// where 'identifier' encompasses a fairly broad spectrum of 8587 /// possibilities, including destructor and operator references. 8588 /// 8589 /// \param OpKind either tok::arrow or tok::period 8590 /// \param ObjCImpDecl the current Objective-C \@implementation 8591 /// decl; this is an ugly hack around the fact that Objective-C 8592 /// \@implementations aren't properly put in the context chain 8593 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 8594 tok::TokenKind OpKind, CXXScopeSpec &SS, 8595 SourceLocation TemplateKWLoc, 8596 UnqualifiedId &Member, Decl *ObjCImpDecl); 8597 8598 MemberExpr * 8599 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 8600 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, 8601 ValueDecl *Member, DeclAccessPair FoundDecl, 8602 bool HadMultipleCandidates, 8603 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 8604 ExprValueKind VK, ExprObjectKind OK, 8605 const TemplateArgumentListInfo *TemplateArgs = nullptr); 8606 8607 // Check whether the declarations we found through a nested-name 8608 // specifier in a member expression are actually members of the base 8609 // type. The restriction here is: 8610 // 8611 // C++ [expr.ref]p2: 8612 // ... In these cases, the id-expression shall name a 8613 // member of the class or of one of its base classes. 8614 // 8615 // So it's perfectly legitimate for the nested-name specifier to name 8616 // an unrelated class, and for us to find an overload set including 8617 // decls from classes which are not superclasses, as long as the decl 8618 // we actually pick through overload resolution is from a superclass. 8619 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 8620 const CXXScopeSpec &SS, 8621 const LookupResult &R); 8622 8623 // This struct is for use by ActOnMemberAccess to allow 8624 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 8625 // changing the access operator from a '.' to a '->' (to see if that is the 8626 // change needed to fix an error about an unknown member, e.g. when the class 8627 // defines a custom operator->). 8628 struct ActOnMemberAccessExtraArgs { 8629 Scope *S; 8630 UnqualifiedId &Id; 8631 Decl *ObjCImpDecl; 8632 }; 8633 8634 ExprResult BuildMemberReferenceExpr( 8635 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 8636 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 8637 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 8638 const TemplateArgumentListInfo *TemplateArgs, const Scope *S, 8639 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 8640 8641 ExprResult 8642 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 8643 bool IsArrow, const CXXScopeSpec &SS, 8644 SourceLocation TemplateKWLoc, 8645 NamedDecl *FirstQualifierInScope, LookupResult &R, 8646 const TemplateArgumentListInfo *TemplateArgs, 8647 const Scope *S, bool SuppressQualifierCheck = false, 8648 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 8649 8650 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, 8651 SourceLocation OpLoc, 8652 const CXXScopeSpec &SS, FieldDecl *Field, 8653 DeclAccessPair FoundDecl, 8654 const DeclarationNameInfo &MemberNameInfo); 8655 8656 /// Perform conversions on the LHS of a member access expression. 8657 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 8658 8659 ExprResult BuildAnonymousStructUnionMemberReference( 8660 const CXXScopeSpec &SS, SourceLocation nameLoc, 8661 IndirectFieldDecl *indirectField, 8662 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 8663 Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); 8664 8665 private: 8666 void CheckMemberAccessOfNoDeref(const MemberExpr *E); 8667 8668 ///@} 8669 8670 // 8671 // 8672 // ------------------------------------------------------------------------- 8673 // 8674 // 8675 8676 /// \name Initializers 8677 /// Implementations are in SemaInit.cpp 8678 ///@{ 8679 8680 public: 8681 /// Stack of types that correspond to the parameter entities that are 8682 /// currently being copy-initialized. Can be empty. 8683 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; 8684 8685 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *> 8686 AggregateDeductionCandidates; 8687 8688 bool IsStringInit(Expr *Init, const ArrayType *AT); 8689 8690 /// Determine whether we can perform aggregate initialization for the purposes 8691 /// of overload resolution. 8692 bool CanPerformAggregateInitializationForOverloadResolution( 8693 const InitializedEntity &Entity, InitListExpr *From); 8694 8695 ExprResult ActOnDesignatedInitializer(Designation &Desig, 8696 SourceLocation EqualOrColonLoc, 8697 bool GNUSyntax, ExprResult Init); 8698 8699 /// Check that the lifetime of the initializer (and its subobjects) is 8700 /// sufficient for initializing the entity, and perform lifetime extension 8701 /// (when permitted) if not. 8702 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); 8703 8704 MaterializeTemporaryExpr * 8705 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 8706 bool BoundToLvalueReference); 8707 8708 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize 8709 /// it as an xvalue. In C++98, the result will still be a prvalue, because 8710 /// we don't have xvalues there. 8711 ExprResult TemporaryMaterializationConversion(Expr *E); 8712 8713 ExprResult PerformQualificationConversion( 8714 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue, 8715 CheckedConversionKind CCK = CheckedConversionKind::Implicit); 8716 8717 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 8718 ExprResult Init); 8719 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 8720 SourceLocation EqualLoc, ExprResult Init, 8721 bool TopLevelOfInitList = false, 8722 bool AllowExplicit = false); 8723 8724 QualType DeduceTemplateSpecializationFromInitializer( 8725 TypeSourceInfo *TInfo, const InitializedEntity &Entity, 8726 const InitializationKind &Kind, MultiExprArg Init); 8727 8728 ///@} 8729 8730 // 8731 // 8732 // ------------------------------------------------------------------------- 8733 // 8734 // 8735 8736 /// \name C++ Lambda Expressions 8737 /// Implementations are in SemaLambda.cpp 8738 ///@{ 8739 8740 public: 8741 /// Create a new lambda closure type. 8742 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 8743 TypeSourceInfo *Info, 8744 unsigned LambdaDependencyKind, 8745 LambdaCaptureDefault CaptureDefault); 8746 8747 /// Number lambda for linkage purposes if necessary. 8748 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, 8749 std::optional<CXXRecordDecl::LambdaNumbering> 8750 NumberingOverride = std::nullopt); 8751 8752 /// Endow the lambda scope info with the relevant properties. 8753 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, 8754 SourceRange IntroducerRange, 8755 LambdaCaptureDefault CaptureDefault, 8756 SourceLocation CaptureDefaultLoc, bool ExplicitParams, 8757 bool Mutable); 8758 8759 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange, 8760 CXXRecordDecl *Class); 8761 8762 void AddTemplateParametersToLambdaCallOperator( 8763 CXXMethodDecl *CallOperator, CXXRecordDecl *Class, 8764 TemplateParameterList *TemplateParams); 8765 8766 void CompleteLambdaCallOperator( 8767 CXXMethodDecl *Method, SourceLocation LambdaLoc, 8768 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, 8769 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, 8770 StorageClass SC, ArrayRef<ParmVarDecl *> Params, 8771 bool HasExplicitResultType); 8772 8773 /// Returns true if the explicit object parameter was invalid. 8774 bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, 8775 SourceLocation CallLoc); 8776 8777 /// Perform initialization analysis of the init-capture and perform 8778 /// any implicit conversions such as an lvalue-to-rvalue conversion if 8779 /// not being used to initialize a reference. 8780 ParsedType actOnLambdaInitCaptureInitialization( 8781 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 8782 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { 8783 return ParsedType::make(buildLambdaInitCaptureInitialization( 8784 Loc, ByRef, EllipsisLoc, std::nullopt, Id, 8785 InitKind != LambdaCaptureInitKind::CopyInit, Init)); 8786 } 8787 QualType buildLambdaInitCaptureInitialization( 8788 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 8789 std::optional<unsigned> NumExpansions, IdentifierInfo *Id, 8790 bool DirectInit, Expr *&Init); 8791 8792 /// Create a dummy variable within the declcontext of the lambda's 8793 /// call operator, for name lookup purposes for a lambda init capture. 8794 /// 8795 /// CodeGen handles emission of lambda captures, ignoring these dummy 8796 /// variables appropriately. 8797 VarDecl *createLambdaInitCaptureVarDecl( 8798 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, 8799 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx); 8800 8801 /// Add an init-capture to a lambda scope. 8802 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef); 8803 8804 /// Note that we have finished the explicit captures for the 8805 /// given lambda. 8806 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 8807 8808 /// Deduce a block or lambda's return type based on the return 8809 /// statements present in the body. 8810 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 8811 8812 /// Once the Lambdas capture are known, we can start to create the closure, 8813 /// call operator method, and keep track of the captures. 8814 /// We do the capture lookup here, but they are not actually captured until 8815 /// after we know what the qualifiers of the call operator are. 8816 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, 8817 Scope *CurContext); 8818 8819 /// This is called after parsing the explicit template parameter list 8820 /// on a lambda (if it exists) in C++2a. 8821 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, 8822 SourceLocation LAngleLoc, 8823 ArrayRef<NamedDecl *> TParams, 8824 SourceLocation RAngleLoc, 8825 ExprResult RequiresClause); 8826 8827 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, 8828 SourceLocation MutableLoc); 8829 8830 void ActOnLambdaClosureParameters( 8831 Scope *LambdaScope, 8832 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo); 8833 8834 /// ActOnStartOfLambdaDefinition - This is called just before we start 8835 /// parsing the body of a lambda; it analyzes the explicit captures and 8836 /// arguments, and sets up various data-structures for the body of the 8837 /// lambda. 8838 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 8839 Declarator &ParamInfo, const DeclSpec &DS); 8840 8841 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 8842 /// is invoked to pop the information about the lambda. 8843 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 8844 bool IsInstantiation = false); 8845 8846 /// ActOnLambdaExpr - This is called when the body of a lambda expression 8847 /// was successfully completed. 8848 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body); 8849 8850 /// Does copying/destroying the captured variable have side effects? 8851 bool CaptureHasSideEffects(const sema::Capture &From); 8852 8853 /// Diagnose if an explicit lambda capture is unused. Returns true if a 8854 /// diagnostic is emitted. 8855 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 8856 const sema::Capture &From); 8857 8858 /// Build a FieldDecl suitable to hold the given capture. 8859 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); 8860 8861 /// Initialize the given capture with a suitable expression. 8862 ExprResult BuildCaptureInit(const sema::Capture &Capture, 8863 SourceLocation ImplicitCaptureLoc, 8864 bool IsOpenMPMapping = false); 8865 8866 /// Complete a lambda-expression having processed and attached the 8867 /// lambda body. 8868 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 8869 sema::LambdaScopeInfo *LSI); 8870 8871 /// Get the return type to use for a lambda's conversion function(s) to 8872 /// function pointer type, given the type of the call operator. 8873 QualType 8874 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, 8875 CallingConv CC); 8876 8877 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 8878 SourceLocation ConvLocation, 8879 CXXConversionDecl *Conv, Expr *Src); 8880 8881 class LambdaScopeForCallOperatorInstantiationRAII 8882 : private FunctionScopeRAII { 8883 public: 8884 LambdaScopeForCallOperatorInstantiationRAII( 8885 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, 8886 LocalInstantiationScope &Scope, 8887 bool ShouldAddDeclsFromParentScope = true); 8888 }; 8889 8890 /// Compute the mangling number context for a lambda expression or 8891 /// block literal. Also return the extra mangling decl if any. 8892 /// 8893 /// \param DC - The DeclContext containing the lambda expression or 8894 /// block literal. 8895 std::tuple<MangleNumberingContext *, Decl *> 8896 getCurrentMangleNumberContext(const DeclContext *DC); 8897 8898 ///@} 8899 8900 // 8901 // 8902 // ------------------------------------------------------------------------- 8903 // 8904 // 8905 8906 /// \name Name Lookup 8907 /// 8908 /// These routines provide name lookup that is used during semantic 8909 /// analysis to resolve the various kinds of names (identifiers, 8910 /// overloaded operator names, constructor names, etc.) into zero or 8911 /// more declarations within a particular scope. The major entry 8912 /// points are LookupName, which performs unqualified name lookup, 8913 /// and LookupQualifiedName, which performs qualified name lookup. 8914 /// 8915 /// All name lookup is performed based on some specific criteria, 8916 /// which specify what names will be visible to name lookup and how 8917 /// far name lookup should work. These criteria are important both 8918 /// for capturing language semantics (certain lookups will ignore 8919 /// certain names, for example) and for performance, since name 8920 /// lookup is often a bottleneck in the compilation of C++. Name 8921 /// lookup criteria is specified via the LookupCriteria enumeration. 8922 /// 8923 /// The results of name lookup can vary based on the kind of name 8924 /// lookup performed, the current language, and the translation 8925 /// unit. In C, for example, name lookup will either return nothing 8926 /// (no entity found) or a single declaration. In C++, name lookup 8927 /// can additionally refer to a set of overloaded functions or 8928 /// result in an ambiguity. All of the possible results of name 8929 /// lookup are captured by the LookupResult class, which provides 8930 /// the ability to distinguish among them. 8931 /// 8932 /// Implementations are in SemaLookup.cpp 8933 ///@{ 8934 8935 public: 8936 /// Tracks whether we are in a context where typo correction is 8937 /// disabled. 8938 bool DisableTypoCorrection; 8939 8940 /// The number of typos corrected by CorrectTypo. 8941 unsigned TyposCorrected; 8942 8943 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 8944 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 8945 8946 /// A cache containing identifiers for which typo correction failed and 8947 /// their locations, so that repeated attempts to correct an identifier in a 8948 /// given location are ignored if typo correction already failed for it. 8949 IdentifierSourceLocations TypoCorrectionFailures; 8950 8951 /// SpecialMemberOverloadResult - The overloading result for a special member 8952 /// function. 8953 /// 8954 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 8955 /// integer are used to determine whether overload resolution succeeded. 8956 class SpecialMemberOverloadResult { 8957 public: 8958 enum Kind { NoMemberOrDeleted, Ambiguous, Success }; 8959 8960 private: 8961 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair; 8962 8963 public: 8964 SpecialMemberOverloadResult() {} 8965 SpecialMemberOverloadResult(CXXMethodDecl *MD) 8966 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} 8967 8968 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } 8969 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 8970 8971 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } 8972 void setKind(Kind K) { Pair.setInt(K); } 8973 }; 8974 8975 class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, 8976 public SpecialMemberOverloadResult { 8977 public: 8978 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) 8979 : FastFoldingSetNode(ID) {} 8980 }; 8981 8982 /// A cache of special member function overload resolution results 8983 /// for C++ records. 8984 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; 8985 8986 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by 8987 /// `TransformTypos` in order to keep track of any TypoExprs that are created 8988 /// recursively during typo correction and wipe them away if the correction 8989 /// fails. 8990 llvm::SmallVector<TypoExpr *, 2> TypoExprs; 8991 8992 enum class AcceptableKind { Visible, Reachable }; 8993 8994 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 8995 // TODO: make this is a typesafe union. 8996 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; 8997 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; 8998 8999 /// Describes the kind of name lookup to perform. 9000 enum LookupNameKind { 9001 /// Ordinary name lookup, which finds ordinary names (functions, 9002 /// variables, typedefs, etc.) in C and most kinds of names 9003 /// (functions, variables, members, types, etc.) in C++. 9004 LookupOrdinaryName = 0, 9005 /// Tag name lookup, which finds the names of enums, classes, 9006 /// structs, and unions. 9007 LookupTagName, 9008 /// Label name lookup. 9009 LookupLabel, 9010 /// Member name lookup, which finds the names of 9011 /// class/struct/union members. 9012 LookupMemberName, 9013 /// Look up of an operator name (e.g., operator+) for use with 9014 /// operator overloading. This lookup is similar to ordinary name 9015 /// lookup, but will ignore any declarations that are class members. 9016 LookupOperatorName, 9017 /// Look up a name following ~ in a destructor name. This is an ordinary 9018 /// lookup, but prefers tags to typedefs. 9019 LookupDestructorName, 9020 /// Look up of a name that precedes the '::' scope resolution 9021 /// operator in C++. This lookup completely ignores operator, object, 9022 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 9023 LookupNestedNameSpecifierName, 9024 /// Look up a namespace name within a C++ using directive or 9025 /// namespace alias definition, ignoring non-namespace names (C++ 9026 /// [basic.lookup.udir]p1). 9027 LookupNamespaceName, 9028 /// Look up all declarations in a scope with the given name, 9029 /// including resolved using declarations. This is appropriate 9030 /// for checking redeclarations for a using declaration. 9031 LookupUsingDeclName, 9032 /// Look up an ordinary name that is going to be redeclared as a 9033 /// name with linkage. This lookup ignores any declarations that 9034 /// are outside of the current scope unless they have linkage. See 9035 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 9036 LookupRedeclarationWithLinkage, 9037 /// Look up a friend of a local class. This lookup does not look 9038 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 9039 LookupLocalFriendName, 9040 /// Look up the name of an Objective-C protocol. 9041 LookupObjCProtocolName, 9042 /// Look up implicit 'self' parameter of an objective-c method. 9043 LookupObjCImplicitSelfParam, 9044 /// Look up the name of an OpenMP user-defined reduction operation. 9045 LookupOMPReductionName, 9046 /// Look up the name of an OpenMP user-defined mapper. 9047 LookupOMPMapperName, 9048 /// Look up any declaration with any name. 9049 LookupAnyName 9050 }; 9051 9052 /// The possible outcomes of name lookup for a literal operator. 9053 enum LiteralOperatorLookupResult { 9054 /// The lookup resulted in an error. 9055 LOLR_Error, 9056 /// The lookup found no match but no diagnostic was issued. 9057 LOLR_ErrorNoDiagnostic, 9058 /// The lookup found a single 'cooked' literal operator, which 9059 /// expects a normal literal to be built and passed to it. 9060 LOLR_Cooked, 9061 /// The lookup found a single 'raw' literal operator, which expects 9062 /// a string literal containing the spelling of the literal token. 9063 LOLR_Raw, 9064 /// The lookup found an overload set of literal operator templates, 9065 /// which expect the characters of the spelling of the literal token to be 9066 /// passed as a non-type template argument pack. 9067 LOLR_Template, 9068 /// The lookup found an overload set of literal operator templates, 9069 /// which expect the character type and characters of the spelling of the 9070 /// string literal token to be passed as template arguments. 9071 LOLR_StringTemplatePack, 9072 }; 9073 9074 SpecialMemberOverloadResult 9075 LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, 9076 bool VolatileArg, bool RValueThis, bool ConstThis, 9077 bool VolatileThis); 9078 9079 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 9080 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 9081 TypoRecoveryCallback; 9082 9083 RedeclarationKind forRedeclarationInCurContext() const; 9084 9085 /// Look up a name, looking for a single declaration. Return 9086 /// null if the results were absent, ambiguous, or overloaded. 9087 /// 9088 /// It is preferable to use the elaborated form and explicitly handle 9089 /// ambiguity and overloaded. 9090 NamedDecl *LookupSingleName( 9091 Scope *S, DeclarationName Name, SourceLocation Loc, 9092 LookupNameKind NameKind, 9093 RedeclarationKind Redecl = RedeclarationKind::NotForRedeclaration); 9094 9095 /// Lookup a builtin function, when name lookup would otherwise 9096 /// fail. 9097 bool LookupBuiltin(LookupResult &R); 9098 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); 9099 9100 /// Perform unqualified name lookup starting from a given 9101 /// scope. 9102 /// 9103 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 9104 /// used to find names within the current scope. For example, 'x' in 9105 /// @code 9106 /// int x; 9107 /// int f() { 9108 /// return x; // unqualified name look finds 'x' in the global scope 9109 /// } 9110 /// @endcode 9111 /// 9112 /// Different lookup criteria can find different names. For example, a 9113 /// particular scope can have both a struct and a function of the same 9114 /// name, and each can be found by certain lookup criteria. For more 9115 /// information about lookup criteria, see the documentation for the 9116 /// class LookupCriteria. 9117 /// 9118 /// @param S The scope from which unqualified name lookup will 9119 /// begin. If the lookup criteria permits, name lookup may also search 9120 /// in the parent scopes. 9121 /// 9122 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to 9123 /// look up and the lookup kind), and is updated with the results of lookup 9124 /// including zero or more declarations and possibly additional information 9125 /// used to diagnose ambiguities. 9126 /// 9127 /// @returns \c true if lookup succeeded and false otherwise. 9128 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false, 9129 bool ForceNoCPlusPlus = false); 9130 9131 /// Perform qualified name lookup into a given context. 9132 /// 9133 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 9134 /// names when the context of those names is explicit specified, e.g., 9135 /// "std::vector" or "x->member", or as part of unqualified name lookup. 9136 /// 9137 /// Different lookup criteria can find different names. For example, a 9138 /// particular scope can have both a struct and a function of the same 9139 /// name, and each can be found by certain lookup criteria. For more 9140 /// information about lookup criteria, see the documentation for the 9141 /// class LookupCriteria. 9142 /// 9143 /// \param R captures both the lookup criteria and any lookup results found. 9144 /// 9145 /// \param LookupCtx The context in which qualified name lookup will 9146 /// search. If the lookup criteria permits, name lookup may also search 9147 /// in the parent contexts or (for C++ classes) base classes. 9148 /// 9149 /// \param InUnqualifiedLookup true if this is qualified name lookup that 9150 /// occurs as part of unqualified name lookup. 9151 /// 9152 /// \returns true if lookup succeeded, false if it failed. 9153 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 9154 bool InUnqualifiedLookup = false); 9155 9156 /// Performs qualified name lookup or special type of lookup for 9157 /// "__super::" scope specifier. 9158 /// 9159 /// This routine is a convenience overload meant to be called from contexts 9160 /// that need to perform a qualified name lookup with an optional C++ scope 9161 /// specifier that might require special kind of lookup. 9162 /// 9163 /// \param R captures both the lookup criteria and any lookup results found. 9164 /// 9165 /// \param LookupCtx The context in which qualified name lookup will 9166 /// search. 9167 /// 9168 /// \param SS An optional C++ scope-specifier. 9169 /// 9170 /// \returns true if lookup succeeded, false if it failed. 9171 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 9172 CXXScopeSpec &SS); 9173 9174 /// Performs name lookup for a name that was parsed in the 9175 /// source code, and may contain a C++ scope specifier. 9176 /// 9177 /// This routine is a convenience routine meant to be called from 9178 /// contexts that receive a name and an optional C++ scope specifier 9179 /// (e.g., "N::M::x"). It will then perform either qualified or 9180 /// unqualified name lookup (with LookupQualifiedName or LookupName, 9181 /// respectively) on the given name and return those results. It will 9182 /// perform a special type of lookup for "__super::" scope specifier. 9183 /// 9184 /// @param S The scope from which unqualified name lookup will 9185 /// begin. 9186 /// 9187 /// @param SS An optional C++ scope-specifier, e.g., "::N::M". 9188 /// 9189 /// @param EnteringContext Indicates whether we are going to enter the 9190 /// context of the scope-specifier SS (if present). 9191 /// 9192 /// @returns True if any decls were found (but possibly ambiguous) 9193 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 9194 QualType ObjectType, bool AllowBuiltinCreation = false, 9195 bool EnteringContext = false); 9196 9197 /// Perform qualified name lookup into all base classes of the given 9198 /// class. 9199 /// 9200 /// \param R captures both the lookup criteria and any lookup results found. 9201 /// 9202 /// \param Class The context in which qualified name lookup will 9203 /// search. Name lookup will search in all base classes merging the results. 9204 /// 9205 /// @returns True if any decls were found (but possibly ambiguous) 9206 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 9207 9208 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 9209 UnresolvedSetImpl &Functions); 9210 9211 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. 9212 /// If GnuLabelLoc is a valid source location, then this is a definition 9213 /// of an __label__ label name, otherwise it is a normal label definition 9214 /// or use. 9215 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 9216 SourceLocation GnuLabelLoc = SourceLocation()); 9217 9218 /// Look up the constructors for the given class. 9219 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 9220 9221 /// Look up the default constructor for the given class. 9222 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 9223 9224 /// Look up the copying constructor for the given class. 9225 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 9226 unsigned Quals); 9227 9228 /// Look up the copying assignment operator for the given class. 9229 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 9230 bool RValueThis, unsigned ThisQuals); 9231 9232 /// Look up the moving constructor for the given class. 9233 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 9234 unsigned Quals); 9235 9236 /// Look up the moving assignment operator for the given class. 9237 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 9238 bool RValueThis, unsigned ThisQuals); 9239 9240 /// Look for the destructor of the given class. 9241 /// 9242 /// During semantic analysis, this routine should be used in lieu of 9243 /// CXXRecordDecl::getDestructor(). 9244 /// 9245 /// \returns The destructor for this class. 9246 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 9247 9248 /// Force the declaration of any implicitly-declared members of this 9249 /// class. 9250 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 9251 9252 /// Make a merged definition of an existing hidden definition \p ND 9253 /// visible at the specified location. 9254 void makeMergedDefinitionVisible(NamedDecl *ND); 9255 9256 /// Check ODR hashes for C/ObjC when merging types from modules. 9257 /// Differently from C++, actually parse the body and reject in case 9258 /// of a mismatch. 9259 template <typename T, 9260 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>> 9261 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) { 9262 if (Duplicate->getODRHash() != Previous->getODRHash()) 9263 return false; 9264 9265 // Make the previous decl visible. 9266 makeMergedDefinitionVisible(Previous); 9267 return true; 9268 } 9269 9270 /// Get the set of additional modules that should be checked during 9271 /// name lookup. A module and its imports become visible when instanting a 9272 /// template defined within it. 9273 llvm::DenseSet<Module *> &getLookupModules(); 9274 9275 bool hasVisibleMergedDefinition(const NamedDecl *Def); 9276 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def); 9277 9278 /// Determine if the template parameter \p D has a visible default argument. 9279 bool 9280 hasVisibleDefaultArgument(const NamedDecl *D, 9281 llvm::SmallVectorImpl<Module *> *Modules = nullptr); 9282 /// Determine if the template parameter \p D has a reachable default argument. 9283 bool hasReachableDefaultArgument( 9284 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 9285 /// Determine if the template parameter \p D has a reachable default argument. 9286 bool hasAcceptableDefaultArgument(const NamedDecl *D, 9287 llvm::SmallVectorImpl<Module *> *Modules, 9288 Sema::AcceptableKind Kind); 9289 9290 /// Determine if there is a visible declaration of \p D that is an explicit 9291 /// specialization declaration for a specialization of a template. (For a 9292 /// member specialization, use hasVisibleMemberSpecialization.) 9293 bool hasVisibleExplicitSpecialization( 9294 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 9295 /// Determine if there is a reachable declaration of \p D that is an explicit 9296 /// specialization declaration for a specialization of a template. (For a 9297 /// member specialization, use hasReachableMemberSpecialization.) 9298 bool hasReachableExplicitSpecialization( 9299 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 9300 9301 /// Determine if there is a visible declaration of \p D that is a member 9302 /// specialization declaration (as opposed to an instantiated declaration). 9303 bool hasVisibleMemberSpecialization( 9304 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 9305 /// Determine if there is a reachable declaration of \p D that is a member 9306 /// specialization declaration (as opposed to an instantiated declaration). 9307 bool hasReachableMemberSpecialization( 9308 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 9309 9310 bool isModuleVisible(const Module *M, bool ModulePrivate = false); 9311 9312 /// Determine whether any declaration of an entity is visible. 9313 bool 9314 hasVisibleDeclaration(const NamedDecl *D, 9315 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 9316 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); 9317 } 9318 9319 bool hasVisibleDeclarationSlow(const NamedDecl *D, 9320 llvm::SmallVectorImpl<Module *> *Modules); 9321 /// Determine whether any declaration of an entity is reachable. 9322 bool 9323 hasReachableDeclaration(const NamedDecl *D, 9324 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 9325 return isReachable(D) || hasReachableDeclarationSlow(D, Modules); 9326 } 9327 bool hasReachableDeclarationSlow( 9328 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 9329 9330 void diagnoseTypo(const TypoCorrection &Correction, 9331 const PartialDiagnostic &TypoDiag, 9332 bool ErrorRecovery = true); 9333 9334 /// Diagnose a successfully-corrected typo. Separated from the correction 9335 /// itself to allow external validation of the result, etc. 9336 /// 9337 /// \param Correction The result of performing typo correction. 9338 /// \param TypoDiag The diagnostic to produce. This will have the corrected 9339 /// string added to it (and usually also a fixit). 9340 /// \param PrevNote A note to use when indicating the location of the entity 9341 /// to which we are correcting. Will have the correction string added 9342 /// to it. 9343 /// \param ErrorRecovery If \c true (the default), the caller is going to 9344 /// recover from the typo as if the corrected string had been typed. 9345 /// In this case, \c PDiag must be an error, and we will attach a fixit 9346 /// to it. 9347 void diagnoseTypo(const TypoCorrection &Correction, 9348 const PartialDiagnostic &TypoDiag, 9349 const PartialDiagnostic &PrevNote, 9350 bool ErrorRecovery = true); 9351 9352 /// Find the associated classes and namespaces for 9353 /// argument-dependent lookup for a call with the given set of 9354 /// arguments. 9355 /// 9356 /// This routine computes the sets of associated classes and associated 9357 /// namespaces searched by argument-dependent lookup 9358 /// (C++ [basic.lookup.argdep]) for a given set of arguments. 9359 void FindAssociatedClassesAndNamespaces( 9360 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, 9361 AssociatedNamespaceSet &AssociatedNamespaces, 9362 AssociatedClassSet &AssociatedClasses); 9363 9364 /// Produce a diagnostic describing the ambiguity that resulted 9365 /// from name lookup. 9366 /// 9367 /// \param Result The result of the ambiguous lookup to be diagnosed. 9368 void DiagnoseAmbiguousLookup(LookupResult &Result); 9369 9370 /// LookupLiteralOperator - Determine which literal operator should be used 9371 /// for a user-defined literal, per C++11 [lex.ext]. 9372 /// 9373 /// Normal overload resolution is not used to select which literal operator to 9374 /// call for a user-defined literal. Look up the provided literal operator 9375 /// name, and filter the results to the appropriate set for the given argument 9376 /// types. 9377 LiteralOperatorLookupResult 9378 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, 9379 bool AllowRaw, bool AllowTemplate, 9380 bool AllowStringTemplate, bool DiagnoseMissing, 9381 StringLiteral *StringLit = nullptr); 9382 9383 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 9384 ArrayRef<Expr *> Args, ADLResult &Functions); 9385 9386 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 9387 VisibleDeclConsumer &Consumer, 9388 bool IncludeGlobalScope = true, 9389 bool LoadExternal = true); 9390 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 9391 VisibleDeclConsumer &Consumer, 9392 bool IncludeGlobalScope = true, 9393 bool IncludeDependentBases = false, 9394 bool LoadExternal = true); 9395 9396 enum CorrectTypoKind { 9397 CTK_NonError, // CorrectTypo used in a non error recovery situation. 9398 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 9399 }; 9400 9401 /// Try to "correct" a typo in the source code by finding 9402 /// visible declarations whose names are similar to the name that was 9403 /// present in the source code. 9404 /// 9405 /// \param TypoName the \c DeclarationNameInfo structure that contains 9406 /// the name that was present in the source code along with its location. 9407 /// 9408 /// \param LookupKind the name-lookup criteria used to search for the name. 9409 /// 9410 /// \param S the scope in which name lookup occurs. 9411 /// 9412 /// \param SS the nested-name-specifier that precedes the name we're 9413 /// looking for, if present. 9414 /// 9415 /// \param CCC A CorrectionCandidateCallback object that provides further 9416 /// validation of typo correction candidates. It also provides flags for 9417 /// determining the set of keywords permitted. 9418 /// 9419 /// \param MemberContext if non-NULL, the context in which to look for 9420 /// a member access expression. 9421 /// 9422 /// \param EnteringContext whether we're entering the context described by 9423 /// the nested-name-specifier SS. 9424 /// 9425 /// \param OPT when non-NULL, the search for visible declarations will 9426 /// also walk the protocols in the qualified interfaces of \p OPT. 9427 /// 9428 /// \returns a \c TypoCorrection containing the corrected name if the typo 9429 /// along with information such as the \c NamedDecl where the corrected name 9430 /// was declared, and any additional \c NestedNameSpecifier needed to access 9431 /// it (C++ only). The \c TypoCorrection is empty if there is no correction. 9432 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 9433 Sema::LookupNameKind LookupKind, Scope *S, 9434 CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, 9435 CorrectTypoKind Mode, 9436 DeclContext *MemberContext = nullptr, 9437 bool EnteringContext = false, 9438 const ObjCObjectPointerType *OPT = nullptr, 9439 bool RecordFailure = true); 9440 9441 /// Try to "correct" a typo in the source code by finding 9442 /// visible declarations whose names are similar to the name that was 9443 /// present in the source code. 9444 /// 9445 /// \param TypoName the \c DeclarationNameInfo structure that contains 9446 /// the name that was present in the source code along with its location. 9447 /// 9448 /// \param LookupKind the name-lookup criteria used to search for the name. 9449 /// 9450 /// \param S the scope in which name lookup occurs. 9451 /// 9452 /// \param SS the nested-name-specifier that precedes the name we're 9453 /// looking for, if present. 9454 /// 9455 /// \param CCC A CorrectionCandidateCallback object that provides further 9456 /// validation of typo correction candidates. It also provides flags for 9457 /// determining the set of keywords permitted. 9458 /// 9459 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print 9460 /// diagnostics when the actual typo correction is attempted. 9461 /// 9462 /// \param TRC A TypoRecoveryCallback functor that will be used to build an 9463 /// Expr from a typo correction candidate. 9464 /// 9465 /// \param MemberContext if non-NULL, the context in which to look for 9466 /// a member access expression. 9467 /// 9468 /// \param EnteringContext whether we're entering the context described by 9469 /// the nested-name-specifier SS. 9470 /// 9471 /// \param OPT when non-NULL, the search for visible declarations will 9472 /// also walk the protocols in the qualified interfaces of \p OPT. 9473 /// 9474 /// \returns a new \c TypoExpr that will later be replaced in the AST with an 9475 /// Expr representing the result of performing typo correction, or nullptr if 9476 /// typo correction is not possible. If nullptr is returned, no diagnostics 9477 /// will be emitted and it is the responsibility of the caller to emit any 9478 /// that are needed. 9479 TypoExpr *CorrectTypoDelayed( 9480 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, 9481 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, 9482 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, 9483 CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, 9484 bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); 9485 9486 /// Kinds of missing import. Note, the values of these enumerators correspond 9487 /// to %select values in diagnostics. 9488 enum class MissingImportKind { 9489 Declaration, 9490 Definition, 9491 DefaultArgument, 9492 ExplicitSpecialization, 9493 PartialSpecialization 9494 }; 9495 9496 /// Diagnose that the specified declaration needs to be visible but 9497 /// isn't, and suggest a module import that would resolve the problem. 9498 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, 9499 MissingImportKind MIK, bool Recover = true); 9500 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, 9501 SourceLocation DeclLoc, ArrayRef<Module *> Modules, 9502 MissingImportKind MIK, bool Recover); 9503 9504 struct TypoExprState { 9505 std::unique_ptr<TypoCorrectionConsumer> Consumer; 9506 TypoDiagnosticGenerator DiagHandler; 9507 TypoRecoveryCallback RecoveryHandler; 9508 TypoExprState(); 9509 TypoExprState(TypoExprState &&other) noexcept; 9510 TypoExprState &operator=(TypoExprState &&other) noexcept; 9511 }; 9512 9513 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 9514 9515 /// Clears the state of the given TypoExpr. 9516 void clearDelayedTypo(TypoExpr *TE); 9517 9518 /// Called on #pragma clang __debug dump II 9519 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); 9520 9521 /// Called on #pragma clang __debug dump E 9522 void ActOnPragmaDump(Expr *E); 9523 9524 private: 9525 // The set of known/encountered (unique, canonicalized) NamespaceDecls. 9526 // 9527 // The boolean value will be true to indicate that the namespace was loaded 9528 // from an AST/PCH file, or false otherwise. 9529 llvm::MapVector<NamespaceDecl *, bool> KnownNamespaces; 9530 9531 /// Whether we have already loaded known namespaces from an extenal 9532 /// source. 9533 bool LoadedExternalKnownNamespaces; 9534 9535 bool CppLookupName(LookupResult &R, Scope *S); 9536 9537 /// Determine if we could use all the declarations in the module. 9538 bool isUsableModule(const Module *M); 9539 9540 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and 9541 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 9542 /// should be skipped entirely. 9543 std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer( 9544 const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, 9545 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, 9546 DeclContext *MemberContext, bool EnteringContext, 9547 const ObjCObjectPointerType *OPT, bool ErrorRecovery); 9548 9549 /// The set of unhandled TypoExprs and their associated state. 9550 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 9551 9552 /// Creates a new TypoExpr AST node. 9553 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 9554 TypoDiagnosticGenerator TDG, 9555 TypoRecoveryCallback TRC, SourceLocation TypoLoc); 9556 9557 /// Cache for module units which is usable for current module. 9558 llvm::DenseSet<const Module *> UsableModuleUnitsCache; 9559 9560 /// Record the typo correction failure and return an empty correction. 9561 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 9562 bool RecordFailure = true) { 9563 if (RecordFailure) 9564 TypoCorrectionFailures[Typo].insert(TypoLoc); 9565 return TypoCorrection(); 9566 } 9567 9568 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind); 9569 9570 /// Determine whether two declarations should be linked together, given that 9571 /// the old declaration might not be visible and the new declaration might 9572 /// not have external linkage. 9573 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, 9574 const NamedDecl *New) { 9575 if (isVisible(Old)) 9576 return true; 9577 // See comment in below overload for why it's safe to compute the linkage 9578 // of the new declaration here. 9579 if (New->isExternallyDeclarable()) { 9580 assert(Old->isExternallyDeclarable() && 9581 "should not have found a non-externally-declarable previous decl"); 9582 return true; 9583 } 9584 return false; 9585 } 9586 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); 9587 9588 ///@} 9589 9590 // 9591 // 9592 // ------------------------------------------------------------------------- 9593 // 9594 // 9595 9596 /// \name Modules 9597 /// Implementations are in SemaModule.cpp 9598 ///@{ 9599 9600 public: 9601 /// Get the module unit whose scope we are currently within. 9602 Module *getCurrentModule() const { 9603 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; 9604 } 9605 9606 /// Is the module scope we are an implementation unit? 9607 bool currentModuleIsImplementation() const { 9608 return ModuleScopes.empty() 9609 ? false 9610 : ModuleScopes.back().Module->isModuleImplementation(); 9611 } 9612 9613 // When loading a non-modular PCH files, this is used to restore module 9614 // visibility. 9615 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { 9616 VisibleModules.setVisible(Mod, ImportLoc); 9617 } 9618 9619 enum class ModuleDeclKind { 9620 Interface, ///< 'export module X;' 9621 Implementation, ///< 'module X;' 9622 PartitionInterface, ///< 'export module X:Y;' 9623 PartitionImplementation, ///< 'module X:Y;' 9624 }; 9625 9626 /// An enumeration to represent the transition of states in parsing module 9627 /// fragments and imports. If we are not parsing a C++20 TU, or we find 9628 /// an error in state transition, the state is set to NotACXX20Module. 9629 enum class ModuleImportState { 9630 FirstDecl, ///< Parsing the first decl in a TU. 9631 GlobalFragment, ///< after 'module;' but before 'module X;' 9632 ImportAllowed, ///< after 'module X;' but before any non-import decl. 9633 ImportFinished, ///< after any non-import decl. 9634 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any 9635 ///< non-import decl. 9636 PrivateFragmentImportFinished, ///< after 'module :private;' but a 9637 ///< non-import decl has already been seen. 9638 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found. 9639 }; 9640 9641 /// The parser has processed a module-declaration that begins the definition 9642 /// of a module interface or implementation. 9643 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, 9644 SourceLocation ModuleLoc, ModuleDeclKind MDK, 9645 ModuleIdPath Path, ModuleIdPath Partition, 9646 ModuleImportState &ImportState); 9647 9648 /// The parser has processed a global-module-fragment declaration that begins 9649 /// the definition of the global module fragment of the current module unit. 9650 /// \param ModuleLoc The location of the 'module' keyword. 9651 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); 9652 9653 /// The parser has processed a private-module-fragment declaration that begins 9654 /// the definition of the private module fragment of the current module unit. 9655 /// \param ModuleLoc The location of the 'module' keyword. 9656 /// \param PrivateLoc The location of the 'private' keyword. 9657 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, 9658 SourceLocation PrivateLoc); 9659 9660 /// The parser has processed a module import declaration. 9661 /// 9662 /// \param StartLoc The location of the first token in the declaration. This 9663 /// could be the location of an '@', 'export', or 'import'. 9664 /// \param ExportLoc The location of the 'export' keyword, if any. 9665 /// \param ImportLoc The location of the 'import' keyword. 9666 /// \param Path The module toplevel name as an access path. 9667 /// \param IsPartition If the name is for a partition. 9668 DeclResult ActOnModuleImport(SourceLocation StartLoc, 9669 SourceLocation ExportLoc, 9670 SourceLocation ImportLoc, ModuleIdPath Path, 9671 bool IsPartition = false); 9672 DeclResult ActOnModuleImport(SourceLocation StartLoc, 9673 SourceLocation ExportLoc, 9674 SourceLocation ImportLoc, Module *M, 9675 ModuleIdPath Path = {}); 9676 9677 /// The parser has processed a module import translated from a 9678 /// #include or similar preprocessing directive. 9679 void ActOnAnnotModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 9680 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 9681 9682 /// The parsed has entered a submodule. 9683 void ActOnAnnotModuleBegin(SourceLocation DirectiveLoc, Module *Mod); 9684 /// The parser has left a submodule. 9685 void ActOnAnnotModuleEnd(SourceLocation DirectiveLoc, Module *Mod); 9686 9687 /// Create an implicit import of the given module at the given 9688 /// source location, for error recovery, if possible. 9689 /// 9690 /// This routine is typically used when an entity found by name lookup 9691 /// is actually hidden within a module that we know about but the user 9692 /// has forgotten to import. 9693 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 9694 Module *Mod); 9695 9696 /// We have parsed the start of an export declaration, including the '{' 9697 /// (if present). 9698 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 9699 SourceLocation LBraceLoc); 9700 9701 /// Complete the definition of an export declaration. 9702 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, 9703 SourceLocation RBraceLoc); 9704 9705 private: 9706 /// The parser has begun a translation unit to be compiled as a C++20 9707 /// Header Unit, helper for ActOnStartOfTranslationUnit() only. 9708 void HandleStartOfHeaderUnit(); 9709 9710 struct ModuleScope { 9711 SourceLocation BeginLoc; 9712 clang::Module *Module = nullptr; 9713 VisibleModuleSet OuterVisibleModules; 9714 }; 9715 /// The modules we're currently parsing. 9716 llvm::SmallVector<ModuleScope, 16> ModuleScopes; 9717 9718 /// For an interface unit, this is the implicitly imported interface unit. 9719 clang::Module *ThePrimaryInterface = nullptr; 9720 9721 /// The explicit global module fragment of the current translation unit. 9722 /// The explicit Global Module Fragment, as specified in C++ 9723 /// [module.global.frag]. 9724 clang::Module *TheGlobalModuleFragment = nullptr; 9725 9726 /// The implicit global module fragments of the current translation unit. 9727 /// 9728 /// The contents in the implicit global module fragment can't be discarded. 9729 clang::Module *TheImplicitGlobalModuleFragment = nullptr; 9730 9731 /// Namespace definitions that we will export when they finish. 9732 llvm::SmallPtrSet<const NamespaceDecl *, 8> DeferredExportedNamespaces; 9733 9734 /// In a C++ standard module, inline declarations require a definition to be 9735 /// present at the end of a definition domain. This set holds the decls to 9736 /// be checked at the end of the TU. 9737 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls; 9738 9739 /// Helper function to judge if we are in module purview. 9740 /// Return false if we are not in a module. 9741 bool isCurrentModulePurview() const; 9742 9743 /// Enter the scope of the explicit global module fragment. 9744 Module *PushGlobalModuleFragment(SourceLocation BeginLoc); 9745 /// Leave the scope of the explicit global module fragment. 9746 void PopGlobalModuleFragment(); 9747 9748 /// Enter the scope of an implicit global module fragment. 9749 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc); 9750 /// Leave the scope of an implicit global module fragment. 9751 void PopImplicitGlobalModuleFragment(); 9752 9753 VisibleModuleSet VisibleModules; 9754 9755 ///@} 9756 9757 // 9758 // 9759 // ------------------------------------------------------------------------- 9760 // 9761 // 9762 9763 /// \name C++ Overloading 9764 /// Implementations are in SemaOverload.cpp 9765 ///@{ 9766 9767 public: 9768 /// Whether deferrable diagnostics should be deferred. 9769 bool DeferDiags = false; 9770 9771 /// RAII class to control scope of DeferDiags. 9772 class DeferDiagsRAII { 9773 Sema &S; 9774 bool SavedDeferDiags = false; 9775 9776 public: 9777 DeferDiagsRAII(Sema &S, bool DeferDiags) 9778 : S(S), SavedDeferDiags(S.DeferDiags) { 9779 S.DeferDiags = DeferDiags; 9780 } 9781 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } 9782 }; 9783 9784 /// Flag indicating if Sema is building a recovery call expression. 9785 /// 9786 /// This flag is used to avoid building recovery call expressions 9787 /// if Sema is already doing so, which would cause infinite recursions. 9788 bool IsBuildingRecoveryCallExpr; 9789 9790 enum OverloadKind { 9791 /// This is a legitimate overload: the existing declarations are 9792 /// functions or function templates with different signatures. 9793 Ovl_Overload, 9794 9795 /// This is not an overload because the signature exactly matches 9796 /// an existing declaration. 9797 Ovl_Match, 9798 9799 /// This is not an overload because the lookup results contain a 9800 /// non-function. 9801 Ovl_NonFunction 9802 }; 9803 9804 /// Determine whether the given New declaration is an overload of the 9805 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 9806 /// New and Old cannot be overloaded, e.g., if New has the same signature as 9807 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 9808 /// functions (or function templates) at all. When it does return Ovl_Match or 9809 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 9810 /// overloaded with. This decl may be a UsingShadowDecl on top of the 9811 /// underlying declaration. 9812 /// 9813 /// Example: Given the following input: 9814 /// 9815 /// void f(int, float); // #1 9816 /// void f(int, int); // #2 9817 /// int f(int, int); // #3 9818 /// 9819 /// When we process #1, there is no previous declaration of "f", so IsOverload 9820 /// will not be used. 9821 /// 9822 /// When we process #2, Old contains only the FunctionDecl for #1. By 9823 /// comparing the parameter types, we see that #1 and #2 are overloaded (since 9824 /// they have different signatures), so this routine returns Ovl_Overload; 9825 /// MatchedDecl is unchanged. 9826 /// 9827 /// When we process #3, Old is an overload set containing #1 and #2. We 9828 /// compare the signatures of #3 to #1 (they're overloaded, so we do nothing) 9829 /// and then #3 to #2. Since the signatures of #3 and #2 are identical (return 9830 /// types of functions are not part of the signature), IsOverload returns 9831 /// Ovl_Match and MatchedDecl will be set to point to the FunctionDecl for #2. 9832 /// 9833 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a 9834 /// class by a using declaration. The rules for whether to hide shadow 9835 /// declarations ignore some properties which otherwise figure into a function 9836 /// template's signature. 9837 OverloadKind CheckOverload(Scope *S, FunctionDecl *New, 9838 const LookupResult &OldDecls, NamedDecl *&OldDecl, 9839 bool UseMemberUsingDeclRules); 9840 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, 9841 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true); 9842 9843 // Checks whether MD constitutes an override the base class method BaseMD. 9844 // When checking for overrides, the object object members are ignored. 9845 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, 9846 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true); 9847 9848 enum class AllowedExplicit { 9849 /// Allow no explicit functions to be used. 9850 None, 9851 /// Allow explicit conversion functions but not explicit constructors. 9852 Conversions, 9853 /// Allow both explicit conversion functions and explicit constructors. 9854 All 9855 }; 9856 9857 ImplicitConversionSequence TryImplicitConversion( 9858 Expr *From, QualType ToType, bool SuppressUserConversions, 9859 AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, 9860 bool AllowObjCWritebackConversion); 9861 9862 /// PerformImplicitConversion - Perform an implicit conversion of the 9863 /// expression From to the type ToType. Returns the 9864 /// converted expression. Flavor is the kind of conversion we're 9865 /// performing, used in the error message. If @p AllowExplicit, 9866 /// explicit user-defined conversions are permitted. 9867 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 9868 AssignmentAction Action, 9869 bool AllowExplicit = false); 9870 9871 /// IsIntegralPromotion - Determines whether the conversion from the 9872 /// expression From (whose potentially-adjusted type is FromType) to 9873 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 9874 /// sets PromotedType to the promoted type. 9875 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 9876 9877 /// IsFloatingPointPromotion - Determines whether the conversion from 9878 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 9879 /// returns true and sets PromotedType to the promoted type. 9880 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 9881 9882 /// Determine if a conversion is a complex promotion. 9883 /// 9884 /// A complex promotion is defined as a complex -> complex conversion 9885 /// where the conversion between the underlying real types is a 9886 /// floating-point or integral promotion. 9887 bool IsComplexPromotion(QualType FromType, QualType ToType); 9888 9889 /// IsPointerConversion - Determines whether the conversion of the 9890 /// expression From, which has the (possibly adjusted) type FromType, 9891 /// can be converted to the type ToType via a pointer conversion (C++ 9892 /// 4.10). If so, returns true and places the converted type (that 9893 /// might differ from ToType in its cv-qualifiers at some level) into 9894 /// ConvertedType. 9895 /// 9896 /// This routine also supports conversions to and from block pointers 9897 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 9898 /// pointers to interfaces. FIXME: Once we've determined the 9899 /// appropriate overloading rules for Objective-C, we may want to 9900 /// split the Objective-C checks into a different routine; however, 9901 /// GCC seems to consider all of these conversions to be pointer 9902 /// conversions, so for now they live here. IncompatibleObjC will be 9903 /// set if the conversion is an allowed Objective-C conversion that 9904 /// should result in a warning. 9905 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 9906 bool InOverloadResolution, QualType &ConvertedType, 9907 bool &IncompatibleObjC); 9908 9909 /// isObjCPointerConversion - Determines whether this is an 9910 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 9911 /// with the same arguments and return values. 9912 bool isObjCPointerConversion(QualType FromType, QualType ToType, 9913 QualType &ConvertedType, bool &IncompatibleObjC); 9914 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 9915 QualType &ConvertedType); 9916 9917 /// FunctionParamTypesAreEqual - This routine checks two function proto types 9918 /// for equality of their parameter types. Caller has already checked that 9919 /// they have same number of parameters. If the parameters are different, 9920 /// ArgPos will have the parameter index of the first different parameter. 9921 /// If `Reversed` is true, the parameters of `NewType` will be compared in 9922 /// reverse order. That's useful if one of the functions is being used as a 9923 /// C++20 synthesized operator overload with a reversed parameter order. 9924 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old, 9925 ArrayRef<QualType> New, 9926 unsigned *ArgPos = nullptr, 9927 bool Reversed = false); 9928 9929 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 9930 const FunctionProtoType *NewType, 9931 unsigned *ArgPos = nullptr, 9932 bool Reversed = false); 9933 9934 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, 9935 const FunctionDecl *NewFunction, 9936 unsigned *ArgPos = nullptr, 9937 bool Reversed = false); 9938 9939 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 9940 /// function types. Catches different number of parameter, mismatch in 9941 /// parameter types, and different return types. 9942 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, 9943 QualType ToType); 9944 9945 /// CheckPointerConversion - Check the pointer conversion from the 9946 /// expression From to the type ToType. This routine checks for 9947 /// ambiguous or inaccessible derived-to-base pointer 9948 /// conversions for which IsPointerConversion has already returned 9949 /// true. It returns true and produces a diagnostic if there was an 9950 /// error, or returns false otherwise. 9951 bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, 9952 CXXCastPath &BasePath, bool IgnoreBaseAccess, 9953 bool Diagnose = true); 9954 9955 /// IsMemberPointerConversion - Determines whether the conversion of the 9956 /// expression From, which has the (possibly adjusted) type FromType, can be 9957 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 9958 /// If so, returns true and places the converted type (that might differ from 9959 /// ToType in its cv-qualifiers at some level) into ConvertedType. 9960 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 9961 bool InOverloadResolution, 9962 QualType &ConvertedType); 9963 9964 /// CheckMemberPointerConversion - Check the member pointer conversion from 9965 /// the expression From to the type ToType. This routine checks for ambiguous 9966 /// or virtual or inaccessible base-to-derived member pointer conversions for 9967 /// which IsMemberPointerConversion has already returned true. It returns true 9968 /// and produces a diagnostic if there was an error, or returns false 9969 /// otherwise. 9970 bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, 9971 CXXCastPath &BasePath, 9972 bool IgnoreBaseAccess); 9973 9974 /// IsQualificationConversion - Determines whether the conversion from 9975 /// an rvalue of type FromType to ToType is a qualification conversion 9976 /// (C++ 4.4). 9977 /// 9978 /// \param ObjCLifetimeConversion Output parameter that will be set to 9979 /// indicate when the qualification conversion involves a change in the 9980 /// Objective-C object lifetime. 9981 bool IsQualificationConversion(QualType FromType, QualType ToType, 9982 bool CStyle, bool &ObjCLifetimeConversion); 9983 9984 /// Determine whether the conversion from FromType to ToType is a valid 9985 /// conversion that strips "noexcept" or "noreturn" off the nested function 9986 /// type. 9987 bool IsFunctionConversion(QualType FromType, QualType ToType, 9988 QualType &ResultTy); 9989 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 9990 void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, 9991 DeclarationName Name, 9992 OverloadCandidateSet &CandidateSet, 9993 FunctionDecl *Fn, MultiExprArg Args, 9994 bool IsMember = false); 9995 9996 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, 9997 FunctionDecl *Fun); 9998 ExprResult PerformImplicitObjectArgumentInitialization( 9999 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, 10000 CXXMethodDecl *Method); 10001 10002 /// PerformContextuallyConvertToBool - Perform a contextual conversion 10003 /// of the expression From to bool (C++0x [conv]p3). 10004 ExprResult PerformContextuallyConvertToBool(Expr *From); 10005 10006 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 10007 /// conversion of the expression From to an Objective-C pointer type. 10008 /// Returns a valid but null ExprResult if no conversion sequence exists. 10009 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 10010 10011 /// Contexts in which a converted constant expression is required. 10012 enum CCEKind { 10013 CCEK_CaseValue, ///< Expression in a case label. 10014 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 10015 CCEK_TemplateArg, ///< Value of a non-type template parameter. 10016 CCEK_InjectedTTP, ///< Injected parameter of a template template parameter. 10017 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. 10018 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier. 10019 CCEK_Noexcept, ///< Condition in a noexcept(bool) specifier. 10020 CCEK_StaticAssertMessageSize, ///< Call to size() in a static assert 10021 ///< message. 10022 CCEK_StaticAssertMessageData, ///< Call to data() in a static assert 10023 ///< message. 10024 }; 10025 10026 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, 10027 CCEKind CCE, 10028 NamedDecl *Dest = nullptr); 10029 10030 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 10031 llvm::APSInt &Value, CCEKind CCE); 10032 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 10033 APValue &Value, CCEKind CCE, 10034 NamedDecl *Dest = nullptr); 10035 10036 /// EvaluateConvertedConstantExpression - Evaluate an Expression 10037 /// That is a converted constant expression 10038 /// (which was built with BuildConvertedConstantExpression) 10039 ExprResult 10040 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, 10041 CCEKind CCE, bool RequireInt, 10042 const APValue &PreNarrowingValue); 10043 10044 /// Abstract base class used to perform a contextual implicit 10045 /// conversion from an expression to any type passing a filter. 10046 class ContextualImplicitConverter { 10047 public: 10048 bool Suppress; 10049 bool SuppressConversion; 10050 10051 ContextualImplicitConverter(bool Suppress = false, 10052 bool SuppressConversion = false) 10053 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 10054 10055 /// Determine whether the specified type is a valid destination type 10056 /// for this conversion. 10057 virtual bool match(QualType T) = 0; 10058 10059 /// Emits a diagnostic complaining that the expression does not have 10060 /// integral or enumeration type. 10061 virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 10062 QualType T) = 0; 10063 10064 /// Emits a diagnostic when the expression has incomplete class type. 10065 virtual SemaDiagnosticBuilder 10066 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 10067 10068 /// Emits a diagnostic when the only matching conversion function 10069 /// is explicit. 10070 virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, 10071 SourceLocation Loc, 10072 QualType T, 10073 QualType ConvTy) = 0; 10074 10075 /// Emits a note for the explicit conversion function. 10076 virtual SemaDiagnosticBuilder 10077 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 10078 10079 /// Emits a diagnostic when there are multiple possible conversion 10080 /// functions. 10081 virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10082 QualType T) = 0; 10083 10084 /// Emits a note for one of the candidate conversions. 10085 virtual SemaDiagnosticBuilder 10086 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 10087 10088 /// Emits a diagnostic when we picked a conversion function 10089 /// (for cases when we are not allowed to pick a conversion function). 10090 virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, 10091 SourceLocation Loc, 10092 QualType T, 10093 QualType ConvTy) = 0; 10094 10095 virtual ~ContextualImplicitConverter() {} 10096 }; 10097 10098 class ICEConvertDiagnoser : public ContextualImplicitConverter { 10099 bool AllowScopedEnumerations; 10100 10101 public: 10102 ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, 10103 bool SuppressConversion) 10104 : ContextualImplicitConverter(Suppress, SuppressConversion), 10105 AllowScopedEnumerations(AllowScopedEnumerations) {} 10106 10107 /// Match an integral or (possibly scoped) enumeration type. 10108 bool match(QualType T) override; 10109 10110 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 10111 QualType T) override { 10112 return diagnoseNotInt(S, Loc, T); 10113 } 10114 10115 /// Emits a diagnostic complaining that the expression does not have 10116 /// integral or enumeration type. 10117 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10118 QualType T) = 0; 10119 }; 10120 10121 /// Perform a contextual implicit conversion. 10122 ExprResult 10123 PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, 10124 ContextualImplicitConverter &Converter); 10125 10126 /// ReferenceCompareResult - Expresses the result of comparing two 10127 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 10128 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 10129 enum ReferenceCompareResult { 10130 /// Ref_Incompatible - The two types are incompatible, so direct 10131 /// reference binding is not possible. 10132 Ref_Incompatible = 0, 10133 /// Ref_Related - The two types are reference-related, which means 10134 /// that their unqualified forms (T1 and T2) are either the same 10135 /// or T1 is a base class of T2. 10136 Ref_Related, 10137 /// Ref_Compatible - The two types are reference-compatible. 10138 Ref_Compatible 10139 }; 10140 10141 // Fake up a scoped enumeration that still contextually converts to bool. 10142 struct ReferenceConversionsScope { 10143 /// The conversions that would be performed on an lvalue of type T2 when 10144 /// binding a reference of type T1 to it, as determined when evaluating 10145 /// whether T1 is reference-compatible with T2. 10146 enum ReferenceConversions { 10147 Qualification = 0x1, 10148 NestedQualification = 0x2, 10149 Function = 0x4, 10150 DerivedToBase = 0x8, 10151 ObjC = 0x10, 10152 ObjCLifetime = 0x20, 10153 10154 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) 10155 }; 10156 }; 10157 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; 10158 10159 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 10160 /// determine whether they are reference-compatible, 10161 /// reference-related, or incompatible, for use in C++ initialization by 10162 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 10163 /// type, and the first type (T1) is the pointee type of the reference 10164 /// type being initialized. 10165 ReferenceCompareResult 10166 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, 10167 ReferenceConversions *Conv = nullptr); 10168 10169 /// AddOverloadCandidate - Adds the given function to the set of 10170 /// candidate functions, using the given function call arguments. If 10171 /// @p SuppressUserConversions, then don't allow user-defined 10172 /// conversions via constructors or conversion operators. 10173 /// 10174 /// \param PartialOverloading true if we are performing "partial" overloading 10175 /// based on an incomplete set of function arguments. This feature is used by 10176 /// code completion. 10177 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, 10178 ArrayRef<Expr *> Args, 10179 OverloadCandidateSet &CandidateSet, 10180 bool SuppressUserConversions = false, 10181 bool PartialOverloading = false, 10182 bool AllowExplicit = true, 10183 bool AllowExplicitConversion = false, 10184 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 10185 ConversionSequenceList EarlyConversions = {}, 10186 OverloadCandidateParamOrder PO = {}, 10187 bool AggregateCandidateDeduction = false, 10188 bool HasMatchedPackOnParmToNonPackOnArg = false); 10189 10190 /// Add all of the function declarations in the given function set to 10191 /// the overload candidate set. 10192 void AddFunctionCandidates( 10193 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, 10194 OverloadCandidateSet &CandidateSet, 10195 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 10196 bool SuppressUserConversions = false, bool PartialOverloading = false, 10197 bool FirstArgumentIsBase = false); 10198 10199 /// AddMethodCandidate - Adds a named decl (which is some kind of 10200 /// method) as a method candidate to the given overload set. 10201 void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, 10202 Expr::Classification ObjectClassification, 10203 ArrayRef<Expr *> Args, 10204 OverloadCandidateSet &CandidateSet, 10205 bool SuppressUserConversion = false, 10206 OverloadCandidateParamOrder PO = {}); 10207 10208 /// AddMethodCandidate - Adds the given C++ member function to the set 10209 /// of candidate functions, using the given function call arguments 10210 /// and the object argument (@c Object). For example, in a call 10211 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 10212 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 10213 /// allow user-defined conversions via constructors or conversion 10214 /// operators. 10215 void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 10216 CXXRecordDecl *ActingContext, QualType ObjectType, 10217 Expr::Classification ObjectClassification, 10218 ArrayRef<Expr *> Args, 10219 OverloadCandidateSet &CandidateSet, 10220 bool SuppressUserConversions = false, 10221 bool PartialOverloading = false, 10222 ConversionSequenceList EarlyConversions = {}, 10223 OverloadCandidateParamOrder PO = {}, 10224 bool HasMatchedPackOnParmToNonPackOnArg = false); 10225 10226 /// Add a C++ member function template as a candidate to the candidate 10227 /// set, using template argument deduction to produce an appropriate member 10228 /// function template specialization. 10229 void AddMethodTemplateCandidate( 10230 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, 10231 CXXRecordDecl *ActingContext, 10232 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, 10233 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, 10234 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 10235 bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); 10236 10237 /// Add a C++ function template specialization as a candidate 10238 /// in the candidate set, using template argument deduction to produce 10239 /// an appropriate function template specialization. 10240 void AddTemplateOverloadCandidate( 10241 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 10242 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 10243 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 10244 bool PartialOverloading = false, bool AllowExplicit = true, 10245 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 10246 OverloadCandidateParamOrder PO = {}, 10247 bool AggregateCandidateDeduction = false); 10248 10249 /// Check that implicit conversion sequences can be formed for each argument 10250 /// whose corresponding parameter has a non-dependent type, per DR1391's 10251 /// [temp.deduct.call]p10. 10252 bool CheckNonDependentConversions( 10253 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 10254 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 10255 ConversionSequenceList &Conversions, bool SuppressUserConversions, 10256 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), 10257 Expr::Classification ObjectClassification = {}, 10258 OverloadCandidateParamOrder PO = {}); 10259 10260 /// AddConversionCandidate - Add a C++ conversion function as a 10261 /// candidate in the candidate set (C++ [over.match.conv], 10262 /// C++ [over.match.copy]). From is the expression we're converting from, 10263 /// and ToType is the type that we're eventually trying to convert to 10264 /// (which may or may not be the same type as the type that the 10265 /// conversion function produces). 10266 void AddConversionCandidate( 10267 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 10268 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 10269 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 10270 bool AllowExplicit, bool AllowResultConversion = true, 10271 bool HasMatchedPackOnParmToNonPackOnArg = false); 10272 10273 /// Adds a conversion function template specialization 10274 /// candidate to the overload set, using template argument deduction 10275 /// to deduce the template arguments of the conversion function 10276 /// template from the type that we are converting to (C++ 10277 /// [temp.deduct.conv]). 10278 void AddTemplateConversionCandidate( 10279 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 10280 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 10281 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 10282 bool AllowExplicit, bool AllowResultConversion = true); 10283 10284 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 10285 /// converts the given @c Object to a function pointer via the 10286 /// conversion function @c Conversion, and then attempts to call it 10287 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 10288 /// the type of function that we'll eventually be calling. 10289 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 10290 DeclAccessPair FoundDecl, 10291 CXXRecordDecl *ActingContext, 10292 const FunctionProtoType *Proto, Expr *Object, 10293 ArrayRef<Expr *> Args, 10294 OverloadCandidateSet &CandidateSet); 10295 10296 /// Add all of the non-member operator function declarations in the given 10297 /// function set to the overload candidate set. 10298 void AddNonMemberOperatorCandidates( 10299 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, 10300 OverloadCandidateSet &CandidateSet, 10301 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 10302 10303 /// Add overload candidates for overloaded operators that are 10304 /// member functions. 10305 /// 10306 /// Add the overloaded operator candidates that are member functions 10307 /// for the operator Op that was used in an operator expression such 10308 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 10309 /// CandidateSet will store the added overload candidates. (C++ 10310 /// [over.match.oper]). 10311 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 10312 SourceLocation OpLoc, ArrayRef<Expr *> Args, 10313 OverloadCandidateSet &CandidateSet, 10314 OverloadCandidateParamOrder PO = {}); 10315 10316 /// AddBuiltinCandidate - Add a candidate for a built-in 10317 /// operator. ResultTy and ParamTys are the result and parameter types 10318 /// of the built-in candidate, respectively. Args and NumArgs are the 10319 /// arguments being passed to the candidate. IsAssignmentOperator 10320 /// should be true when this built-in candidate is an assignment 10321 /// operator. NumContextualBoolArguments is the number of arguments 10322 /// (at the beginning of the argument list) that will be contextually 10323 /// converted to bool. 10324 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 10325 OverloadCandidateSet &CandidateSet, 10326 bool IsAssignmentOperator = false, 10327 unsigned NumContextualBoolArguments = 0); 10328 10329 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 10330 /// operator overloads to the candidate set (C++ [over.built]), based 10331 /// on the operator @p Op and the arguments given. For example, if the 10332 /// operator is a binary '+', this routine might add "int 10333 /// operator+(int, int)" to cover integer addition. 10334 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 10335 SourceLocation OpLoc, ArrayRef<Expr *> Args, 10336 OverloadCandidateSet &CandidateSet); 10337 10338 /// Add function candidates found via argument-dependent lookup 10339 /// to the set of overloading candidates. 10340 /// 10341 /// This routine performs argument-dependent name lookup based on the 10342 /// given function name (which may also be an operator name) and adds 10343 /// all of the overload candidates found by ADL to the overload 10344 /// candidate set (C++ [basic.lookup.argdep]). 10345 void AddArgumentDependentLookupCandidates( 10346 DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, 10347 TemplateArgumentListInfo *ExplicitTemplateArgs, 10348 OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); 10349 10350 /// Check the enable_if expressions on the given function. Returns the first 10351 /// failing attribute, or NULL if they were all successful. 10352 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, 10353 ArrayRef<Expr *> Args, 10354 bool MissingImplicitThis = false); 10355 10356 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 10357 /// non-ArgDependent DiagnoseIfAttrs. 10358 /// 10359 /// Argument-dependent diagnose_if attributes should be checked each time a 10360 /// function is used as a direct callee of a function call. 10361 /// 10362 /// Returns true if any errors were emitted. 10363 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 10364 const Expr *ThisArg, 10365 ArrayRef<const Expr *> Args, 10366 SourceLocation Loc); 10367 10368 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 10369 /// ArgDependent DiagnoseIfAttrs. 10370 /// 10371 /// Argument-independent diagnose_if attributes should be checked on every use 10372 /// of a function. 10373 /// 10374 /// Returns true if any errors were emitted. 10375 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 10376 SourceLocation Loc); 10377 10378 /// Determine if \p A and \p B are equivalent internal linkage declarations 10379 /// from different modules, and thus an ambiguity error can be downgraded to 10380 /// an extension warning. 10381 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 10382 const NamedDecl *B); 10383 void diagnoseEquivalentInternalLinkageDeclarations( 10384 SourceLocation Loc, const NamedDecl *D, 10385 ArrayRef<const NamedDecl *> Equiv); 10386 10387 // Emit as a 'note' the specific overload candidate 10388 void NoteOverloadCandidate( 10389 const NamedDecl *Found, const FunctionDecl *Fn, 10390 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), 10391 QualType DestType = QualType(), bool TakingAddress = false); 10392 10393 // Emit as a series of 'note's all template and non-templates identified by 10394 // the expression Expr 10395 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), 10396 bool TakingAddress = false); 10397 10398 /// Returns whether the given function's address can be taken or not, 10399 /// optionally emitting a diagnostic if the address can't be taken. 10400 /// 10401 /// Returns false if taking the address of the function is illegal. 10402 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 10403 bool Complain = false, 10404 SourceLocation Loc = SourceLocation()); 10405 10406 // [PossiblyAFunctionType] --> [Return] 10407 // NonFunctionType --> NonFunctionType 10408 // R (A) --> R(A) 10409 // R (*)(A) --> R (A) 10410 // R (&)(A) --> R (A) 10411 // R (S::*)(A) --> R (A) 10412 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 10413 10414 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10415 /// an overloaded function (C++ [over.over]), where @p From is an 10416 /// expression with overloaded function type and @p ToType is the type 10417 /// we're trying to resolve to. For example: 10418 /// 10419 /// @code 10420 /// int f(double); 10421 /// int f(int); 10422 /// 10423 /// int (*pfd)(double) = f; // selects f(double) 10424 /// @endcode 10425 /// 10426 /// This routine returns the resulting FunctionDecl if it could be 10427 /// resolved, and NULL otherwise. When @p Complain is true, this 10428 /// routine will emit diagnostics if there is an error. 10429 FunctionDecl * 10430 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, 10431 bool Complain, DeclAccessPair &Found, 10432 bool *pHadMultipleCandidates = nullptr); 10433 10434 /// Given an expression that refers to an overloaded function, try to 10435 /// resolve that function to a single function that can have its address 10436 /// taken. This will modify `Pair` iff it returns non-null. 10437 /// 10438 /// This routine can only succeed if from all of the candidates in the 10439 /// overload set for SrcExpr that can have their addresses taken, there is one 10440 /// candidate that is more constrained than the rest. 10441 FunctionDecl * 10442 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); 10443 10444 /// Given an overloaded function, tries to turn it into a non-overloaded 10445 /// function reference using resolveAddressOfSingleOverloadCandidate. This 10446 /// will perform access checks, diagnose the use of the resultant decl, and, 10447 /// if requested, potentially perform a function-to-pointer decay. 10448 /// 10449 /// Returns false if resolveAddressOfSingleOverloadCandidate fails. 10450 /// Otherwise, returns true. This may emit diagnostics and return true. 10451 bool resolveAndFixAddressOfSingleOverloadCandidate( 10452 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); 10453 10454 /// Given an expression that refers to an overloaded function, try to 10455 /// resolve that overloaded function expression down to a single function. 10456 /// 10457 /// This routine can only resolve template-ids that refer to a single function 10458 /// template, where that template-id refers to a single template whose 10459 /// template arguments are either provided by the template-id or have 10460 /// defaults, as described in C++0x [temp.arg.explicit]p3. 10461 /// 10462 /// If no template-ids are found, no diagnostics are emitted and NULL is 10463 /// returned. 10464 FunctionDecl *ResolveSingleFunctionTemplateSpecialization( 10465 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr, 10466 TemplateSpecCandidateSet *FailedTSC = nullptr); 10467 10468 // Resolve and fix an overloaded expression that can be resolved 10469 // because it identifies a single function template specialization. 10470 // 10471 // Last three arguments should only be supplied if Complain = true 10472 // 10473 // Return true if it was logically possible to so resolve the 10474 // expression, regardless of whether or not it succeeded. Always 10475 // returns true if 'complain' is set. 10476 bool ResolveAndFixSingleFunctionTemplateSpecialization( 10477 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false, 10478 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), 10479 QualType DestTypeForComplaining = QualType(), 10480 unsigned DiagIDForComplaining = 0); 10481 10482 /// Add the overload candidates named by callee and/or found by argument 10483 /// dependent lookup to the given overload set. 10484 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10485 ArrayRef<Expr *> Args, 10486 OverloadCandidateSet &CandidateSet, 10487 bool PartialOverloading = false); 10488 10489 /// Add the call candidates from the given set of lookup results to the given 10490 /// overload set. Non-function lookup results are ignored. 10491 void AddOverloadedCallCandidates( 10492 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 10493 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); 10494 10495 // An enum used to represent the different possible results of building a 10496 // range-based for loop. 10497 enum ForRangeStatus { 10498 FRS_Success, 10499 FRS_NoViableFunction, 10500 FRS_DiagnosticIssued 10501 }; 10502 10503 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 10504 /// given LookupResult is non-empty, it is assumed to describe a member which 10505 /// will be invoked. Otherwise, the function will be found via argument 10506 /// dependent lookup. 10507 /// CallExpr is set to a valid expression and FRS_Success returned on success, 10508 /// otherwise CallExpr is set to ExprError() and some non-success value 10509 /// is returned. 10510 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, 10511 SourceLocation RangeLoc, 10512 const DeclarationNameInfo &NameInfo, 10513 LookupResult &MemberLookup, 10514 OverloadCandidateSet *CandidateSet, 10515 Expr *Range, ExprResult *CallExpr); 10516 10517 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10518 /// (which eventually refers to the declaration Func) and the call 10519 /// arguments Args/NumArgs, attempt to resolve the function call down 10520 /// to a specific function. If overload resolution succeeds, returns 10521 /// the call expression produced by overload resolution. 10522 /// Otherwise, emits diagnostics and returns ExprError. 10523 ExprResult BuildOverloadedCallExpr( 10524 Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, 10525 MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, 10526 bool AllowTypoCorrection = true, bool CalleesAddressIsTaken = false); 10527 10528 /// Constructs and populates an OverloadedCandidateSet from 10529 /// the given function. 10530 /// \returns true when an the ExprResult output parameter has been set. 10531 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 10532 MultiExprArg Args, SourceLocation RParenLoc, 10533 OverloadCandidateSet *CandidateSet, 10534 ExprResult *Result); 10535 10536 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 10537 NestedNameSpecifierLoc NNSLoc, 10538 DeclarationNameInfo DNI, 10539 const UnresolvedSetImpl &Fns, 10540 bool PerformADL = true); 10541 10542 /// Create a unary operation that may resolve to an overloaded 10543 /// operator. 10544 /// 10545 /// \param OpLoc The location of the operator itself (e.g., '*'). 10546 /// 10547 /// \param Opc The UnaryOperatorKind that describes this operator. 10548 /// 10549 /// \param Fns The set of non-member functions that will be 10550 /// considered by overload resolution. The caller needs to build this 10551 /// set based on the context using, e.g., 10552 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10553 /// set should not contain any member functions; those will be added 10554 /// by CreateOverloadedUnaryOp(). 10555 /// 10556 /// \param Input The input argument. 10557 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 10558 UnaryOperatorKind Opc, 10559 const UnresolvedSetImpl &Fns, Expr *input, 10560 bool RequiresADL = true); 10561 10562 /// Perform lookup for an overloaded binary operator. 10563 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 10564 OverloadedOperatorKind Op, 10565 const UnresolvedSetImpl &Fns, 10566 ArrayRef<Expr *> Args, bool RequiresADL = true); 10567 10568 /// Create a binary operation that may resolve to an overloaded 10569 /// operator. 10570 /// 10571 /// \param OpLoc The location of the operator itself (e.g., '+'). 10572 /// 10573 /// \param Opc The BinaryOperatorKind that describes this operator. 10574 /// 10575 /// \param Fns The set of non-member functions that will be 10576 /// considered by overload resolution. The caller needs to build this 10577 /// set based on the context using, e.g., 10578 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10579 /// set should not contain any member functions; those will be added 10580 /// by CreateOverloadedBinOp(). 10581 /// 10582 /// \param LHS Left-hand argument. 10583 /// \param RHS Right-hand argument. 10584 /// \param PerformADL Whether to consider operator candidates found by ADL. 10585 /// \param AllowRewrittenCandidates Whether to consider candidates found by 10586 /// C++20 operator rewrites. 10587 /// \param DefaultedFn If we are synthesizing a defaulted operator function, 10588 /// the function in question. Such a function is never a candidate in 10589 /// our overload resolution. This also enables synthesizing a three-way 10590 /// comparison from < and == as described in C++20 [class.spaceship]p1. 10591 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 10592 const UnresolvedSetImpl &Fns, Expr *LHS, 10593 Expr *RHS, bool RequiresADL = true, 10594 bool AllowRewrittenCandidates = true, 10595 FunctionDecl *DefaultedFn = nullptr); 10596 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, 10597 const UnresolvedSetImpl &Fns, 10598 Expr *LHS, Expr *RHS, 10599 FunctionDecl *DefaultedFn); 10600 10601 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10602 SourceLocation RLoc, Expr *Base, 10603 MultiExprArg Args); 10604 10605 /// BuildCallToMemberFunction - Build a call to a member 10606 /// function. MemExpr is the expression that refers to the member 10607 /// function (and includes the object parameter), Args/NumArgs are the 10608 /// arguments to the function call (not including the object 10609 /// parameter). The caller needs to validate that the member 10610 /// expression refers to a non-static member function or an overloaded 10611 /// member function. 10612 ExprResult BuildCallToMemberFunction( 10613 Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, 10614 SourceLocation RParenLoc, Expr *ExecConfig = nullptr, 10615 bool IsExecConfig = false, bool AllowRecovery = false); 10616 10617 /// BuildCallToObjectOfClassType - Build a call to an object of class 10618 /// type (C++ [over.call.object]), which can end up invoking an 10619 /// overloaded function call operator (@c operator()) or performing a 10620 /// user-defined conversion on the object argument. 10621 ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, 10622 SourceLocation LParenLoc, 10623 MultiExprArg Args, 10624 SourceLocation RParenLoc); 10625 10626 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 10627 /// (if one exists), where @c Base is an expression of class type and 10628 /// @c Member is the name of the member we're trying to find. 10629 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 10630 SourceLocation OpLoc, 10631 bool *NoArrowOperatorFound = nullptr); 10632 10633 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 10634 CXXConversionDecl *Method, 10635 bool HadMultipleCandidates); 10636 10637 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call 10638 /// to a literal operator described by the provided lookup results. 10639 ExprResult BuildLiteralOperatorCall( 10640 LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, 10641 SourceLocation LitEndLoc, 10642 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 10643 10644 /// FixOverloadedFunctionReference - E is an expression that refers to 10645 /// a C++ overloaded function (possibly with some parentheses and 10646 /// perhaps a '&' around it). We have resolved the overloaded function 10647 /// to the function declaration Fn, so patch up the expression E to 10648 /// refer (possibly indirectly) to Fn. Returns the new expr. 10649 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, 10650 FunctionDecl *Fn); 10651 ExprResult FixOverloadedFunctionReference(ExprResult, 10652 DeclAccessPair FoundDecl, 10653 FunctionDecl *Fn); 10654 10655 /// - Returns a selector which best matches given argument list or 10656 /// nullptr if none could be found 10657 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 10658 bool IsInstance, 10659 SmallVectorImpl<ObjCMethodDecl *> &Methods); 10660 10661 ///@} 10662 10663 // 10664 // 10665 // ------------------------------------------------------------------------- 10666 // 10667 // 10668 10669 /// \name Statements 10670 /// Implementations are in SemaStmt.cpp 10671 ///@{ 10672 10673 public: 10674 /// Stack of active SEH __finally scopes. Can be empty. 10675 SmallVector<Scope *, 2> CurrentSEHFinally; 10676 10677 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); 10678 StmtResult ActOnExprStmtError(); 10679 10680 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 10681 bool HasLeadingEmptyMacro = false); 10682 10683 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, 10684 SourceLocation EndLoc); 10685 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 10686 10687 /// DiagnoseDiscardedExprMarkedNodiscard - Given an expression that is 10688 /// semantically a discarded-value expression, diagnose if any [[nodiscard]] 10689 /// value has been discarded. 10690 void DiagnoseDiscardedExprMarkedNodiscard(const Expr *E); 10691 10692 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 10693 /// whose result is unused, warn. 10694 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID); 10695 10696 void ActOnStartOfCompoundStmt(bool IsStmtExpr); 10697 void ActOnAfterCompoundStatementLeadingPragmas(); 10698 void ActOnFinishOfCompoundStmt(); 10699 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 10700 ArrayRef<Stmt *> Elts, bool isStmtExpr); 10701 10702 sema::CompoundScopeInfo &getCurCompoundScope() const; 10703 10704 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); 10705 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, 10706 SourceLocation DotDotDotLoc, ExprResult RHS, 10707 SourceLocation ColonLoc); 10708 10709 /// ActOnCaseStmtBody - This installs a statement as the body of a case. 10710 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 10711 10712 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 10713 SourceLocation ColonLoc, Stmt *SubStmt, 10714 Scope *CurScope); 10715 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 10716 SourceLocation ColonLoc, Stmt *SubStmt); 10717 10718 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, 10719 ArrayRef<const Attr *> Attrs, Stmt *SubStmt); 10720 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList, 10721 Stmt *SubStmt); 10722 10723 /// Check whether the given statement can have musttail applied to it, 10724 /// issuing a diagnostic and returning false if not. In the success case, 10725 /// the statement is rewritten to remove implicit nodes from the return 10726 /// value. 10727 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); 10728 10729 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, 10730 SourceLocation LParenLoc, Stmt *InitStmt, 10731 ConditionResult Cond, SourceLocation RParenLoc, 10732 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 10733 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, 10734 SourceLocation LParenLoc, Stmt *InitStmt, 10735 ConditionResult Cond, SourceLocation RParenLoc, 10736 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 10737 10738 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); 10739 10740 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 10741 SourceLocation LParenLoc, Stmt *InitStmt, 10742 ConditionResult Cond, 10743 SourceLocation RParenLoc); 10744 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 10745 Stmt *Body); 10746 10747 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 10748 /// integer not in the range of enum values. 10749 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 10750 Expr *SrcExpr); 10751 10752 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, 10753 ConditionResult Cond, SourceLocation RParenLoc, 10754 Stmt *Body); 10755 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 10756 SourceLocation WhileLoc, SourceLocation CondLParen, 10757 Expr *Cond, SourceLocation CondRParen); 10758 10759 StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 10760 Stmt *First, ConditionResult Second, 10761 FullExprArg Third, SourceLocation RParenLoc, 10762 Stmt *Body); 10763 10764 /// In an Objective C collection iteration statement: 10765 /// for (x in y) 10766 /// x can be an arbitrary l-value expression. Bind it up as a 10767 /// full-expression. 10768 StmtResult ActOnForEachLValueExpr(Expr *E); 10769 10770 enum BuildForRangeKind { 10771 /// Initial building of a for-range statement. 10772 BFRK_Build, 10773 /// Instantiation or recovery rebuild of a for-range statement. Don't 10774 /// attempt any typo-correction. 10775 BFRK_Rebuild, 10776 /// Determining whether a for-range statement could be built. Avoid any 10777 /// unnecessary or irreversible actions. 10778 BFRK_Check 10779 }; 10780 10781 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement. 10782 /// 10783 /// C++11 [stmt.ranged]: 10784 /// A range-based for statement is equivalent to 10785 /// 10786 /// { 10787 /// auto && __range = range-init; 10788 /// for ( auto __begin = begin-expr, 10789 /// __end = end-expr; 10790 /// __begin != __end; 10791 /// ++__begin ) { 10792 /// for-range-declaration = *__begin; 10793 /// statement 10794 /// } 10795 /// } 10796 /// 10797 /// The body of the loop is not available yet, since it cannot be analysed 10798 /// until we have determined the type of the for-range-declaration. 10799 StmtResult ActOnCXXForRangeStmt( 10800 Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, 10801 Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, 10802 SourceLocation RParenLoc, BuildForRangeKind Kind, 10803 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {}); 10804 10805 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement. 10806 StmtResult BuildCXXForRangeStmt( 10807 SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, 10808 SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, 10809 Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, 10810 BuildForRangeKind Kind, 10811 ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps = {}); 10812 10813 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 10814 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the 10815 /// body cannot be performed until after the type of the range variable is 10816 /// determined. 10817 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 10818 10819 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 10820 LabelDecl *TheDecl); 10821 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 10822 SourceLocation StarLoc, Expr *DestExp); 10823 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 10824 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 10825 10826 struct NamedReturnInfo { 10827 const VarDecl *Candidate; 10828 10829 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; 10830 Status S; 10831 10832 bool isMoveEligible() const { return S != None; }; 10833 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } 10834 }; 10835 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn }; 10836 10837 /// Determine whether the given expression might be move-eligible or 10838 /// copy-elidable in either a (co_)return statement or throw expression, 10839 /// without considering function return type, if applicable. 10840 /// 10841 /// \param E The expression being returned from the function or block, 10842 /// being thrown, or being co_returned from a coroutine. This expression 10843 /// might be modified by the implementation. 10844 /// 10845 /// \param Mode Overrides detection of current language mode 10846 /// and uses the rules for C++23. 10847 /// 10848 /// \returns An aggregate which contains the Candidate and isMoveEligible 10849 /// and isCopyElidable methods. If Candidate is non-null, it means 10850 /// isMoveEligible() would be true under the most permissive language 10851 /// standard. 10852 NamedReturnInfo getNamedReturnInfo( 10853 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal); 10854 10855 /// Determine whether the given NRVO candidate variable is move-eligible or 10856 /// copy-elidable, without considering function return type. 10857 /// 10858 /// \param VD The NRVO candidate variable. 10859 /// 10860 /// \returns An aggregate which contains the Candidate and isMoveEligible 10861 /// and isCopyElidable methods. If Candidate is non-null, it means 10862 /// isMoveEligible() would be true under the most permissive language 10863 /// standard. 10864 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD); 10865 10866 /// Updates given NamedReturnInfo's move-eligible and 10867 /// copy-elidable statuses, considering the function 10868 /// return type criteria as applicable to return statements. 10869 /// 10870 /// \param Info The NamedReturnInfo object to update. 10871 /// 10872 /// \param ReturnType This is the return type of the function. 10873 /// \returns The copy elision candidate, in case the initial return expression 10874 /// was copy elidable, or nullptr otherwise. 10875 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, 10876 QualType ReturnType); 10877 10878 /// Perform the initialization of a potentially-movable value, which 10879 /// is the result of return value. 10880 /// 10881 /// This routine implements C++20 [class.copy.elision]p3, which attempts to 10882 /// treat returned lvalues as rvalues in certain cases (to prefer move 10883 /// construction), then falls back to treating them as lvalues if that failed. 10884 ExprResult 10885 PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 10886 const NamedReturnInfo &NRInfo, Expr *Value, 10887 bool SupressSimplerImplicitMoves = false); 10888 10889 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 10890 10891 /// Deduce the return type for a function from a returned expression, per 10892 /// C++1y [dcl.spec.auto]p6. 10893 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 10894 SourceLocation ReturnLoc, Expr *RetExpr, 10895 const AutoType *AT); 10896 10897 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 10898 Scope *CurScope); 10899 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 10900 bool AllowRecovery = false); 10901 10902 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements 10903 /// for capturing scopes. 10904 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 10905 NamedReturnInfo &NRInfo, 10906 bool SupressSimplerImplicitMoves); 10907 10908 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 10909 /// and creates a proper catch handler from them. 10910 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 10911 Stmt *HandlerBlock); 10912 10913 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of 10914 /// handlers and creates a try statement from them. 10915 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 10916 ArrayRef<Stmt *> Handlers); 10917 10918 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 10919 SourceLocation TryLoc, Stmt *TryBlock, 10920 Stmt *Handler); 10921 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, 10922 Stmt *Block); 10923 void ActOnStartSEHFinallyBlock(); 10924 void ActOnAbortSEHFinallyBlock(); 10925 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 10926 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 10927 10928 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 10929 bool IsIfExists, 10930 NestedNameSpecifierLoc QualifierLoc, 10931 DeclarationNameInfo NameInfo, 10932 Stmt *Nested); 10933 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 10934 bool IsIfExists, CXXScopeSpec &SS, 10935 UnqualifiedId &Name, Stmt *Nested); 10936 10937 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 10938 CapturedRegionKind Kind, unsigned NumParams); 10939 typedef std::pair<StringRef, QualType> CapturedParamNameType; 10940 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 10941 CapturedRegionKind Kind, 10942 ArrayRef<CapturedParamNameType> Params, 10943 unsigned OpenMPCaptureLevel = 0); 10944 StmtResult ActOnCapturedRegionEnd(Stmt *S); 10945 void ActOnCapturedRegionError(); 10946 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 10947 SourceLocation Loc, 10948 unsigned NumParams); 10949 10950 private: 10951 /// Check whether the given statement can have musttail applied to it, 10952 /// issuing a diagnostic and returning false if not. 10953 bool checkMustTailAttr(const Stmt *St, const Attr &MTA); 10954 10955 /// Check if the given expression contains 'break' or 'continue' 10956 /// statement that produces control flow different from GCC. 10957 void CheckBreakContinueBinding(Expr *E); 10958 10959 ///@} 10960 10961 // 10962 // 10963 // ------------------------------------------------------------------------- 10964 // 10965 // 10966 10967 /// \name `inline asm` Statement 10968 /// Implementations are in SemaStmtAsm.cpp 10969 ///@{ 10970 10971 public: 10972 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 10973 bool IsVolatile, unsigned NumOutputs, 10974 unsigned NumInputs, IdentifierInfo **Names, 10975 MultiExprArg Constraints, MultiExprArg Exprs, 10976 Expr *AsmString, MultiExprArg Clobbers, 10977 unsigned NumLabels, SourceLocation RParenLoc); 10978 10979 void FillInlineAsmIdentifierInfo(Expr *Res, 10980 llvm::InlineAsmIdentifierInfo &Info); 10981 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 10982 SourceLocation TemplateKWLoc, 10983 UnqualifiedId &Id, 10984 bool IsUnevaluatedContext); 10985 bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, 10986 SourceLocation AsmLoc); 10987 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, 10988 SourceLocation AsmLoc); 10989 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 10990 ArrayRef<Token> AsmToks, StringRef AsmString, 10991 unsigned NumOutputs, unsigned NumInputs, 10992 ArrayRef<StringRef> Constraints, 10993 ArrayRef<StringRef> Clobbers, 10994 ArrayRef<Expr *> Exprs, SourceLocation EndLoc); 10995 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 10996 SourceLocation Location, bool AlwaysCreate); 10997 10998 ///@} 10999 11000 // 11001 // 11002 // ------------------------------------------------------------------------- 11003 // 11004 // 11005 11006 /// \name Statement Attribute Handling 11007 /// Implementations are in SemaStmtAttr.cpp 11008 ///@{ 11009 11010 public: 11011 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, 11012 const AttributeCommonInfo &A); 11013 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, 11014 const AttributeCommonInfo &A); 11015 11016 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E); 11017 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs); 11018 11019 /// Process the attributes before creating an attributed statement. Returns 11020 /// the semantic attributes that have been processed. 11021 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, 11022 SmallVectorImpl<const Attr *> &OutAttrs); 11023 11024 ExprResult ActOnCXXAssumeAttr(Stmt *St, const ParsedAttr &A, 11025 SourceRange Range); 11026 ExprResult BuildCXXAssumeExpr(Expr *Assumption, 11027 const IdentifierInfo *AttrName, 11028 SourceRange Range); 11029 11030 ///@} 11031 11032 // 11033 // 11034 // ------------------------------------------------------------------------- 11035 // 11036 // 11037 11038 /// \name C++ Templates 11039 /// Implementations are in SemaTemplate.cpp 11040 ///@{ 11041 11042 public: 11043 // Saves the current floating-point pragma stack and clear it in this Sema. 11044 class FpPragmaStackSaveRAII { 11045 public: 11046 FpPragmaStackSaveRAII(Sema &S) 11047 : S(S), SavedStack(std::move(S.FpPragmaStack)) { 11048 S.FpPragmaStack.Stack.clear(); 11049 } 11050 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); } 11051 11052 private: 11053 Sema &S; 11054 PragmaStack<FPOptionsOverride> SavedStack; 11055 }; 11056 11057 void resetFPOptions(FPOptions FPO) { 11058 CurFPFeatures = FPO; 11059 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts)); 11060 } 11061 11062 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { 11063 return llvm::ArrayRef(InventedParameterInfos.begin() + 11064 InventedParameterInfosStart, 11065 InventedParameterInfos.end()); 11066 } 11067 11068 /// The number of SFINAE diagnostics that have been trapped. 11069 unsigned NumSFINAEErrors; 11070 11071 ArrayRef<sema::FunctionScopeInfo *> getFunctionScopes() const { 11072 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart, 11073 FunctionScopes.end()); 11074 } 11075 11076 typedef llvm::MapVector<const FunctionDecl *, 11077 std::unique_ptr<LateParsedTemplate>> 11078 LateParsedTemplateMapT; 11079 LateParsedTemplateMapT LateParsedTemplateMap; 11080 11081 /// Determine the number of levels of enclosing template parameters. This is 11082 /// only usable while parsing. Note that this does not include dependent 11083 /// contexts in which no template parameters have yet been declared, such as 11084 /// in a terse function template or generic lambda before the first 'auto' is 11085 /// encountered. 11086 unsigned getTemplateDepth(Scope *S) const; 11087 11088 void FilterAcceptableTemplateNames(LookupResult &R, 11089 bool AllowFunctionTemplates = true, 11090 bool AllowDependent = true); 11091 bool hasAnyAcceptableTemplateNames(LookupResult &R, 11092 bool AllowFunctionTemplates = true, 11093 bool AllowDependent = true, 11094 bool AllowNonTemplateFunctions = false); 11095 /// Try to interpret the lookup result D as a template-name. 11096 /// 11097 /// \param D A declaration found by name lookup. 11098 /// \param AllowFunctionTemplates Whether function templates should be 11099 /// considered valid results. 11100 /// \param AllowDependent Whether unresolved using declarations (that might 11101 /// name templates) should be considered valid results. 11102 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, 11103 bool AllowFunctionTemplates = true, 11104 bool AllowDependent = true); 11105 11106 enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; 11107 /// Whether and why a template name is required in this lookup. 11108 class RequiredTemplateKind { 11109 public: 11110 /// Template name is required if TemplateKWLoc is valid. 11111 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) 11112 : TemplateKW(TemplateKWLoc) {} 11113 /// Template name is unconditionally required. 11114 RequiredTemplateKind(TemplateNameIsRequiredTag) {} 11115 11116 SourceLocation getTemplateKeywordLoc() const { 11117 return TemplateKW.value_or(SourceLocation()); 11118 } 11119 bool hasTemplateKeyword() const { 11120 return getTemplateKeywordLoc().isValid(); 11121 } 11122 bool isRequired() const { return TemplateKW != SourceLocation(); } 11123 explicit operator bool() const { return isRequired(); } 11124 11125 private: 11126 std::optional<SourceLocation> TemplateKW; 11127 }; 11128 11129 enum class AssumedTemplateKind { 11130 /// This is not assumed to be a template name. 11131 None, 11132 /// This is assumed to be a template name because lookup found nothing. 11133 FoundNothing, 11134 /// This is assumed to be a template name because lookup found one or more 11135 /// functions (but no function templates). 11136 FoundFunctions, 11137 }; 11138 11139 bool 11140 LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 11141 QualType ObjectType, bool EnteringContext, 11142 RequiredTemplateKind RequiredTemplate = SourceLocation(), 11143 AssumedTemplateKind *ATK = nullptr, 11144 bool AllowTypoCorrection = true); 11145 11146 TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, 11147 bool hasTemplateKeyword, 11148 const UnqualifiedId &Name, 11149 ParsedType ObjectType, bool EnteringContext, 11150 TemplateTy &Template, 11151 bool &MemberOfUnknownSpecialization, 11152 bool Disambiguation = false); 11153 11154 /// Try to resolve an undeclared template name as a type template. 11155 /// 11156 /// Sets II to the identifier corresponding to the template name, and updates 11157 /// Name to a corresponding (typo-corrected) type template name and TNK to 11158 /// the corresponding kind, if possible. 11159 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, 11160 TemplateNameKind &TNK, 11161 SourceLocation NameLoc, 11162 IdentifierInfo *&II); 11163 11164 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 11165 SourceLocation NameLoc, 11166 bool Diagnose = true); 11167 11168 /// Determine whether a particular identifier might be the name in a C++1z 11169 /// deduction-guide declaration. 11170 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 11171 SourceLocation NameLoc, CXXScopeSpec &SS, 11172 ParsedTemplateTy *Template = nullptr); 11173 11174 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 11175 SourceLocation IILoc, Scope *S, 11176 const CXXScopeSpec *SS, 11177 TemplateTy &SuggestedTemplate, 11178 TemplateNameKind &SuggestedKind); 11179 11180 /// Determine whether we would be unable to instantiate this template (because 11181 /// it either has no definition, or is in the process of being instantiated). 11182 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 11183 NamedDecl *Instantiation, 11184 bool InstantiatedFromMember, 11185 const NamedDecl *Pattern, 11186 const NamedDecl *PatternDef, 11187 TemplateSpecializationKind TSK, 11188 bool Complain = true); 11189 11190 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 11191 /// that the template parameter 'PrevDecl' is being shadowed by a new 11192 /// declaration at location Loc. Returns true to indicate that this is 11193 /// an error, and false otherwise. 11194 /// 11195 /// \param Loc The location of the declaration that shadows a template 11196 /// parameter. 11197 /// 11198 /// \param PrevDecl The template parameter that the declaration shadows. 11199 /// 11200 /// \param SupportedForCompatibility Whether to issue the diagnostic as 11201 /// a warning for compatibility with older versions of clang. 11202 /// Ignored when MSVC compatibility is enabled. 11203 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, 11204 bool SupportedForCompatibility = false); 11205 11206 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 11207 /// the parameter D to reference the templated declaration and return a 11208 /// pointer to the template declaration. Otherwise, do nothing to D and return 11209 /// null. 11210 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 11211 11212 /// ActOnTypeParameter - Called when a C++ template type parameter 11213 /// (e.g., "typename T") has been parsed. Typename specifies whether 11214 /// the keyword "typename" was used to declare the type parameter 11215 /// (otherwise, "class" was used), and KeyLoc is the location of the 11216 /// "class" or "typename" keyword. ParamName is the name of the 11217 /// parameter (NULL indicates an unnamed template parameter) and 11218 /// ParamNameLoc is the location of the parameter name (if any). 11219 /// If the type parameter has a default argument, it will be added 11220 /// later via ActOnTypeParameterDefault. 11221 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, 11222 SourceLocation EllipsisLoc, 11223 SourceLocation KeyLoc, 11224 IdentifierInfo *ParamName, 11225 SourceLocation ParamNameLoc, unsigned Depth, 11226 unsigned Position, SourceLocation EqualLoc, 11227 ParsedType DefaultArg, bool HasTypeConstraint); 11228 11229 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint); 11230 11231 bool ActOnTypeConstraint(const CXXScopeSpec &SS, 11232 TemplateIdAnnotation *TypeConstraint, 11233 TemplateTypeParmDecl *ConstrainedParameter, 11234 SourceLocation EllipsisLoc); 11235 bool BuildTypeConstraint(const CXXScopeSpec &SS, 11236 TemplateIdAnnotation *TypeConstraint, 11237 TemplateTypeParmDecl *ConstrainedParameter, 11238 SourceLocation EllipsisLoc, 11239 bool AllowUnexpandedPack); 11240 11241 /// Attach a type-constraint to a template parameter. 11242 /// \returns true if an error occurred. This can happen if the 11243 /// immediately-declared constraint could not be formed (e.g. incorrect number 11244 /// of arguments for the named concept). 11245 bool AttachTypeConstraint(NestedNameSpecifierLoc NS, 11246 DeclarationNameInfo NameInfo, 11247 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, 11248 const TemplateArgumentListInfo *TemplateArgs, 11249 TemplateTypeParmDecl *ConstrainedParameter, 11250 QualType ConstrainedType, 11251 SourceLocation EllipsisLoc); 11252 11253 bool AttachTypeConstraint(AutoTypeLoc TL, 11254 NonTypeTemplateParmDecl *NewConstrainedParm, 11255 NonTypeTemplateParmDecl *OrigConstrainedParm, 11256 SourceLocation EllipsisLoc); 11257 11258 /// Require the given type to be a structural type, and diagnose if it is not. 11259 /// 11260 /// \return \c true if an error was produced. 11261 bool RequireStructuralType(QualType T, SourceLocation Loc); 11262 11263 /// Check that the type of a non-type template parameter is 11264 /// well-formed. 11265 /// 11266 /// \returns the (possibly-promoted) parameter type if valid; 11267 /// otherwise, produces a diagnostic and returns a NULL type. 11268 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 11269 SourceLocation Loc); 11270 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 11271 11272 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 11273 unsigned Depth, unsigned Position, 11274 SourceLocation EqualLoc, 11275 Expr *DefaultArg); 11276 11277 /// ActOnTemplateTemplateParameter - Called when a C++ template template 11278 /// parameter (e.g. T in template <template \<typename> class T> class array) 11279 /// has been parsed. S is the current scope. 11280 NamedDecl *ActOnTemplateTemplateParameter( 11281 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, 11282 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, 11283 SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, 11284 SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); 11285 11286 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally 11287 /// constrained by RequiresClause, that contains the template parameters in 11288 /// Params. 11289 TemplateParameterList *ActOnTemplateParameterList( 11290 unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, 11291 SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, 11292 SourceLocation RAngleLoc, Expr *RequiresClause); 11293 11294 /// The context in which we are checking a template parameter list. 11295 enum TemplateParamListContext { 11296 TPC_ClassTemplate, 11297 TPC_VarTemplate, 11298 TPC_FunctionTemplate, 11299 TPC_ClassTemplateMember, 11300 TPC_FriendClassTemplate, 11301 TPC_FriendFunctionTemplate, 11302 TPC_FriendFunctionTemplateDefinition, 11303 TPC_TypeAliasTemplate 11304 }; 11305 11306 /// Checks the validity of a template parameter list, possibly 11307 /// considering the template parameter list from a previous 11308 /// declaration. 11309 /// 11310 /// If an "old" template parameter list is provided, it must be 11311 /// equivalent (per TemplateParameterListsAreEqual) to the "new" 11312 /// template parameter list. 11313 /// 11314 /// \param NewParams Template parameter list for a new template 11315 /// declaration. This template parameter list will be updated with any 11316 /// default arguments that are carried through from the previous 11317 /// template parameter list. 11318 /// 11319 /// \param OldParams If provided, template parameter list from a 11320 /// previous declaration of the same template. Default template 11321 /// arguments will be merged from the old template parameter list to 11322 /// the new template parameter list. 11323 /// 11324 /// \param TPC Describes the context in which we are checking the given 11325 /// template parameter list. 11326 /// 11327 /// \param SkipBody If we might have already made a prior merged definition 11328 /// of this template visible, the corresponding body-skipping information. 11329 /// Default argument redefinition is not an error when skipping such a body, 11330 /// because (under the ODR) we can assume the default arguments are the same 11331 /// as the prior merged definition. 11332 /// 11333 /// \returns true if an error occurred, false otherwise. 11334 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 11335 TemplateParameterList *OldParams, 11336 TemplateParamListContext TPC, 11337 SkipBodyInfo *SkipBody = nullptr); 11338 11339 /// Match the given template parameter lists to the given scope 11340 /// specifier, returning the template parameter list that applies to the 11341 /// name. 11342 /// 11343 /// \param DeclStartLoc the start of the declaration that has a scope 11344 /// specifier or a template parameter list. 11345 /// 11346 /// \param DeclLoc The location of the declaration itself. 11347 /// 11348 /// \param SS the scope specifier that will be matched to the given template 11349 /// parameter lists. This scope specifier precedes a qualified name that is 11350 /// being declared. 11351 /// 11352 /// \param TemplateId The template-id following the scope specifier, if there 11353 /// is one. Used to check for a missing 'template<>'. 11354 /// 11355 /// \param ParamLists the template parameter lists, from the outermost to the 11356 /// innermost template parameter lists. 11357 /// 11358 /// \param IsFriend Whether to apply the slightly different rules for 11359 /// matching template parameters to scope specifiers in friend 11360 /// declarations. 11361 /// 11362 /// \param IsMemberSpecialization will be set true if the scope specifier 11363 /// denotes a fully-specialized type, and therefore this is a declaration of 11364 /// a member specialization. 11365 /// 11366 /// \returns the template parameter list, if any, that corresponds to the 11367 /// name that is preceded by the scope specifier @p SS. This template 11368 /// parameter list may have template parameters (if we're declaring a 11369 /// template) or may have no template parameters (if we're declaring a 11370 /// template specialization), or may be NULL (if what we're declaring isn't 11371 /// itself a template). 11372 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 11373 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 11374 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 11375 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, 11376 bool &IsMemberSpecialization, bool &Invalid, 11377 bool SuppressDiagnostic = false); 11378 11379 /// Returns the template parameter list with all default template argument 11380 /// information. 11381 TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD); 11382 11383 DeclResult CheckClassTemplate( 11384 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 11385 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 11386 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 11387 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 11388 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 11389 TemplateParameterList **OuterTemplateParamLists, 11390 SkipBodyInfo *SkipBody = nullptr); 11391 11392 /// Translates template arguments as provided by the parser 11393 /// into template arguments used by semantic analysis. 11394 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 11395 TemplateArgumentListInfo &Out); 11396 11397 /// Convert a parsed type into a parsed template argument. This is mostly 11398 /// trivial, except that we may have parsed a C++17 deduced class template 11399 /// specialization type, in which case we should form a template template 11400 /// argument instead of a type template argument. 11401 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); 11402 11403 void NoteAllFoundTemplates(TemplateName Name); 11404 11405 QualType CheckTemplateIdType(TemplateName Template, 11406 SourceLocation TemplateLoc, 11407 TemplateArgumentListInfo &TemplateArgs); 11408 11409 TypeResult 11410 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 11411 TemplateTy Template, const IdentifierInfo *TemplateII, 11412 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 11413 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, 11414 bool IsCtorOrDtorName = false, bool IsClassName = false, 11415 ImplicitTypenameContext AllowImplicitTypename = 11416 ImplicitTypenameContext::No); 11417 11418 /// Parsed an elaborated-type-specifier that refers to a template-id, 11419 /// such as \c class T::template apply<U>. 11420 TypeResult ActOnTagTemplateIdType( 11421 TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, 11422 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, 11423 SourceLocation TemplateLoc, SourceLocation LAngleLoc, 11424 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); 11425 11426 DeclResult ActOnVarTemplateSpecialization( 11427 Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, 11428 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 11429 StorageClass SC, bool IsPartialSpecialization); 11430 11431 /// Get the specialization of the given variable template corresponding to 11432 /// the specified argument list, or a null-but-valid result if the arguments 11433 /// are dependent. 11434 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 11435 SourceLocation TemplateLoc, 11436 SourceLocation TemplateNameLoc, 11437 const TemplateArgumentListInfo &TemplateArgs); 11438 11439 /// Form a reference to the specialization of the given variable template 11440 /// corresponding to the specified argument list, or a null-but-valid result 11441 /// if the arguments are dependent. 11442 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 11443 const DeclarationNameInfo &NameInfo, 11444 VarTemplateDecl *Template, NamedDecl *FoundD, 11445 SourceLocation TemplateLoc, 11446 const TemplateArgumentListInfo *TemplateArgs); 11447 11448 ExprResult 11449 CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 11450 const DeclarationNameInfo &ConceptNameInfo, 11451 NamedDecl *FoundDecl, ConceptDecl *NamedConcept, 11452 const TemplateArgumentListInfo *TemplateArgs); 11453 11454 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); 11455 void diagnoseMissingTemplateArguments(const CXXScopeSpec &SS, 11456 bool TemplateKeyword, TemplateDecl *TD, 11457 SourceLocation Loc); 11458 11459 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 11460 SourceLocation TemplateKWLoc, LookupResult &R, 11461 bool RequiresADL, 11462 const TemplateArgumentListInfo *TemplateArgs); 11463 11464 // We actually only call this from template instantiation. 11465 ExprResult 11466 BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 11467 const DeclarationNameInfo &NameInfo, 11468 const TemplateArgumentListInfo *TemplateArgs, 11469 bool IsAddressOfOperand); 11470 11471 /// Form a template name from a name that is syntactically required to name a 11472 /// template, either due to use of the 'template' keyword or because a name in 11473 /// this syntactic context is assumed to name a template (C++ 11474 /// [temp.names]p2-4). 11475 /// 11476 /// This action forms a template name given the name of the template and its 11477 /// optional scope specifier. This is used when the 'template' keyword is used 11478 /// or when the parsing context unambiguously treats a following '<' as 11479 /// introducing a template argument list. Note that this may produce a 11480 /// non-dependent template name if we can perform the lookup now and identify 11481 /// the named template. 11482 /// 11483 /// For example, given "x.MetaFun::template apply", the scope specifier 11484 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location 11485 /// of the "template" keyword, and "apply" is the \p Name. 11486 TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, 11487 SourceLocation TemplateKWLoc, 11488 const UnqualifiedId &Name, 11489 ParsedType ObjectType, 11490 bool EnteringContext, TemplateTy &Template, 11491 bool AllowInjectedClassName = false); 11492 11493 DeclResult ActOnClassTemplateSpecialization( 11494 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 11495 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 11496 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 11497 MultiTemplateParamsArg TemplateParameterLists, 11498 SkipBodyInfo *SkipBody = nullptr); 11499 11500 /// Check the non-type template arguments of a class template 11501 /// partial specialization according to C++ [temp.class.spec]p9. 11502 /// 11503 /// \param TemplateNameLoc the location of the template name. 11504 /// \param PrimaryTemplate the template parameters of the primary class 11505 /// template. 11506 /// \param NumExplicit the number of explicitly-specified template arguments. 11507 /// \param TemplateArgs the template arguments of the class template 11508 /// partial specialization. 11509 /// 11510 /// \returns \c true if there was an error, \c false otherwise. 11511 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, 11512 TemplateDecl *PrimaryTemplate, 11513 unsigned NumExplicitArgs, 11514 ArrayRef<TemplateArgument> Args); 11515 void CheckTemplatePartialSpecialization( 11516 ClassTemplatePartialSpecializationDecl *Partial); 11517 void CheckTemplatePartialSpecialization( 11518 VarTemplatePartialSpecializationDecl *Partial); 11519 11520 Decl *ActOnTemplateDeclarator(Scope *S, 11521 MultiTemplateParamsArg TemplateParameterLists, 11522 Declarator &D); 11523 11524 /// Diagnose cases where we have an explicit template specialization 11525 /// before/after an explicit template instantiation, producing diagnostics 11526 /// for those cases where they are required and determining whether the 11527 /// new specialization/instantiation will have any effect. 11528 /// 11529 /// \param NewLoc the location of the new explicit specialization or 11530 /// instantiation. 11531 /// 11532 /// \param NewTSK the kind of the new explicit specialization or 11533 /// instantiation. 11534 /// 11535 /// \param PrevDecl the previous declaration of the entity. 11536 /// 11537 /// \param PrevTSK the kind of the old explicit specialization or 11538 /// instantiatin. 11539 /// 11540 /// \param PrevPointOfInstantiation if valid, indicates where the previous 11541 /// declaration was instantiated (either implicitly or explicitly). 11542 /// 11543 /// \param HasNoEffect will be set to true to indicate that the new 11544 /// specialization or instantiation has no effect and should be ignored. 11545 /// 11546 /// \returns true if there was an error that should prevent the introduction 11547 /// of the new declaration into the AST, false otherwise. 11548 bool CheckSpecializationInstantiationRedecl( 11549 SourceLocation NewLoc, 11550 TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, 11551 NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, 11552 SourceLocation PrevPtOfInstantiation, bool &SuppressNew); 11553 11554 /// Perform semantic analysis for the given dependent function 11555 /// template specialization. 11556 /// 11557 /// The only possible way to get a dependent function template specialization 11558 /// is with a friend declaration, like so: 11559 /// 11560 /// \code 11561 /// template \<class T> void foo(T); 11562 /// template \<class T> class A { 11563 /// friend void foo<>(T); 11564 /// }; 11565 /// \endcode 11566 /// 11567 /// There really isn't any useful analysis we can do here, so we 11568 /// just store the information. 11569 bool CheckDependentFunctionTemplateSpecialization( 11570 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, 11571 LookupResult &Previous); 11572 11573 /// Perform semantic analysis for the given function template 11574 /// specialization. 11575 /// 11576 /// This routine performs all of the semantic analysis required for an 11577 /// explicit function template specialization. On successful completion, 11578 /// the function declaration \p FD will become a function template 11579 /// specialization. 11580 /// 11581 /// \param FD the function declaration, which will be updated to become a 11582 /// function template specialization. 11583 /// 11584 /// \param ExplicitTemplateArgs the explicitly-provided template arguments, 11585 /// if any. Note that this may be valid info even when 0 arguments are 11586 /// explicitly provided as in, e.g., \c void sort<>(char*, char*); 11587 /// as it anyway contains info on the angle brackets locations. 11588 /// 11589 /// \param Previous the set of declarations that may be specialized by 11590 /// this function specialization. 11591 /// 11592 /// \param QualifiedFriend whether this is a lookup for a qualified friend 11593 /// declaration with no explicit template argument list that might be 11594 /// befriending a function template specialization. 11595 bool CheckFunctionTemplateSpecialization( 11596 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 11597 LookupResult &Previous, bool QualifiedFriend = false); 11598 11599 /// Perform semantic analysis for the given non-template member 11600 /// specialization. 11601 /// 11602 /// This routine performs all of the semantic analysis required for an 11603 /// explicit member function specialization. On successful completion, 11604 /// the function declaration \p FD will become a member function 11605 /// specialization. 11606 /// 11607 /// \param Member the member declaration, which will be updated to become a 11608 /// specialization. 11609 /// 11610 /// \param Previous the set of declarations, one of which may be specialized 11611 /// by this function specialization; the set will be modified to contain the 11612 /// redeclared member. 11613 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 11614 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 11615 11616 // Explicit instantiation of a class template specialization 11617 DeclResult ActOnExplicitInstantiation( 11618 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 11619 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 11620 TemplateTy Template, SourceLocation TemplateNameLoc, 11621 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, 11622 SourceLocation RAngleLoc, const ParsedAttributesView &Attr); 11623 11624 // Explicit instantiation of a member class of a class template. 11625 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 11626 SourceLocation TemplateLoc, 11627 unsigned TagSpec, SourceLocation KWLoc, 11628 CXXScopeSpec &SS, IdentifierInfo *Name, 11629 SourceLocation NameLoc, 11630 const ParsedAttributesView &Attr); 11631 11632 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 11633 SourceLocation TemplateLoc, 11634 Declarator &D); 11635 11636 /// If the given template parameter has a default template 11637 /// argument, substitute into that default template argument and 11638 /// return the corresponding template argument. 11639 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable( 11640 TemplateDecl *Template, SourceLocation TemplateLoc, 11641 SourceLocation RAngleLoc, Decl *Param, 11642 ArrayRef<TemplateArgument> SugaredConverted, 11643 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg); 11644 11645 /// Returns the top most location responsible for the definition of \p N. 11646 /// If \p N is a a template specialization, this is the location 11647 /// of the top of the instantiation stack. 11648 /// Otherwise, the location of \p N is returned. 11649 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const; 11650 11651 /// Specifies the context in which a particular template 11652 /// argument is being checked. 11653 enum CheckTemplateArgumentKind { 11654 /// The template argument was specified in the code or was 11655 /// instantiated with some deduced template arguments. 11656 CTAK_Specified, 11657 11658 /// The template argument was deduced via template argument 11659 /// deduction. 11660 CTAK_Deduced, 11661 11662 /// The template argument was deduced from an array bound 11663 /// via template argument deduction. 11664 CTAK_DeducedFromArrayBound 11665 }; 11666 11667 struct CheckTemplateArgumentInfo { 11668 explicit CheckTemplateArgumentInfo(bool PartialOrdering = false, 11669 bool MatchingTTP = false) 11670 : PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {} 11671 CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete; 11672 CheckTemplateArgumentInfo & 11673 operator=(const CheckTemplateArgumentInfo &) = delete; 11674 11675 /// The checked, converted argument will be added to the 11676 /// end of these vectors. 11677 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 11678 11679 /// The check is being performed in the context of partial ordering. 11680 bool PartialOrdering; 11681 11682 /// If true, assume these template arguments are 11683 /// the injected template arguments for a template template parameter. 11684 /// This will relax the requirement that all its possible uses are valid: 11685 /// TTP checking is loose, and assumes that invalid uses will be diagnosed 11686 /// during instantiation. 11687 bool MatchingTTP; 11688 11689 /// Is set to true when, in the context of TTP matching, a pack parameter 11690 /// matches non-pack arguments. 11691 bool MatchedPackOnParmToNonPackOnArg = false; 11692 }; 11693 11694 /// Check that the given template argument corresponds to the given 11695 /// template parameter. 11696 /// 11697 /// \param Param The template parameter against which the argument will be 11698 /// checked. 11699 /// 11700 /// \param Arg The template argument, which may be updated due to conversions. 11701 /// 11702 /// \param Template The template in which the template argument resides. 11703 /// 11704 /// \param TemplateLoc The location of the template name for the template 11705 /// whose argument list we're matching. 11706 /// 11707 /// \param RAngleLoc The location of the right angle bracket ('>') that closes 11708 /// the template argument list. 11709 /// 11710 /// \param ArgumentPackIndex The index into the argument pack where this 11711 /// argument will be placed. Only valid if the parameter is a parameter pack. 11712 /// 11713 /// \param CTAK Describes how we arrived at this particular template argument: 11714 /// explicitly written, deduced, etc. 11715 /// 11716 /// \returns true on error, false otherwise. 11717 bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, 11718 NamedDecl *Template, SourceLocation TemplateLoc, 11719 SourceLocation RAngleLoc, 11720 unsigned ArgumentPackIndex, 11721 CheckTemplateArgumentInfo &CTAI, 11722 CheckTemplateArgumentKind CTAK); 11723 11724 /// Check that the given template arguments can be provided to 11725 /// the given template, converting the arguments along the way. 11726 /// 11727 /// \param Template The template to which the template arguments are being 11728 /// provided. 11729 /// 11730 /// \param TemplateLoc The location of the template name in the source. 11731 /// 11732 /// \param TemplateArgs The list of template arguments. If the template is 11733 /// a template template parameter, this function may extend the set of 11734 /// template arguments to also include substituted, defaulted template 11735 /// arguments. 11736 /// 11737 /// \param PartialTemplateArgs True if the list of template arguments is 11738 /// intentionally partial, e.g., because we're checking just the initial 11739 /// set of template arguments. 11740 /// 11741 /// \param Converted Will receive the converted, canonicalized template 11742 /// arguments. 11743 /// 11744 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to 11745 /// contain the converted forms of the template arguments as written. 11746 /// Otherwise, \p TemplateArgs will not be modified. 11747 /// 11748 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will 11749 /// receive true if the cause for the error is the associated constraints of 11750 /// the template not being satisfied by the template arguments. 11751 /// 11752 /// \param DefaultArgs any default arguments from template specialization 11753 /// deduction. 11754 /// 11755 /// \returns true if an error occurred, false otherwise. 11756 bool CheckTemplateArgumentList(TemplateDecl *Template, 11757 SourceLocation TemplateLoc, 11758 TemplateArgumentListInfo &TemplateArgs, 11759 const DefaultArguments &DefaultArgs, 11760 bool PartialTemplateArgs, 11761 CheckTemplateArgumentInfo &CTAI, 11762 bool UpdateArgsWithConversions = true, 11763 bool *ConstraintsNotSatisfied = nullptr); 11764 11765 bool CheckTemplateTypeArgument( 11766 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, 11767 SmallVectorImpl<TemplateArgument> &SugaredConverted, 11768 SmallVectorImpl<TemplateArgument> &CanonicalConverted); 11769 11770 /// Check a template argument against its corresponding 11771 /// template type parameter. 11772 /// 11773 /// This routine implements the semantics of C++ [temp.arg.type]. It 11774 /// returns true if an error occurred, and false otherwise. 11775 bool CheckTemplateArgument(TypeSourceInfo *Arg); 11776 11777 /// Check a template argument against its corresponding 11778 /// non-type template parameter. 11779 /// 11780 /// This routine implements the semantics of C++ [temp.arg.nontype]. 11781 /// If an error occurred, it returns ExprError(); otherwise, it 11782 /// returns the converted template argument. \p ParamType is the 11783 /// type of the non-type template parameter after it has been instantiated. 11784 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 11785 QualType InstantiatedParamType, Expr *Arg, 11786 TemplateArgument &SugaredConverted, 11787 TemplateArgument &CanonicalConverted, 11788 bool MatchingTTP, 11789 CheckTemplateArgumentKind CTAK); 11790 11791 /// Check a template argument against its corresponding 11792 /// template template parameter. 11793 /// 11794 /// This routine implements the semantics of C++ [temp.arg.template]. 11795 /// It returns true if an error occurred, and false otherwise. 11796 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 11797 TemplateParameterList *Params, 11798 TemplateArgumentLoc &Arg, 11799 bool PartialOrdering, 11800 bool *MatchedPackOnParmToNonPackOnArg); 11801 11802 void NoteTemplateLocation(const NamedDecl &Decl, 11803 std::optional<SourceRange> ParamRange = {}); 11804 void NoteTemplateParameterLocation(const NamedDecl &Decl); 11805 11806 /// Given a non-type template argument that refers to a 11807 /// declaration and the type of its corresponding non-type template 11808 /// parameter, produce an expression that properly refers to that 11809 /// declaration. 11810 /// FIXME: This is used in some contexts where the resulting expression 11811 /// doesn't need to live too long. It would be useful if this function 11812 /// could return a temporary expression. 11813 ExprResult BuildExpressionFromDeclTemplateArgument( 11814 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, 11815 NamedDecl *TemplateParam = nullptr); 11816 ExprResult 11817 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, 11818 SourceLocation Loc); 11819 11820 /// Enumeration describing how template parameter lists are compared 11821 /// for equality. 11822 enum TemplateParameterListEqualKind { 11823 /// We are matching the template parameter lists of two templates 11824 /// that might be redeclarations. 11825 /// 11826 /// \code 11827 /// template<typename T> struct X; 11828 /// template<typename T> struct X; 11829 /// \endcode 11830 TPL_TemplateMatch, 11831 11832 /// We are matching the template parameter lists of two template 11833 /// template parameters as part of matching the template parameter lists 11834 /// of two templates that might be redeclarations. 11835 /// 11836 /// \code 11837 /// template<template<int I> class TT> struct X; 11838 /// template<template<int Value> class Other> struct X; 11839 /// \endcode 11840 TPL_TemplateTemplateParmMatch, 11841 11842 /// We are determining whether the template-parameters are equivalent 11843 /// according to C++ [temp.over.link]/6. This comparison does not consider 11844 /// constraints. 11845 /// 11846 /// \code 11847 /// template<C1 T> void f(T); 11848 /// template<C2 T> void f(T); 11849 /// \endcode 11850 TPL_TemplateParamsEquivalent, 11851 }; 11852 11853 // A struct to represent the 'new' declaration, which is either itself just 11854 // the named decl, or the important information we need about it in order to 11855 // do constraint comparisons. 11856 class TemplateCompareNewDeclInfo { 11857 const NamedDecl *ND = nullptr; 11858 const DeclContext *DC = nullptr; 11859 const DeclContext *LexicalDC = nullptr; 11860 SourceLocation Loc; 11861 11862 public: 11863 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {} 11864 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, 11865 const DeclContext *LexicalDeclCtx, 11866 SourceLocation Loc) 11867 11868 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) { 11869 assert(DC && LexicalDC && 11870 "Constructor only for cases where we have the information to put " 11871 "in here"); 11872 } 11873 11874 // If this was constructed with no information, we cannot do substitution 11875 // for constraint comparison, so make sure we can check that. 11876 bool isInvalid() const { return !ND && !DC; } 11877 11878 const NamedDecl *getDecl() const { return ND; } 11879 11880 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; } 11881 11882 const DeclContext *getLexicalDeclContext() const { 11883 return ND ? ND->getLexicalDeclContext() : LexicalDC; 11884 } 11885 11886 const DeclContext *getDeclContext() const { 11887 return ND ? ND->getDeclContext() : DC; 11888 } 11889 11890 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; } 11891 }; 11892 11893 /// Determine whether the given template parameter lists are 11894 /// equivalent. 11895 /// 11896 /// \param New The new template parameter list, typically written in the 11897 /// source code as part of a new template declaration. 11898 /// 11899 /// \param Old The old template parameter list, typically found via 11900 /// name lookup of the template declared with this template parameter 11901 /// list. 11902 /// 11903 /// \param Complain If true, this routine will produce a diagnostic if 11904 /// the template parameter lists are not equivalent. 11905 /// 11906 /// \param Kind describes how we are to match the template parameter lists. 11907 /// 11908 /// \param TemplateArgLoc If this source location is valid, then we 11909 /// are actually checking the template parameter list of a template 11910 /// argument (New) against the template parameter list of its 11911 /// corresponding template template parameter (Old). We produce 11912 /// slightly different diagnostics in this scenario. 11913 /// 11914 /// \returns True if the template parameter lists are equal, false 11915 /// otherwise. 11916 bool TemplateParameterListsAreEqual( 11917 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, 11918 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, 11919 TemplateParameterListEqualKind Kind, 11920 SourceLocation TemplateArgLoc = SourceLocation()); 11921 11922 bool TemplateParameterListsAreEqual( 11923 TemplateParameterList *New, TemplateParameterList *Old, bool Complain, 11924 TemplateParameterListEqualKind Kind, 11925 SourceLocation TemplateArgLoc = SourceLocation()) { 11926 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain, 11927 Kind, TemplateArgLoc); 11928 } 11929 11930 /// Check whether a template can be declared within this scope. 11931 /// 11932 /// If the template declaration is valid in this scope, returns 11933 /// false. Otherwise, issues a diagnostic and returns true. 11934 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 11935 11936 /// Called when the parser has parsed a C++ typename 11937 /// specifier, e.g., "typename T::type". 11938 /// 11939 /// \param S The scope in which this typename type occurs. 11940 /// \param TypenameLoc the location of the 'typename' keyword 11941 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 11942 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 11943 /// \param IdLoc the location of the identifier. 11944 /// \param IsImplicitTypename context where T::type refers to a type. 11945 TypeResult ActOnTypenameType( 11946 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, 11947 const IdentifierInfo &II, SourceLocation IdLoc, 11948 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No); 11949 11950 /// Called when the parser has parsed a C++ typename 11951 /// specifier that ends in a template-id, e.g., 11952 /// "typename MetaFun::template apply<T1, T2>". 11953 /// 11954 /// \param S The scope in which this typename type occurs. 11955 /// \param TypenameLoc the location of the 'typename' keyword 11956 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 11957 /// \param TemplateLoc the location of the 'template' keyword, if any. 11958 /// \param TemplateName The template name. 11959 /// \param TemplateII The identifier used to name the template. 11960 /// \param TemplateIILoc The location of the template name. 11961 /// \param LAngleLoc The location of the opening angle bracket ('<'). 11962 /// \param TemplateArgs The template arguments. 11963 /// \param RAngleLoc The location of the closing angle bracket ('>'). 11964 TypeResult 11965 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 11966 const CXXScopeSpec &SS, SourceLocation TemplateLoc, 11967 TemplateTy TemplateName, const IdentifierInfo *TemplateII, 11968 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 11969 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); 11970 11971 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 11972 SourceLocation KeywordLoc, 11973 NestedNameSpecifierLoc QualifierLoc, 11974 const IdentifierInfo &II, SourceLocation IILoc, 11975 TypeSourceInfo **TSI, bool DeducedTSTContext); 11976 11977 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 11978 SourceLocation KeywordLoc, 11979 NestedNameSpecifierLoc QualifierLoc, 11980 const IdentifierInfo &II, SourceLocation IILoc, 11981 bool DeducedTSTContext = true); 11982 11983 /// Rebuilds a type within the context of the current instantiation. 11984 /// 11985 /// The type \p T is part of the type of an out-of-line member definition of 11986 /// a class template (or class template partial specialization) that was 11987 /// parsed and constructed before we entered the scope of the class template 11988 /// (or partial specialization thereof). This routine will rebuild that type 11989 /// now that we have entered the declarator's scope, which may produce 11990 /// different canonical types, e.g., 11991 /// 11992 /// \code 11993 /// template<typename T> 11994 /// struct X { 11995 /// typedef T* pointer; 11996 /// pointer data(); 11997 /// }; 11998 /// 11999 /// template<typename T> 12000 /// typename X<T>::pointer X<T>::data() { ... } 12001 /// \endcode 12002 /// 12003 /// Here, the type "typename X<T>::pointer" will be created as a 12004 /// DependentNameType, since we do not know that we can look into X<T> when we 12005 /// parsed the type. This function will rebuild the type, performing the 12006 /// lookup of "pointer" in X<T> and returning an ElaboratedType whose 12007 /// canonical type is the same as the canonical type of T*, allowing the 12008 /// return types of the out-of-line definition and the declaration to match. 12009 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 12010 SourceLocation Loc, 12011 DeclarationName Name); 12012 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 12013 12014 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 12015 12016 /// Rebuild the template parameters now that we know we're in a current 12017 /// instantiation. 12018 bool 12019 RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params); 12020 12021 /// Produces a formatted string that describes the binding of 12022 /// template parameters to template arguments. 12023 std::string 12024 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 12025 const TemplateArgumentList &Args); 12026 12027 std::string 12028 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 12029 const TemplateArgument *Args, 12030 unsigned NumArgs); 12031 12032 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 12033 SourceLocation Less, 12034 SourceLocation Greater); 12035 12036 /// ActOnDependentIdExpression - Handle a dependent id-expression that 12037 /// was just parsed. This is only possible with an explicit scope 12038 /// specifier naming a dependent type. 12039 ExprResult ActOnDependentIdExpression( 12040 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 12041 const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, 12042 const TemplateArgumentListInfo *TemplateArgs); 12043 12044 ExprResult 12045 BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 12046 SourceLocation TemplateKWLoc, 12047 const DeclarationNameInfo &NameInfo, 12048 const TemplateArgumentListInfo *TemplateArgs); 12049 12050 // Calculates whether the expression Constraint depends on an enclosing 12051 // template, for the purposes of [temp.friend] p9. 12052 // TemplateDepth is the 'depth' of the friend function, which is used to 12053 // compare whether a declaration reference is referring to a containing 12054 // template, or just the current friend function. A 'lower' TemplateDepth in 12055 // the AST refers to a 'containing' template. As the constraint is 12056 // uninstantiated, this is relative to the 'top' of the TU. 12057 bool 12058 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, 12059 unsigned TemplateDepth, 12060 const Expr *Constraint); 12061 12062 /// Find the failed Boolean condition within a given Boolean 12063 /// constant expression, and describe it with a string. 12064 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); 12065 12066 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); 12067 12068 ConceptDecl *ActOnStartConceptDefinition( 12069 Scope *S, MultiTemplateParamsArg TemplateParameterLists, 12070 const IdentifierInfo *Name, SourceLocation NameLoc); 12071 12072 ConceptDecl *ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, 12073 Expr *ConstraintExpr, 12074 const ParsedAttributesView &Attrs); 12075 12076 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, 12077 bool &AddToScope); 12078 bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc); 12079 12080 TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 12081 const CXXScopeSpec &SS, 12082 const IdentifierInfo *Name, 12083 SourceLocation TagLoc, SourceLocation NameLoc); 12084 12085 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 12086 CachedTokens &Toks); 12087 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 12088 bool IsInsideALocalClassWithinATemplateFunction(); 12089 12090 /// We've found a use of a templated declaration that would trigger an 12091 /// implicit instantiation. Check that any relevant explicit specializations 12092 /// and partial specializations are visible/reachable, and diagnose if not. 12093 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); 12094 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec); 12095 12096 ///@} 12097 12098 // 12099 // 12100 // ------------------------------------------------------------------------- 12101 // 12102 // 12103 12104 /// \name C++ Template Argument Deduction 12105 /// Implementations are in SemaTemplateDeduction.cpp 12106 ///@{ 12107 12108 public: 12109 /// When true, access checking violations are treated as SFINAE 12110 /// failures rather than hard errors. 12111 bool AccessCheckingSFINAE; 12112 12113 /// RAII class used to determine whether SFINAE has 12114 /// trapped any errors that occur during template argument 12115 /// deduction. 12116 class SFINAETrap { 12117 Sema &SemaRef; 12118 unsigned PrevSFINAEErrors; 12119 bool PrevInNonInstantiationSFINAEContext; 12120 bool PrevAccessCheckingSFINAE; 12121 bool PrevLastDiagnosticIgnored; 12122 12123 public: 12124 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 12125 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 12126 PrevInNonInstantiationSFINAEContext( 12127 SemaRef.InNonInstantiationSFINAEContext), 12128 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), 12129 PrevLastDiagnosticIgnored( 12130 SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { 12131 if (!SemaRef.isSFINAEContext()) 12132 SemaRef.InNonInstantiationSFINAEContext = true; 12133 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 12134 } 12135 12136 ~SFINAETrap() { 12137 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 12138 SemaRef.InNonInstantiationSFINAEContext = 12139 PrevInNonInstantiationSFINAEContext; 12140 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 12141 SemaRef.getDiagnostics().setLastDiagnosticIgnored( 12142 PrevLastDiagnosticIgnored); 12143 } 12144 12145 /// Determine whether any SFINAE errors have been trapped. 12146 bool hasErrorOccurred() const { 12147 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 12148 } 12149 }; 12150 12151 /// RAII class used to indicate that we are performing provisional 12152 /// semantic analysis to determine the validity of a construct, so 12153 /// typo-correction and diagnostics in the immediate context (not within 12154 /// implicitly-instantiated templates) should be suppressed. 12155 class TentativeAnalysisScope { 12156 Sema &SemaRef; 12157 // FIXME: Using a SFINAETrap for this is a hack. 12158 SFINAETrap Trap; 12159 bool PrevDisableTypoCorrection; 12160 12161 public: 12162 explicit TentativeAnalysisScope(Sema &SemaRef) 12163 : SemaRef(SemaRef), Trap(SemaRef, true), 12164 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 12165 SemaRef.DisableTypoCorrection = true; 12166 } 12167 ~TentativeAnalysisScope() { 12168 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 12169 } 12170 }; 12171 12172 /// For each declaration that involved template argument deduction, the 12173 /// set of diagnostics that were suppressed during that template argument 12174 /// deduction. 12175 /// 12176 /// FIXME: Serialize this structure to the AST file. 12177 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1>> 12178 SuppressedDiagnosticsMap; 12179 SuppressedDiagnosticsMap SuppressedDiagnostics; 12180 12181 /// Compare types for equality with respect to possibly compatible 12182 /// function types (noreturn adjustment, implicit calling conventions). If any 12183 /// of parameter and argument is not a function, just perform type comparison. 12184 /// 12185 /// \param P the template parameter type. 12186 /// 12187 /// \param A the argument type. 12188 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg); 12189 12190 /// Allocate a TemplateArgumentLoc where all locations have 12191 /// been initialized to the given location. 12192 /// 12193 /// \param Arg The template argument we are producing template argument 12194 /// location information for. 12195 /// 12196 /// \param NTTPType For a declaration template argument, the type of 12197 /// the non-type template parameter that corresponds to this template 12198 /// argument. Can be null if no type sugar is available to add to the 12199 /// type from the template argument. 12200 /// 12201 /// \param Loc The source location to use for the resulting template 12202 /// argument. 12203 TemplateArgumentLoc 12204 getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, 12205 SourceLocation Loc, 12206 NamedDecl *TemplateParam = nullptr); 12207 12208 /// Get a template argument mapping the given template parameter to itself, 12209 /// e.g. for X in \c template<int X>, this would return an expression template 12210 /// argument referencing X. 12211 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, 12212 SourceLocation Location); 12213 12214 /// Adjust the type \p ArgFunctionType to match the calling convention, 12215 /// noreturn, and optionally the exception specification of \p FunctionType. 12216 /// Deduction often wants to ignore these properties when matching function 12217 /// types. 12218 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, 12219 bool AdjustExceptionSpec = false); 12220 12221 TemplateDeductionResult 12222 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 12223 ArrayRef<TemplateArgument> TemplateArgs, 12224 sema::TemplateDeductionInfo &Info); 12225 12226 TemplateDeductionResult 12227 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 12228 ArrayRef<TemplateArgument> TemplateArgs, 12229 sema::TemplateDeductionInfo &Info); 12230 12231 /// Deduce the template arguments of the given template from \p FromType. 12232 /// Used to implement the IsDeducible constraint for alias CTAD per C++ 12233 /// [over.match.class.deduct]p4. 12234 /// 12235 /// It only supports class or type alias templates. 12236 TemplateDeductionResult 12237 DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, 12238 sema::TemplateDeductionInfo &Info); 12239 12240 TemplateDeductionResult DeduceTemplateArguments( 12241 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps, 12242 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info, 12243 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 12244 bool NumberOfArgumentsMustMatch); 12245 12246 /// Substitute the explicitly-provided template arguments into the 12247 /// given function template according to C++ [temp.arg.explicit]. 12248 /// 12249 /// \param FunctionTemplate the function template into which the explicit 12250 /// template arguments will be substituted. 12251 /// 12252 /// \param ExplicitTemplateArgs the explicitly-specified template 12253 /// arguments. 12254 /// 12255 /// \param Deduced the deduced template arguments, which will be populated 12256 /// with the converted and checked explicit template arguments. 12257 /// 12258 /// \param ParamTypes will be populated with the instantiated function 12259 /// parameters. 12260 /// 12261 /// \param FunctionType if non-NULL, the result type of the function template 12262 /// will also be instantiated and the pointed-to value will be updated with 12263 /// the instantiated function type. 12264 /// 12265 /// \param Info if substitution fails for any reason, this object will be 12266 /// populated with more information about the failure. 12267 /// 12268 /// \returns TemplateDeductionResult::Success if substitution was successful, 12269 /// or some failure condition. 12270 TemplateDeductionResult SubstituteExplicitTemplateArguments( 12271 FunctionTemplateDecl *FunctionTemplate, 12272 TemplateArgumentListInfo &ExplicitTemplateArgs, 12273 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 12274 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 12275 sema::TemplateDeductionInfo &Info); 12276 12277 /// brief A function argument from which we performed template argument 12278 // deduction for a call. 12279 struct OriginalCallArg { 12280 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, 12281 unsigned ArgIdx, QualType OriginalArgType) 12282 : OriginalParamType(OriginalParamType), 12283 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), 12284 OriginalArgType(OriginalArgType) {} 12285 12286 QualType OriginalParamType; 12287 bool DecomposedParam; 12288 unsigned ArgIdx; 12289 QualType OriginalArgType; 12290 }; 12291 12292 /// Finish template argument deduction for a function template, 12293 /// checking the deduced template arguments for completeness and forming 12294 /// the function template specialization. 12295 /// 12296 /// \param OriginalCallArgs If non-NULL, the original call arguments against 12297 /// which the deduced argument types should be compared. 12298 TemplateDeductionResult FinishTemplateArgumentDeduction( 12299 FunctionTemplateDecl *FunctionTemplate, 12300 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 12301 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 12302 sema::TemplateDeductionInfo &Info, 12303 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs, 12304 bool PartialOverloading, bool PartialOrdering, 12305 llvm::function_ref<bool()> CheckNonDependent = [] { return false; }); 12306 12307 /// Perform template argument deduction from a function call 12308 /// (C++ [temp.deduct.call]). 12309 /// 12310 /// \param FunctionTemplate the function template for which we are performing 12311 /// template argument deduction. 12312 /// 12313 /// \param ExplicitTemplateArgs the explicit template arguments provided 12314 /// for this call. 12315 /// 12316 /// \param Args the function call arguments 12317 /// 12318 /// \param Specialization if template argument deduction was successful, 12319 /// this will be set to the function template specialization produced by 12320 /// template argument deduction. 12321 /// 12322 /// \param Info the argument will be updated to provide additional information 12323 /// about template argument deduction. 12324 /// 12325 /// \param CheckNonDependent A callback to invoke to check conversions for 12326 /// non-dependent parameters, between deduction and substitution, per DR1391. 12327 /// If this returns true, substitution will be skipped and we return 12328 /// TemplateDeductionResult::NonDependentConversionFailure. The callback is 12329 /// passed the parameter types (after substituting explicit template 12330 /// arguments). 12331 /// 12332 /// \returns the result of template argument deduction. 12333 TemplateDeductionResult DeduceTemplateArguments( 12334 FunctionTemplateDecl *FunctionTemplate, 12335 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 12336 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, 12337 bool PartialOverloading, bool AggregateDeductionCandidate, 12338 bool PartialOrdering, QualType ObjectType, 12339 Expr::Classification ObjectClassification, 12340 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); 12341 12342 /// Deduce template arguments when taking the address of a function 12343 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to 12344 /// a template. 12345 /// 12346 /// \param FunctionTemplate the function template for which we are performing 12347 /// template argument deduction. 12348 /// 12349 /// \param ExplicitTemplateArgs the explicitly-specified template 12350 /// arguments. 12351 /// 12352 /// \param ArgFunctionType the function type that will be used as the 12353 /// "argument" type (A) when performing template argument deduction from the 12354 /// function template's function type. This type may be NULL, if there is no 12355 /// argument type to compare against, in C++0x [temp.arg.explicit]p3. 12356 /// 12357 /// \param Specialization if template argument deduction was successful, 12358 /// this will be set to the function template specialization produced by 12359 /// template argument deduction. 12360 /// 12361 /// \param Info the argument will be updated to provide additional information 12362 /// about template argument deduction. 12363 /// 12364 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking 12365 /// the address of a function template per [temp.deduct.funcaddr] and 12366 /// [over.over]. If \c false, we are looking up a function template 12367 /// specialization based on its signature, per [temp.deduct.decl]. 12368 /// 12369 /// \returns the result of template argument deduction. 12370 TemplateDeductionResult DeduceTemplateArguments( 12371 FunctionTemplateDecl *FunctionTemplate, 12372 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, 12373 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, 12374 bool IsAddressOfFunction = false); 12375 12376 /// Deduce template arguments for a templated conversion 12377 /// function (C++ [temp.deduct.conv]) and, if successful, produce a 12378 /// conversion function template specialization. 12379 TemplateDeductionResult DeduceTemplateArguments( 12380 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType, 12381 Expr::Classification ObjectClassification, QualType ToType, 12382 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); 12383 12384 /// Deduce template arguments for a function template when there is 12385 /// nothing to deduce against (C++0x [temp.arg.explicit]p3). 12386 /// 12387 /// \param FunctionTemplate the function template for which we are performing 12388 /// template argument deduction. 12389 /// 12390 /// \param ExplicitTemplateArgs the explicitly-specified template 12391 /// arguments. 12392 /// 12393 /// \param Specialization if template argument deduction was successful, 12394 /// this will be set to the function template specialization produced by 12395 /// template argument deduction. 12396 /// 12397 /// \param Info the argument will be updated to provide additional information 12398 /// about template argument deduction. 12399 /// 12400 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking 12401 /// the address of a function template in a context where we do not have a 12402 /// target type, per [over.over]. If \c false, we are looking up a function 12403 /// template specialization based on its signature, which only happens when 12404 /// deducing a function parameter type from an argument that is a template-id 12405 /// naming a function template specialization. 12406 /// 12407 /// \returns the result of template argument deduction. 12408 TemplateDeductionResult 12409 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 12410 TemplateArgumentListInfo *ExplicitTemplateArgs, 12411 FunctionDecl *&Specialization, 12412 sema::TemplateDeductionInfo &Info, 12413 bool IsAddressOfFunction = false); 12414 12415 /// Substitute Replacement for \p auto in \p TypeWithAuto 12416 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 12417 /// Substitute Replacement for auto in TypeWithAuto 12418 TypeSourceInfo *SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 12419 QualType Replacement); 12420 12421 // Substitute auto in TypeWithAuto for a Dependent auto type 12422 QualType SubstAutoTypeDependent(QualType TypeWithAuto); 12423 12424 // Substitute auto in TypeWithAuto for a Dependent auto type 12425 TypeSourceInfo * 12426 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto); 12427 12428 /// Completely replace the \c auto in \p TypeWithAuto by 12429 /// \p Replacement. This does not retain any \c auto type sugar. 12430 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); 12431 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 12432 QualType Replacement); 12433 12434 /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6) 12435 /// 12436 /// Note that this is done even if the initializer is dependent. (This is 12437 /// necessary to support partial ordering of templates using 'auto'.) 12438 /// A dependent type will be produced when deducing from a dependent type. 12439 /// 12440 /// \param Type the type pattern using the auto type-specifier. 12441 /// \param Init the initializer for the variable whose type is to be deduced. 12442 /// \param Result if type deduction was successful, this will be set to the 12443 /// deduced type. 12444 /// \param Info the argument will be updated to provide additional information 12445 /// about template argument deduction. 12446 /// \param DependentDeduction Set if we should permit deduction in 12447 /// dependent cases. This is necessary for template partial ordering 12448 /// with 'auto' template parameters. The template parameter depth to be 12449 /// used should be specified in the 'Info' parameter. 12450 /// \param IgnoreConstraints Set if we should not fail if the deduced type 12451 /// does not satisfy the type-constraint in the auto 12452 /// type. 12453 TemplateDeductionResult 12454 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, 12455 sema::TemplateDeductionInfo &Info, 12456 bool DependentDeduction = false, 12457 bool IgnoreConstraints = false, 12458 TemplateSpecCandidateSet *FailedTSC = nullptr); 12459 void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init); 12460 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 12461 bool Diagnose = true); 12462 12463 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, 12464 SourceLocation Loc); 12465 12466 /// Returns the more specialized class template partial specialization 12467 /// according to the rules of partial ordering of class template partial 12468 /// specializations (C++ [temp.class.order]). 12469 /// 12470 /// \param PS1 the first class template partial specialization 12471 /// 12472 /// \param PS2 the second class template partial specialization 12473 /// 12474 /// \returns the more specialized class template partial specialization. If 12475 /// neither partial specialization is more specialized, returns NULL. 12476 ClassTemplatePartialSpecializationDecl * 12477 getMoreSpecializedPartialSpecialization( 12478 ClassTemplatePartialSpecializationDecl *PS1, 12479 ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 12480 12481 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, 12482 sema::TemplateDeductionInfo &Info); 12483 12484 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 12485 VarTemplatePartialSpecializationDecl *PS1, 12486 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 12487 12488 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, 12489 sema::TemplateDeductionInfo &Info); 12490 12491 bool isTemplateTemplateParameterAtLeastAsSpecializedAs( 12492 TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, 12493 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, 12494 bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg); 12495 12496 /// Mark which template parameters are used in a given expression. 12497 /// 12498 /// \param E the expression from which template parameters will be deduced. 12499 /// 12500 /// \param Used a bit vector whose elements will be set to \c true 12501 /// to indicate when the corresponding template parameter will be 12502 /// deduced. 12503 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 12504 unsigned Depth, llvm::SmallBitVector &Used); 12505 12506 /// Mark which template parameters can be deduced from a given 12507 /// template argument list. 12508 /// 12509 /// \param TemplateArgs the template argument list from which template 12510 /// parameters will be deduced. 12511 /// 12512 /// \param Used a bit vector whose elements will be set to \c true 12513 /// to indicate when the corresponding template parameter will be 12514 /// deduced. 12515 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 12516 bool OnlyDeduced, unsigned Depth, 12517 llvm::SmallBitVector &Used); 12518 void 12519 MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, 12520 llvm::SmallBitVector &Deduced) { 12521 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 12522 } 12523 12524 /// Marks all of the template parameters that will be deduced by a 12525 /// call to the given function template. 12526 static void 12527 MarkDeducedTemplateParameters(ASTContext &Ctx, 12528 const FunctionTemplateDecl *FunctionTemplate, 12529 llvm::SmallBitVector &Deduced); 12530 12531 /// Returns the more specialized function template according 12532 /// to the rules of function template partial ordering (C++ 12533 /// [temp.func.order]). 12534 /// 12535 /// \param FT1 the first function template 12536 /// 12537 /// \param FT2 the second function template 12538 /// 12539 /// \param TPOC the context in which we are performing partial ordering of 12540 /// function templates. 12541 /// 12542 /// \param NumCallArguments1 The number of arguments in the call to FT1, used 12543 /// only when \c TPOC is \c TPOC_Call. Does not include the object argument 12544 /// when calling a member function. 12545 /// 12546 /// \param RawObj1Ty The type of the object parameter of FT1 if a member 12547 /// function only used if \c TPOC is \c TPOC_Call and FT1 is a Function 12548 /// template from a member function 12549 /// 12550 /// \param RawObj2Ty The type of the object parameter of FT2 if a member 12551 /// function only used if \c TPOC is \c TPOC_Call and FT2 is a Function 12552 /// template from a member function 12553 /// 12554 /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload 12555 /// candidate with a reversed parameter order. In this case, the corresponding 12556 /// P/A pairs between FT1 and FT2 are reversed. 12557 /// 12558 /// \returns the more specialized function template. If neither 12559 /// template is more specialized, returns NULL. 12560 FunctionTemplateDecl *getMoreSpecializedTemplate( 12561 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, 12562 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, 12563 QualType RawObj1Ty = {}, QualType RawObj2Ty = {}, bool Reversed = false); 12564 12565 /// Retrieve the most specialized of the given function template 12566 /// specializations. 12567 /// 12568 /// \param SpecBegin the start iterator of the function template 12569 /// specializations that we will be comparing. 12570 /// 12571 /// \param SpecEnd the end iterator of the function template 12572 /// specializations, paired with \p SpecBegin. 12573 /// 12574 /// \param Loc the location where the ambiguity or no-specializations 12575 /// diagnostic should occur. 12576 /// 12577 /// \param NoneDiag partial diagnostic used to diagnose cases where there are 12578 /// no matching candidates. 12579 /// 12580 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one 12581 /// occurs. 12582 /// 12583 /// \param CandidateDiag partial diagnostic used for each function template 12584 /// specialization that is a candidate in the ambiguous ordering. One 12585 /// parameter in this diagnostic should be unbound, which will correspond to 12586 /// the string describing the template arguments for the function template 12587 /// specialization. 12588 /// 12589 /// \returns the most specialized function template specialization, if 12590 /// found. Otherwise, returns SpecEnd. 12591 UnresolvedSetIterator 12592 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 12593 TemplateSpecCandidateSet &FailedCandidates, 12594 SourceLocation Loc, const PartialDiagnostic &NoneDiag, 12595 const PartialDiagnostic &AmbigDiag, 12596 const PartialDiagnostic &CandidateDiag, 12597 bool Complain = true, QualType TargetType = QualType()); 12598 12599 /// Returns the more constrained function according to the rules of 12600 /// partial ordering by constraints (C++ [temp.constr.order]). 12601 /// 12602 /// \param FD1 the first function 12603 /// 12604 /// \param FD2 the second function 12605 /// 12606 /// \returns the more constrained function. If neither function is 12607 /// more constrained, returns NULL. 12608 FunctionDecl *getMoreConstrainedFunction(FunctionDecl *FD1, 12609 FunctionDecl *FD2); 12610 12611 ///@} 12612 12613 // 12614 // 12615 // ------------------------------------------------------------------------- 12616 // 12617 // 12618 12619 /// \name C++ Template Deduction Guide 12620 /// Implementations are in SemaTemplateDeductionGuide.cpp 12621 ///@{ 12622 12623 /// Declare implicit deduction guides for a class template if we've 12624 /// not already done so. 12625 void DeclareImplicitDeductionGuides(TemplateDecl *Template, 12626 SourceLocation Loc); 12627 12628 FunctionTemplateDecl *DeclareAggregateDeductionGuideFromInitList( 12629 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes, 12630 SourceLocation Loc); 12631 12632 ///@} 12633 12634 // 12635 // 12636 // ------------------------------------------------------------------------- 12637 // 12638 // 12639 12640 /// \name C++ Template Instantiation 12641 /// Implementations are in SemaTemplateInstantiate.cpp 12642 ///@{ 12643 12644 public: 12645 /// A helper class for building up ExtParameterInfos. 12646 class ExtParameterInfoBuilder { 12647 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; 12648 bool HasInteresting = false; 12649 12650 public: 12651 /// Set the ExtParameterInfo for the parameter at the given index, 12652 /// 12653 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { 12654 assert(Infos.size() <= index); 12655 Infos.resize(index); 12656 Infos.push_back(info); 12657 12658 if (!HasInteresting) 12659 HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); 12660 } 12661 12662 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the 12663 /// ExtParameterInfo array we've built up. 12664 const FunctionProtoType::ExtParameterInfo * 12665 getPointerOrNull(unsigned numParams) { 12666 if (!HasInteresting) 12667 return nullptr; 12668 Infos.resize(numParams); 12669 return Infos.data(); 12670 } 12671 }; 12672 12673 /// The current instantiation scope used to store local 12674 /// variables. 12675 LocalInstantiationScope *CurrentInstantiationScope; 12676 12677 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 12678 UnparsedDefaultArgInstantiationsMap; 12679 12680 /// A mapping from parameters with unparsed default arguments to the 12681 /// set of instantiations of each parameter. 12682 /// 12683 /// This mapping is a temporary data structure used when parsing 12684 /// nested class templates or nested classes of class templates, 12685 /// where we might end up instantiating an inner class before the 12686 /// default arguments of its methods have been parsed. 12687 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 12688 12689 /// A context in which code is being synthesized (where a source location 12690 /// alone is not sufficient to identify the context). This covers template 12691 /// instantiation and various forms of implicitly-generated functions. 12692 struct CodeSynthesisContext { 12693 /// The kind of template instantiation we are performing 12694 enum SynthesisKind { 12695 /// We are instantiating a template declaration. The entity is 12696 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 12697 TemplateInstantiation, 12698 12699 /// We are instantiating a default argument for a template 12700 /// parameter. The Entity is the template parameter whose argument is 12701 /// being instantiated, the Template is the template, and the 12702 /// TemplateArgs/NumTemplateArguments provide the template arguments as 12703 /// specified. 12704 DefaultTemplateArgumentInstantiation, 12705 12706 /// We are instantiating a default argument for a function. 12707 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 12708 /// provides the template arguments as specified. 12709 DefaultFunctionArgumentInstantiation, 12710 12711 /// We are substituting explicit template arguments provided for 12712 /// a function template. The entity is a FunctionTemplateDecl. 12713 ExplicitTemplateArgumentSubstitution, 12714 12715 /// We are substituting template argument determined as part of 12716 /// template argument deduction for either a class template 12717 /// partial specialization or a function template. The 12718 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or 12719 /// a TemplateDecl. 12720 DeducedTemplateArgumentSubstitution, 12721 12722 /// We are substituting into a lambda expression. 12723 LambdaExpressionSubstitution, 12724 12725 /// We are substituting prior template arguments into a new 12726 /// template parameter. The template parameter itself is either a 12727 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 12728 PriorTemplateArgumentSubstitution, 12729 12730 /// We are checking the validity of a default template argument that 12731 /// has been used when naming a template-id. 12732 DefaultTemplateArgumentChecking, 12733 12734 /// We are computing the exception specification for a defaulted special 12735 /// member function. 12736 ExceptionSpecEvaluation, 12737 12738 /// We are instantiating the exception specification for a function 12739 /// template which was deferred until it was needed. 12740 ExceptionSpecInstantiation, 12741 12742 /// We are instantiating a requirement of a requires expression. 12743 RequirementInstantiation, 12744 12745 /// We are checking the satisfaction of a nested requirement of a requires 12746 /// expression. 12747 NestedRequirementConstraintsCheck, 12748 12749 /// We are declaring an implicit special member function. 12750 DeclaringSpecialMember, 12751 12752 /// We are declaring an implicit 'operator==' for a defaulted 12753 /// 'operator<=>'. 12754 DeclaringImplicitEqualityComparison, 12755 12756 /// We are defining a synthesized function (such as a defaulted special 12757 /// member). 12758 DefiningSynthesizedFunction, 12759 12760 // We are checking the constraints associated with a constrained entity or 12761 // the constraint expression of a concept. This includes the checks that 12762 // atomic constraints have the type 'bool' and that they can be constant 12763 // evaluated. 12764 ConstraintsCheck, 12765 12766 // We are substituting template arguments into a constraint expression. 12767 ConstraintSubstitution, 12768 12769 // We are normalizing a constraint expression. 12770 ConstraintNormalization, 12771 12772 // Instantiating a Requires Expression parameter clause. 12773 RequirementParameterInstantiation, 12774 12775 // We are substituting into the parameter mapping of an atomic constraint 12776 // during normalization. 12777 ParameterMappingSubstitution, 12778 12779 /// We are rewriting a comparison operator in terms of an operator<=>. 12780 RewritingOperatorAsSpaceship, 12781 12782 /// We are initializing a structured binding. 12783 InitializingStructuredBinding, 12784 12785 /// We are marking a class as __dllexport. 12786 MarkingClassDllexported, 12787 12788 /// We are building an implied call from __builtin_dump_struct. The 12789 /// arguments are in CallArgs. 12790 BuildingBuiltinDumpStructCall, 12791 12792 /// Added for Template instantiation observation. 12793 /// Memoization means we are _not_ instantiating a template because 12794 /// it is already instantiated (but we entered a context where we 12795 /// would have had to if it was not already instantiated). 12796 Memoization, 12797 12798 /// We are building deduction guides for a class. 12799 BuildingDeductionGuides, 12800 12801 /// We are instantiating a type alias template declaration. 12802 TypeAliasTemplateInstantiation, 12803 12804 /// We are performing partial ordering for template template parameters. 12805 PartialOrderingTTP, 12806 } Kind; 12807 12808 /// Was the enclosing context a non-instantiation SFINAE context? 12809 bool SavedInNonInstantiationSFINAEContext; 12810 12811 /// The point of instantiation or synthesis within the source code. 12812 SourceLocation PointOfInstantiation; 12813 12814 /// The entity that is being synthesized. 12815 Decl *Entity; 12816 12817 /// The template (or partial specialization) in which we are 12818 /// performing the instantiation, for substitutions of prior template 12819 /// arguments. 12820 NamedDecl *Template; 12821 12822 union { 12823 /// The list of template arguments we are substituting, if they 12824 /// are not part of the entity. 12825 const TemplateArgument *TemplateArgs; 12826 12827 /// The list of argument expressions in a synthesized call. 12828 const Expr *const *CallArgs; 12829 }; 12830 12831 // FIXME: Wrap this union around more members, or perhaps store the 12832 // kind-specific members in the RAII object owning the context. 12833 union { 12834 /// The number of template arguments in TemplateArgs. 12835 unsigned NumTemplateArgs; 12836 12837 /// The number of expressions in CallArgs. 12838 unsigned NumCallArgs; 12839 12840 /// The special member being declared or defined. 12841 CXXSpecialMemberKind SpecialMember; 12842 }; 12843 12844 ArrayRef<TemplateArgument> template_arguments() const { 12845 assert(Kind != DeclaringSpecialMember); 12846 return {TemplateArgs, NumTemplateArgs}; 12847 } 12848 12849 /// The template deduction info object associated with the 12850 /// substitution or checking of explicit or deduced template arguments. 12851 sema::TemplateDeductionInfo *DeductionInfo; 12852 12853 /// The source range that covers the construct that cause 12854 /// the instantiation, e.g., the template-id that causes a class 12855 /// template instantiation. 12856 SourceRange InstantiationRange; 12857 12858 CodeSynthesisContext() 12859 : Kind(TemplateInstantiation), 12860 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), 12861 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), 12862 DeductionInfo(nullptr) {} 12863 12864 /// Determines whether this template is an actual instantiation 12865 /// that should be counted toward the maximum instantiation depth. 12866 bool isInstantiationRecord() const; 12867 }; 12868 12869 /// A stack object to be created when performing template 12870 /// instantiation. 12871 /// 12872 /// Construction of an object of type \c InstantiatingTemplate 12873 /// pushes the current instantiation onto the stack of active 12874 /// instantiations. If the size of this stack exceeds the maximum 12875 /// number of recursive template instantiations, construction 12876 /// produces an error and evaluates true. 12877 /// 12878 /// Destruction of this object will pop the named instantiation off 12879 /// the stack. 12880 struct InstantiatingTemplate { 12881 /// Note that we are instantiating a class template, 12882 /// function template, variable template, alias template, 12883 /// or a member thereof. 12884 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12885 Decl *Entity, 12886 SourceRange InstantiationRange = SourceRange()); 12887 12888 struct ExceptionSpecification {}; 12889 /// Note that we are instantiating an exception specification 12890 /// of a function template. 12891 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12892 FunctionDecl *Entity, ExceptionSpecification, 12893 SourceRange InstantiationRange = SourceRange()); 12894 12895 /// Note that we are instantiating a type alias template declaration. 12896 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12897 TypeAliasTemplateDecl *Entity, 12898 ArrayRef<TemplateArgument> TemplateArgs, 12899 SourceRange InstantiationRange = SourceRange()); 12900 12901 /// Note that we are instantiating a default argument in a 12902 /// template-id. 12903 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12904 TemplateParameter Param, TemplateDecl *Template, 12905 ArrayRef<TemplateArgument> TemplateArgs, 12906 SourceRange InstantiationRange = SourceRange()); 12907 12908 /// Note that we are substituting either explicitly-specified or 12909 /// deduced template arguments during function template argument deduction. 12910 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12911 FunctionTemplateDecl *FunctionTemplate, 12912 ArrayRef<TemplateArgument> TemplateArgs, 12913 CodeSynthesisContext::SynthesisKind Kind, 12914 sema::TemplateDeductionInfo &DeductionInfo, 12915 SourceRange InstantiationRange = SourceRange()); 12916 12917 /// Note that we are instantiating as part of template 12918 /// argument deduction for a class template declaration. 12919 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12920 TemplateDecl *Template, 12921 ArrayRef<TemplateArgument> TemplateArgs, 12922 sema::TemplateDeductionInfo &DeductionInfo, 12923 SourceRange InstantiationRange = SourceRange()); 12924 12925 /// Note that we are instantiating as part of template 12926 /// argument deduction for a class template partial 12927 /// specialization. 12928 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12929 ClassTemplatePartialSpecializationDecl *PartialSpec, 12930 ArrayRef<TemplateArgument> TemplateArgs, 12931 sema::TemplateDeductionInfo &DeductionInfo, 12932 SourceRange InstantiationRange = SourceRange()); 12933 12934 /// Note that we are instantiating as part of template 12935 /// argument deduction for a variable template partial 12936 /// specialization. 12937 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12938 VarTemplatePartialSpecializationDecl *PartialSpec, 12939 ArrayRef<TemplateArgument> TemplateArgs, 12940 sema::TemplateDeductionInfo &DeductionInfo, 12941 SourceRange InstantiationRange = SourceRange()); 12942 12943 /// Note that we are instantiating a default argument for a function 12944 /// parameter. 12945 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12946 ParmVarDecl *Param, 12947 ArrayRef<TemplateArgument> TemplateArgs, 12948 SourceRange InstantiationRange = SourceRange()); 12949 12950 /// Note that we are substituting prior template arguments into a 12951 /// non-type parameter. 12952 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12953 NamedDecl *Template, NonTypeTemplateParmDecl *Param, 12954 ArrayRef<TemplateArgument> TemplateArgs, 12955 SourceRange InstantiationRange); 12956 12957 /// Note that we are substituting prior template arguments into a 12958 /// template template parameter. 12959 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12960 NamedDecl *Template, TemplateTemplateParmDecl *Param, 12961 ArrayRef<TemplateArgument> TemplateArgs, 12962 SourceRange InstantiationRange); 12963 12964 /// Note that we are checking the default template argument 12965 /// against the template parameter for a given template-id. 12966 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12967 TemplateDecl *Template, NamedDecl *Param, 12968 ArrayRef<TemplateArgument> TemplateArgs, 12969 SourceRange InstantiationRange); 12970 12971 struct ConstraintsCheck {}; 12972 /// \brief Note that we are checking the constraints associated with some 12973 /// constrained entity (a concept declaration or a template with associated 12974 /// constraints). 12975 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12976 ConstraintsCheck, NamedDecl *Template, 12977 ArrayRef<TemplateArgument> TemplateArgs, 12978 SourceRange InstantiationRange); 12979 12980 struct ConstraintSubstitution {}; 12981 /// \brief Note that we are checking a constraint expression associated 12982 /// with a template declaration or as part of the satisfaction check of a 12983 /// concept. 12984 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12985 ConstraintSubstitution, NamedDecl *Template, 12986 sema::TemplateDeductionInfo &DeductionInfo, 12987 SourceRange InstantiationRange); 12988 12989 struct ConstraintNormalization {}; 12990 /// \brief Note that we are normalizing a constraint expression. 12991 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12992 ConstraintNormalization, NamedDecl *Template, 12993 SourceRange InstantiationRange); 12994 12995 struct ParameterMappingSubstitution {}; 12996 /// \brief Note that we are subtituting into the parameter mapping of an 12997 /// atomic constraint during constraint normalization. 12998 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 12999 ParameterMappingSubstitution, NamedDecl *Template, 13000 SourceRange InstantiationRange); 13001 13002 /// \brief Note that we are substituting template arguments into a part of 13003 /// a requirement of a requires expression. 13004 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 13005 concepts::Requirement *Req, 13006 sema::TemplateDeductionInfo &DeductionInfo, 13007 SourceRange InstantiationRange = SourceRange()); 13008 13009 /// \brief Note that we are checking the satisfaction of the constraint 13010 /// expression inside of a nested requirement. 13011 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 13012 concepts::NestedRequirement *Req, ConstraintsCheck, 13013 SourceRange InstantiationRange = SourceRange()); 13014 13015 /// \brief Note that we are checking a requires clause. 13016 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 13017 const RequiresExpr *E, 13018 sema::TemplateDeductionInfo &DeductionInfo, 13019 SourceRange InstantiationRange); 13020 13021 struct BuildingDeductionGuidesTag {}; 13022 /// \brief Note that we are building deduction guides. 13023 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 13024 TemplateDecl *Entity, BuildingDeductionGuidesTag, 13025 SourceRange InstantiationRange = SourceRange()); 13026 13027 struct PartialOrderingTTP {}; 13028 /// \brief Note that we are partial ordering template template parameters. 13029 InstantiatingTemplate(Sema &SemaRef, SourceLocation ArgLoc, 13030 PartialOrderingTTP, TemplateDecl *PArg, 13031 SourceRange InstantiationRange = SourceRange()); 13032 13033 /// Note that we have finished instantiating this template. 13034 void Clear(); 13035 13036 ~InstantiatingTemplate() { Clear(); } 13037 13038 /// Determines whether we have exceeded the maximum 13039 /// recursive template instantiations. 13040 bool isInvalid() const { return Invalid; } 13041 13042 /// Determine whether we are already instantiating this 13043 /// specialization in some surrounding active instantiation. 13044 bool isAlreadyInstantiating() const { return AlreadyInstantiating; } 13045 13046 private: 13047 Sema &SemaRef; 13048 bool Invalid; 13049 bool AlreadyInstantiating; 13050 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 13051 SourceRange InstantiationRange); 13052 13053 InstantiatingTemplate(Sema &SemaRef, 13054 CodeSynthesisContext::SynthesisKind Kind, 13055 SourceLocation PointOfInstantiation, 13056 SourceRange InstantiationRange, Decl *Entity, 13057 NamedDecl *Template = nullptr, 13058 ArrayRef<TemplateArgument> TemplateArgs = {}, 13059 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 13060 13061 InstantiatingTemplate(const InstantiatingTemplate &) = delete; 13062 13063 InstantiatingTemplate &operator=(const InstantiatingTemplate &) = delete; 13064 }; 13065 13066 bool SubstTemplateArgument(const TemplateArgumentLoc &Input, 13067 const MultiLevelTemplateArgumentList &TemplateArgs, 13068 TemplateArgumentLoc &Output, 13069 SourceLocation Loc = {}, 13070 const DeclarationName &Entity = {}); 13071 bool 13072 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 13073 const MultiLevelTemplateArgumentList &TemplateArgs, 13074 TemplateArgumentListInfo &Outputs); 13075 13076 /// Retrieve the template argument list(s) that should be used to 13077 /// instantiate the definition of the given declaration. 13078 /// 13079 /// \param ND the declaration for which we are computing template 13080 /// instantiation arguments. 13081 /// 13082 /// \param DC In the event we don't HAVE a declaration yet, we instead provide 13083 /// the decl context where it will be created. In this case, the `Innermost` 13084 /// should likely be provided. If ND is non-null, this is ignored. 13085 /// 13086 /// \param Innermost if non-NULL, specifies a template argument list for the 13087 /// template declaration passed as ND. 13088 /// 13089 /// \param RelativeToPrimary true if we should get the template 13090 /// arguments relative to the primary template, even when we're 13091 /// dealing with a specialization. This is only relevant for function 13092 /// template specializations. 13093 /// 13094 /// \param Pattern If non-NULL, indicates the pattern from which we will be 13095 /// instantiating the definition of the given declaration, \p ND. This is 13096 /// used to determine the proper set of template instantiation arguments for 13097 /// friend function template specializations. 13098 /// 13099 /// \param ForConstraintInstantiation when collecting arguments, 13100 /// ForConstraintInstantiation indicates we should continue looking when 13101 /// encountering a lambda generic call operator, and continue looking for 13102 /// arguments on an enclosing class template. 13103 /// 13104 /// \param SkipForSpecialization when specified, any template specializations 13105 /// in a traversal would be ignored. 13106 /// \param ForDefaultArgumentSubstitution indicates we should continue looking 13107 /// when encountering a specialized member function template, rather than 13108 /// returning immediately. 13109 MultiLevelTemplateArgumentList getTemplateInstantiationArgs( 13110 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false, 13111 std::optional<ArrayRef<TemplateArgument>> Innermost = std::nullopt, 13112 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr, 13113 bool ForConstraintInstantiation = false, 13114 bool SkipForSpecialization = false, 13115 bool ForDefaultArgumentSubstitution = false); 13116 13117 /// RAII object to handle the state changes required to synthesize 13118 /// a function body. 13119 class SynthesizedFunctionScope { 13120 Sema &S; 13121 Sema::ContextRAII SavedContext; 13122 bool PushedCodeSynthesisContext = false; 13123 13124 public: 13125 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 13126 : S(S), SavedContext(S, DC) { 13127 auto *FD = dyn_cast<FunctionDecl>(DC); 13128 S.PushFunctionScope(); 13129 S.PushExpressionEvaluationContext( 13130 (FD && FD->isImmediateFunction()) 13131 ? ExpressionEvaluationContext::ImmediateFunctionContext 13132 : ExpressionEvaluationContext::PotentiallyEvaluated); 13133 if (FD) { 13134 auto &Current = S.currentEvaluationContext(); 13135 const auto &Parent = S.parentEvaluationContext(); 13136 13137 FD->setWillHaveBody(true); 13138 Current.InImmediateFunctionContext = 13139 FD->isImmediateFunction() || 13140 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() || 13141 Parent.isImmediateFunctionContext())); 13142 13143 Current.InImmediateEscalatingFunctionContext = 13144 S.getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); 13145 } else 13146 assert(isa<ObjCMethodDecl>(DC)); 13147 } 13148 13149 void addContextNote(SourceLocation UseLoc) { 13150 assert(!PushedCodeSynthesisContext); 13151 13152 Sema::CodeSynthesisContext Ctx; 13153 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; 13154 Ctx.PointOfInstantiation = UseLoc; 13155 Ctx.Entity = cast<Decl>(S.CurContext); 13156 S.pushCodeSynthesisContext(Ctx); 13157 13158 PushedCodeSynthesisContext = true; 13159 } 13160 13161 ~SynthesizedFunctionScope() { 13162 if (PushedCodeSynthesisContext) 13163 S.popCodeSynthesisContext(); 13164 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) { 13165 FD->setWillHaveBody(false); 13166 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction()); 13167 } 13168 S.PopExpressionEvaluationContext(); 13169 S.PopFunctionScopeInfo(); 13170 } 13171 }; 13172 13173 /// List of active code synthesis contexts. 13174 /// 13175 /// This vector is treated as a stack. As synthesis of one entity requires 13176 /// synthesis of another, additional contexts are pushed onto the stack. 13177 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; 13178 13179 /// Specializations whose definitions are currently being instantiated. 13180 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; 13181 13182 /// Non-dependent types used in templates that have already been instantiated 13183 /// by some template instantiation. 13184 llvm::DenseSet<QualType> InstantiatedNonDependentTypes; 13185 13186 /// Extra modules inspected when performing a lookup during a template 13187 /// instantiation. Computed lazily. 13188 SmallVector<Module *, 16> CodeSynthesisContextLookupModules; 13189 13190 /// Cache of additional modules that should be used for name lookup 13191 /// within the current template instantiation. Computed lazily; use 13192 /// getLookupModules() to get a complete set. 13193 llvm::DenseSet<Module *> LookupModulesCache; 13194 13195 /// Map from the most recent declaration of a namespace to the most 13196 /// recent visible declaration of that namespace. 13197 llvm::DenseMap<NamedDecl *, NamedDecl *> VisibleNamespaceCache; 13198 13199 /// Whether we are in a SFINAE context that is not associated with 13200 /// template instantiation. 13201 /// 13202 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 13203 /// of a template instantiation or template argument deduction. 13204 bool InNonInstantiationSFINAEContext; 13205 13206 /// The number of \p CodeSynthesisContexts that are not template 13207 /// instantiations and, therefore, should not be counted as part of the 13208 /// instantiation depth. 13209 /// 13210 /// When the instantiation depth reaches the user-configurable limit 13211 /// \p LangOptions::InstantiationDepth we will abort instantiation. 13212 // FIXME: Should we have a similar limit for other forms of synthesis? 13213 unsigned NonInstantiationEntries; 13214 13215 /// The depth of the context stack at the point when the most recent 13216 /// error or warning was produced. 13217 /// 13218 /// This value is used to suppress printing of redundant context stacks 13219 /// when there are multiple errors or warnings in the same instantiation. 13220 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. 13221 unsigned LastEmittedCodeSynthesisContextDepth = 0; 13222 13223 /// The template instantiation callbacks to trace or track 13224 /// instantiations (objects can be chained). 13225 /// 13226 /// This callbacks is used to print, trace or track template 13227 /// instantiations as they are being constructed. 13228 std::vector<std::unique_ptr<TemplateInstantiationCallback>> 13229 TemplateInstCallbacks; 13230 13231 /// The current index into pack expansion arguments that will be 13232 /// used for substitution of parameter packs. 13233 /// 13234 /// The pack expansion index will be -1 to indicate that parameter packs 13235 /// should be instantiated as themselves. Otherwise, the index specifies 13236 /// which argument within the parameter pack will be used for substitution. 13237 int ArgumentPackSubstitutionIndex; 13238 13239 /// RAII object used to change the argument pack substitution index 13240 /// within a \c Sema object. 13241 /// 13242 /// See \c ArgumentPackSubstitutionIndex for more information. 13243 class ArgumentPackSubstitutionIndexRAII { 13244 Sema &Self; 13245 int OldSubstitutionIndex; 13246 13247 public: 13248 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 13249 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 13250 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 13251 } 13252 13253 ~ArgumentPackSubstitutionIndexRAII() { 13254 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 13255 } 13256 }; 13257 13258 friend class ArgumentPackSubstitutionRAII; 13259 13260 void pushCodeSynthesisContext(CodeSynthesisContext Ctx); 13261 void popCodeSynthesisContext(); 13262 13263 void PrintContextStack() { 13264 if (!CodeSynthesisContexts.empty() && 13265 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { 13266 PrintInstantiationStack(); 13267 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); 13268 } 13269 if (PragmaAttributeCurrentTargetDecl) 13270 PrintPragmaAttributeInstantiationPoint(); 13271 } 13272 /// Prints the current instantiation stack through a series of 13273 /// notes. 13274 void PrintInstantiationStack(); 13275 13276 /// Determines whether we are currently in a context where 13277 /// template argument substitution failures are not considered 13278 /// errors. 13279 /// 13280 /// \returns An empty \c Optional if we're not in a SFINAE context. 13281 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 13282 /// template-deduction context object, which can be used to capture 13283 /// diagnostics that will be suppressed. 13284 std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 13285 13286 /// Perform substitution on the type T with a given set of template 13287 /// arguments. 13288 /// 13289 /// This routine substitutes the given template arguments into the 13290 /// type T and produces the instantiated type. 13291 /// 13292 /// \param T the type into which the template arguments will be 13293 /// substituted. If this type is not dependent, it will be returned 13294 /// immediately. 13295 /// 13296 /// \param Args the template arguments that will be 13297 /// substituted for the top-level template parameters within T. 13298 /// 13299 /// \param Loc the location in the source code where this substitution 13300 /// is being performed. It will typically be the location of the 13301 /// declarator (if we're instantiating the type of some declaration) 13302 /// or the location of the type in the source code (if, e.g., we're 13303 /// instantiating the type of a cast expression). 13304 /// 13305 /// \param Entity the name of the entity associated with a declaration 13306 /// being instantiated (if any). May be empty to indicate that there 13307 /// is no such entity (if, e.g., this is a type that occurs as part of 13308 /// a cast expression) or that the entity has no name (e.g., an 13309 /// unnamed function parameter). 13310 /// 13311 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is 13312 /// acceptable as the top level type of the result. 13313 /// 13314 /// \param IsIncompleteSubstitution If provided, the pointee will be set 13315 /// whenever substitution would perform a replacement with a null or 13316 /// non-existent template argument. 13317 /// 13318 /// \returns If the instantiation succeeds, the instantiated 13319 /// type. Otherwise, produces diagnostics and returns a NULL type. 13320 TypeSourceInfo *SubstType(TypeSourceInfo *T, 13321 const MultiLevelTemplateArgumentList &TemplateArgs, 13322 SourceLocation Loc, DeclarationName Entity, 13323 bool AllowDeducedTST = false); 13324 13325 QualType SubstType(QualType T, 13326 const MultiLevelTemplateArgumentList &TemplateArgs, 13327 SourceLocation Loc, DeclarationName Entity, 13328 bool *IsIncompleteSubstitution = nullptr); 13329 13330 TypeSourceInfo *SubstType(TypeLoc TL, 13331 const MultiLevelTemplateArgumentList &TemplateArgs, 13332 SourceLocation Loc, DeclarationName Entity); 13333 13334 /// A form of SubstType intended specifically for instantiating the 13335 /// type of a FunctionDecl. Its purpose is solely to force the 13336 /// instantiation of default-argument expressions and to avoid 13337 /// instantiating an exception-specification. 13338 TypeSourceInfo *SubstFunctionDeclType( 13339 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, 13340 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, 13341 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true); 13342 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 13343 const MultiLevelTemplateArgumentList &Args); 13344 bool SubstExceptionSpec(SourceLocation Loc, 13345 FunctionProtoType::ExceptionSpecInfo &ESI, 13346 SmallVectorImpl<QualType> &ExceptionStorage, 13347 const MultiLevelTemplateArgumentList &Args); 13348 ParmVarDecl * 13349 SubstParmVarDecl(ParmVarDecl *D, 13350 const MultiLevelTemplateArgumentList &TemplateArgs, 13351 int indexAdjustment, std::optional<unsigned> NumExpansions, 13352 bool ExpectParameterPack, bool EvaluateConstraints = true); 13353 13354 /// Substitute the given template arguments into the given set of 13355 /// parameters, producing the set of parameter types that would be generated 13356 /// from such a substitution. 13357 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, 13358 const FunctionProtoType::ExtParameterInfo *ExtParamInfos, 13359 const MultiLevelTemplateArgumentList &TemplateArgs, 13360 SmallVectorImpl<QualType> &ParamTypes, 13361 SmallVectorImpl<ParmVarDecl *> *OutParams, 13362 ExtParameterInfoBuilder &ParamInfos); 13363 13364 /// Substitute the given template arguments into the default argument. 13365 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, 13366 const MultiLevelTemplateArgumentList &TemplateArgs, 13367 bool ForCallExpr = false); 13368 ExprResult SubstExpr(Expr *E, 13369 const MultiLevelTemplateArgumentList &TemplateArgs); 13370 13371 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator 13372 // to disable constraint evaluation, then restore the state. 13373 template <typename InstTy> struct ConstraintEvalRAII { 13374 InstTy &TI; 13375 bool OldValue; 13376 13377 ConstraintEvalRAII(InstTy &TI) 13378 : TI(TI), OldValue(TI.getEvaluateConstraints()) { 13379 TI.setEvaluateConstraints(false); 13380 } 13381 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); } 13382 }; 13383 13384 // Must be used instead of SubstExpr at 'constraint checking' time. 13385 ExprResult 13386 SubstConstraintExpr(Expr *E, 13387 const MultiLevelTemplateArgumentList &TemplateArgs); 13388 // Unlike the above, this does not evaluates constraints. 13389 ExprResult SubstConstraintExprWithoutSatisfaction( 13390 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); 13391 13392 /// Substitute the given template arguments into a list of 13393 /// expressions, expanding pack expansions if required. 13394 /// 13395 /// \param Exprs The list of expressions to substitute into. 13396 /// 13397 /// \param IsCall Whether this is some form of call, in which case 13398 /// default arguments will be dropped. 13399 /// 13400 /// \param TemplateArgs The set of template arguments to substitute. 13401 /// 13402 /// \param Outputs Will receive all of the substituted arguments. 13403 /// 13404 /// \returns true if an error occurred, false otherwise. 13405 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 13406 const MultiLevelTemplateArgumentList &TemplateArgs, 13407 SmallVectorImpl<Expr *> &Outputs); 13408 13409 StmtResult SubstStmt(Stmt *S, 13410 const MultiLevelTemplateArgumentList &TemplateArgs); 13411 13412 ExprResult 13413 SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, 13414 bool CXXDirectInit); 13415 13416 /// Perform substitution on the base class specifiers of the 13417 /// given class template specialization. 13418 /// 13419 /// Produces a diagnostic and returns true on error, returns false and 13420 /// attaches the instantiated base classes to the class template 13421 /// specialization if successful. 13422 bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 13423 const MultiLevelTemplateArgumentList &TemplateArgs); 13424 13425 /// Instantiate the definition of a class from a given pattern. 13426 /// 13427 /// \param PointOfInstantiation The point of instantiation within the 13428 /// source code. 13429 /// 13430 /// \param Instantiation is the declaration whose definition is being 13431 /// instantiated. This will be either a class template specialization 13432 /// or a member class of a class template specialization. 13433 /// 13434 /// \param Pattern is the pattern from which the instantiation 13435 /// occurs. This will be either the declaration of a class template or 13436 /// the declaration of a member class of a class template. 13437 /// 13438 /// \param TemplateArgs The template arguments to be substituted into 13439 /// the pattern. 13440 /// 13441 /// \param TSK the kind of implicit or explicit instantiation to perform. 13442 /// 13443 /// \param Complain whether to complain if the class cannot be instantiated 13444 /// due to the lack of a definition. 13445 /// 13446 /// \returns true if an error occurred, false otherwise. 13447 bool InstantiateClass(SourceLocation PointOfInstantiation, 13448 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 13449 const MultiLevelTemplateArgumentList &TemplateArgs, 13450 TemplateSpecializationKind TSK, bool Complain = true); 13451 13452 /// Instantiate the definition of an enum from a given pattern. 13453 /// 13454 /// \param PointOfInstantiation The point of instantiation within the 13455 /// source code. 13456 /// \param Instantiation is the declaration whose definition is being 13457 /// instantiated. This will be a member enumeration of a class 13458 /// temploid specialization, or a local enumeration within a 13459 /// function temploid specialization. 13460 /// \param Pattern The templated declaration from which the instantiation 13461 /// occurs. 13462 /// \param TemplateArgs The template arguments to be substituted into 13463 /// the pattern. 13464 /// \param TSK The kind of implicit or explicit instantiation to perform. 13465 /// 13466 /// \return \c true if an error occurred, \c false otherwise. 13467 bool InstantiateEnum(SourceLocation PointOfInstantiation, 13468 EnumDecl *Instantiation, EnumDecl *Pattern, 13469 const MultiLevelTemplateArgumentList &TemplateArgs, 13470 TemplateSpecializationKind TSK); 13471 13472 /// Instantiate the definition of a field from the given pattern. 13473 /// 13474 /// \param PointOfInstantiation The point of instantiation within the 13475 /// source code. 13476 /// \param Instantiation is the declaration whose definition is being 13477 /// instantiated. This will be a class of a class temploid 13478 /// specialization, or a local enumeration within a function temploid 13479 /// specialization. 13480 /// \param Pattern The templated declaration from which the instantiation 13481 /// occurs. 13482 /// \param TemplateArgs The template arguments to be substituted into 13483 /// the pattern. 13484 /// 13485 /// \return \c true if an error occurred, \c false otherwise. 13486 bool InstantiateInClassInitializer( 13487 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 13488 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 13489 13490 bool usesPartialOrExplicitSpecialization( 13491 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); 13492 13493 bool InstantiateClassTemplateSpecialization( 13494 SourceLocation PointOfInstantiation, 13495 ClassTemplateSpecializationDecl *ClassTemplateSpec, 13496 TemplateSpecializationKind TSK, bool Complain = true, 13497 bool PrimaryHasMatchedPackOnParmToNonPackOnArg = false); 13498 13499 /// Instantiates the definitions of all of the member 13500 /// of the given class, which is an instantiation of a class template 13501 /// or a member class of a template. 13502 void 13503 InstantiateClassMembers(SourceLocation PointOfInstantiation, 13504 CXXRecordDecl *Instantiation, 13505 const MultiLevelTemplateArgumentList &TemplateArgs, 13506 TemplateSpecializationKind TSK); 13507 13508 /// Instantiate the definitions of all of the members of the 13509 /// given class template specialization, which was named as part of an 13510 /// explicit instantiation. 13511 void InstantiateClassTemplateSpecializationMembers( 13512 SourceLocation PointOfInstantiation, 13513 ClassTemplateSpecializationDecl *ClassTemplateSpec, 13514 TemplateSpecializationKind TSK); 13515 13516 NestedNameSpecifierLoc SubstNestedNameSpecifierLoc( 13517 NestedNameSpecifierLoc NNS, 13518 const MultiLevelTemplateArgumentList &TemplateArgs); 13519 13520 /// Do template substitution on declaration name info. 13521 DeclarationNameInfo 13522 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 13523 const MultiLevelTemplateArgumentList &TemplateArgs); 13524 TemplateName 13525 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 13526 SourceLocation Loc, 13527 const MultiLevelTemplateArgumentList &TemplateArgs); 13528 13529 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, 13530 const MultiLevelTemplateArgumentList &TemplateArgs, 13531 bool EvaluateConstraint); 13532 13533 /// Determine whether we are currently performing template instantiation. 13534 bool inTemplateInstantiation() const { 13535 return CodeSynthesisContexts.size() > NonInstantiationEntries; 13536 } 13537 13538 using EntityPrinter = llvm::function_ref<void(llvm::raw_ostream &)>; 13539 13540 /// \brief create a Requirement::SubstitutionDiagnostic with only a 13541 /// SubstitutedEntity and DiagLoc using ASTContext's allocator. 13542 concepts::Requirement::SubstitutionDiagnostic * 13543 createSubstDiagAt(SourceLocation Location, EntityPrinter Printer); 13544 13545 ///@} 13546 13547 // 13548 // 13549 // ------------------------------------------------------------------------- 13550 // 13551 // 13552 13553 /// \name C++ Template Declaration Instantiation 13554 /// Implementations are in SemaTemplateInstantiateDecl.cpp 13555 ///@{ 13556 13557 public: 13558 /// An entity for which implicit template instantiation is required. 13559 /// 13560 /// The source location associated with the declaration is the first place in 13561 /// the source code where the declaration was "used". It is not necessarily 13562 /// the point of instantiation (which will be either before or after the 13563 /// namespace-scope declaration that triggered this implicit instantiation), 13564 /// However, it is the location that diagnostics should generally refer to, 13565 /// because users will need to know what code triggered the instantiation. 13566 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 13567 13568 /// The queue of implicit template instantiations that are required 13569 /// but have not yet been performed. 13570 std::deque<PendingImplicitInstantiation> PendingInstantiations; 13571 13572 /// Queue of implicit template instantiations that cannot be performed 13573 /// eagerly. 13574 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; 13575 13576 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses; 13577 SmallVector<std::deque<PendingImplicitInstantiation>, 8> 13578 SavedPendingInstantiations; 13579 13580 /// The queue of implicit template instantiations that are required 13581 /// and must be performed within the current local scope. 13582 /// 13583 /// This queue is only used for member functions of local classes in 13584 /// templates, which must be instantiated in the same scope as their 13585 /// enclosing function, so that they can reference function-local 13586 /// types, static variables, enumerators, etc. 13587 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 13588 13589 class LocalEagerInstantiationScope { 13590 public: 13591 LocalEagerInstantiationScope(Sema &S) : S(S) { 13592 SavedPendingLocalImplicitInstantiations.swap( 13593 S.PendingLocalImplicitInstantiations); 13594 } 13595 13596 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } 13597 13598 ~LocalEagerInstantiationScope() { 13599 assert(S.PendingLocalImplicitInstantiations.empty() && 13600 "there shouldn't be any pending local implicit instantiations"); 13601 SavedPendingLocalImplicitInstantiations.swap( 13602 S.PendingLocalImplicitInstantiations); 13603 } 13604 13605 private: 13606 Sema &S; 13607 std::deque<PendingImplicitInstantiation> 13608 SavedPendingLocalImplicitInstantiations; 13609 }; 13610 13611 /// Records and restores the CurFPFeatures state on entry/exit of compound 13612 /// statements. 13613 class FPFeaturesStateRAII { 13614 public: 13615 FPFeaturesStateRAII(Sema &S); 13616 ~FPFeaturesStateRAII(); 13617 FPOptionsOverride getOverrides() { return OldOverrides; } 13618 13619 private: 13620 Sema &S; 13621 FPOptions OldFPFeaturesState; 13622 FPOptionsOverride OldOverrides; 13623 LangOptions::FPEvalMethodKind OldEvalMethod; 13624 SourceLocation OldFPPragmaLocation; 13625 }; 13626 13627 class GlobalEagerInstantiationScope { 13628 public: 13629 GlobalEagerInstantiationScope(Sema &S, bool Enabled) 13630 : S(S), Enabled(Enabled) { 13631 if (!Enabled) 13632 return; 13633 13634 S.SavedPendingInstantiations.emplace_back(); 13635 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations); 13636 13637 S.SavedVTableUses.emplace_back(); 13638 S.SavedVTableUses.back().swap(S.VTableUses); 13639 } 13640 13641 void perform() { 13642 if (Enabled) { 13643 S.DefineUsedVTables(); 13644 S.PerformPendingInstantiations(); 13645 } 13646 } 13647 13648 ~GlobalEagerInstantiationScope() { 13649 if (!Enabled) 13650 return; 13651 13652 // Restore the set of pending vtables. 13653 assert(S.VTableUses.empty() && 13654 "VTableUses should be empty before it is discarded."); 13655 S.VTableUses.swap(S.SavedVTableUses.back()); 13656 S.SavedVTableUses.pop_back(); 13657 13658 // Restore the set of pending implicit instantiations. 13659 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { 13660 assert(S.PendingInstantiations.empty() && 13661 "PendingInstantiations should be empty before it is discarded."); 13662 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back()); 13663 S.SavedPendingInstantiations.pop_back(); 13664 } else { 13665 // Template instantiations in the PCH may be delayed until the TU. 13666 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back()); 13667 S.PendingInstantiations.insert( 13668 S.PendingInstantiations.end(), 13669 S.SavedPendingInstantiations.back().begin(), 13670 S.SavedPendingInstantiations.back().end()); 13671 S.SavedPendingInstantiations.pop_back(); 13672 } 13673 } 13674 13675 private: 13676 Sema &S; 13677 bool Enabled; 13678 }; 13679 13680 ExplicitSpecifier instantiateExplicitSpecifier( 13681 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES); 13682 13683 struct LateInstantiatedAttribute { 13684 const Attr *TmplAttr; 13685 LocalInstantiationScope *Scope; 13686 Decl *NewDecl; 13687 13688 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 13689 Decl *D) 13690 : TmplAttr(A), Scope(S), NewDecl(D) {} 13691 }; 13692 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 13693 13694 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 13695 const Decl *Pattern, Decl *Inst, 13696 LateInstantiatedAttrVec *LateAttrs = nullptr, 13697 LocalInstantiationScope *OuterMostScope = nullptr); 13698 13699 /// Update instantiation attributes after template was late parsed. 13700 /// 13701 /// Some attributes are evaluated based on the body of template. If it is 13702 /// late parsed, such attributes cannot be evaluated when declaration is 13703 /// instantiated. This function is used to update instantiation attributes 13704 /// when template definition is ready. 13705 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst); 13706 13707 void 13708 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, 13709 const Decl *Pattern, Decl *Inst, 13710 LateInstantiatedAttrVec *LateAttrs = nullptr, 13711 LocalInstantiationScope *OuterMostScope = nullptr); 13712 13713 /// In the MS ABI, we need to instantiate default arguments of dllexported 13714 /// default constructors along with the constructor definition. This allows IR 13715 /// gen to emit a constructor closure which calls the default constructor with 13716 /// its default arguments. 13717 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); 13718 13719 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 13720 ParmVarDecl *Param); 13721 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 13722 FunctionDecl *Function); 13723 13724 /// Instantiate (or find existing instantiation of) a function template with a 13725 /// given set of template arguments. 13726 /// 13727 /// Usually this should not be used, and template argument deduction should be 13728 /// used in its place. 13729 FunctionDecl *InstantiateFunctionDeclaration( 13730 FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, 13731 SourceLocation Loc, 13732 CodeSynthesisContext::SynthesisKind CSC = 13733 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution); 13734 13735 /// Instantiate the definition of the given function from its 13736 /// template. 13737 /// 13738 /// \param PointOfInstantiation the point at which the instantiation was 13739 /// required. Note that this is not precisely a "point of instantiation" 13740 /// for the function, but it's close. 13741 /// 13742 /// \param Function the already-instantiated declaration of a 13743 /// function template specialization or member function of a class template 13744 /// specialization. 13745 /// 13746 /// \param Recursive if true, recursively instantiates any functions that 13747 /// are required by this instantiation. 13748 /// 13749 /// \param DefinitionRequired if true, then we are performing an explicit 13750 /// instantiation where the body of the function is required. Complain if 13751 /// there is no such body. 13752 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 13753 FunctionDecl *Function, 13754 bool Recursive = false, 13755 bool DefinitionRequired = false, 13756 bool AtEndOfTU = false); 13757 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 13758 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 13759 const TemplateArgumentList *PartialSpecArgs, 13760 const TemplateArgumentListInfo &TemplateArgsInfo, 13761 SmallVectorImpl<TemplateArgument> &Converted, 13762 SourceLocation PointOfInstantiation, 13763 LateInstantiatedAttrVec *LateAttrs = nullptr, 13764 LocalInstantiationScope *StartingScope = nullptr); 13765 13766 /// Instantiates a variable template specialization by completing it 13767 /// with appropriate type information and initializer. 13768 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 13769 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 13770 const MultiLevelTemplateArgumentList &TemplateArgs); 13771 13772 /// BuildVariableInstantiation - Used after a new variable has been created. 13773 /// Sets basic variable data and decides whether to postpone the 13774 /// variable instantiation. 13775 void 13776 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 13777 const MultiLevelTemplateArgumentList &TemplateArgs, 13778 LateInstantiatedAttrVec *LateAttrs, 13779 DeclContext *Owner, 13780 LocalInstantiationScope *StartingScope, 13781 bool InstantiatingVarTemplate = false, 13782 VarTemplateSpecializationDecl *PrevVTSD = nullptr); 13783 13784 /// Instantiate the initializer of a variable. 13785 void InstantiateVariableInitializer( 13786 VarDecl *Var, VarDecl *OldVar, 13787 const MultiLevelTemplateArgumentList &TemplateArgs); 13788 13789 /// Instantiate the definition of the given variable from its 13790 /// template. 13791 /// 13792 /// \param PointOfInstantiation the point at which the instantiation was 13793 /// required. Note that this is not precisely a "point of instantiation" 13794 /// for the variable, but it's close. 13795 /// 13796 /// \param Var the already-instantiated declaration of a templated variable. 13797 /// 13798 /// \param Recursive if true, recursively instantiates any functions that 13799 /// are required by this instantiation. 13800 /// 13801 /// \param DefinitionRequired if true, then we are performing an explicit 13802 /// instantiation where a definition of the variable is required. Complain 13803 /// if there is no such definition. 13804 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 13805 VarDecl *Var, bool Recursive = false, 13806 bool DefinitionRequired = false, 13807 bool AtEndOfTU = false); 13808 13809 void InstantiateMemInitializers( 13810 CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, 13811 const MultiLevelTemplateArgumentList &TemplateArgs); 13812 13813 /// Find the instantiation of the given declaration within the 13814 /// current instantiation. 13815 /// 13816 /// This routine is intended to be used when \p D is a declaration 13817 /// referenced from within a template, that needs to mapped into the 13818 /// corresponding declaration within an instantiation. For example, 13819 /// given: 13820 /// 13821 /// \code 13822 /// template<typename T> 13823 /// struct X { 13824 /// enum Kind { 13825 /// KnownValue = sizeof(T) 13826 /// }; 13827 /// 13828 /// bool getKind() const { return KnownValue; } 13829 /// }; 13830 /// 13831 /// template struct X<int>; 13832 /// \endcode 13833 /// 13834 /// In the instantiation of X<int>::getKind(), we need to map the \p 13835 /// EnumConstantDecl for \p KnownValue (which refers to 13836 /// X<T>::<Kind>::KnownValue) to its instantiation 13837 /// (X<int>::<Kind>::KnownValue). 13838 /// \p FindInstantiatedDecl performs this mapping from within the 13839 /// instantiation of X<int>. 13840 NamedDecl * 13841 FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 13842 const MultiLevelTemplateArgumentList &TemplateArgs, 13843 bool FindingInstantiatedContext = false); 13844 13845 /// Finds the instantiation of the given declaration context 13846 /// within the current instantiation. 13847 /// 13848 /// \returns NULL if there was an error 13849 DeclContext * 13850 FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 13851 const MultiLevelTemplateArgumentList &TemplateArgs); 13852 13853 Decl *SubstDecl(Decl *D, DeclContext *Owner, 13854 const MultiLevelTemplateArgumentList &TemplateArgs); 13855 13856 /// Substitute the name and return type of a defaulted 'operator<=>' to form 13857 /// an implicit 'operator=='. 13858 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 13859 FunctionDecl *Spaceship); 13860 13861 /// Performs template instantiation for all implicit template 13862 /// instantiations we have seen until this point. 13863 void PerformPendingInstantiations(bool LocalOnly = false); 13864 13865 TemplateParameterList * 13866 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 13867 const MultiLevelTemplateArgumentList &TemplateArgs, 13868 bool EvaluateConstraints = true); 13869 13870 void PerformDependentDiagnostics( 13871 const DeclContext *Pattern, 13872 const MultiLevelTemplateArgumentList &TemplateArgs); 13873 13874 private: 13875 /// Introduce the instantiated local variables into the local 13876 /// instantiation scope. 13877 void addInstantiatedLocalVarsToScope(FunctionDecl *Function, 13878 const FunctionDecl *PatternDecl, 13879 LocalInstantiationScope &Scope); 13880 /// Introduce the instantiated function parameters into the local 13881 /// instantiation scope, and set the parameter names to those used 13882 /// in the template. 13883 bool addInstantiatedParametersToScope( 13884 FunctionDecl *Function, const FunctionDecl *PatternDecl, 13885 LocalInstantiationScope &Scope, 13886 const MultiLevelTemplateArgumentList &TemplateArgs); 13887 13888 /// Introduce the instantiated captures of the lambda into the local 13889 /// instantiation scope. 13890 bool addInstantiatedCapturesToScope( 13891 FunctionDecl *Function, const FunctionDecl *PatternDecl, 13892 LocalInstantiationScope &Scope, 13893 const MultiLevelTemplateArgumentList &TemplateArgs); 13894 13895 int ParsingClassDepth = 0; 13896 13897 class SavePendingParsedClassStateRAII { 13898 public: 13899 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } 13900 13901 ~SavePendingParsedClassStateRAII() { 13902 assert(S.DelayedOverridingExceptionSpecChecks.empty() && 13903 "there shouldn't be any pending delayed exception spec checks"); 13904 assert(S.DelayedEquivalentExceptionSpecChecks.empty() && 13905 "there shouldn't be any pending delayed exception spec checks"); 13906 swapSavedState(); 13907 } 13908 13909 private: 13910 Sema &S; 13911 decltype(DelayedOverridingExceptionSpecChecks) 13912 SavedOverridingExceptionSpecChecks; 13913 decltype(DelayedEquivalentExceptionSpecChecks) 13914 SavedEquivalentExceptionSpecChecks; 13915 13916 void swapSavedState() { 13917 SavedOverridingExceptionSpecChecks.swap( 13918 S.DelayedOverridingExceptionSpecChecks); 13919 SavedEquivalentExceptionSpecChecks.swap( 13920 S.DelayedEquivalentExceptionSpecChecks); 13921 } 13922 }; 13923 13924 ///@} 13925 13926 // 13927 // 13928 // ------------------------------------------------------------------------- 13929 // 13930 // 13931 13932 /// \name C++ Variadic Templates 13933 /// Implementations are in SemaTemplateVariadic.cpp 13934 ///@{ 13935 13936 public: 13937 /// Determine whether an unexpanded parameter pack might be permitted in this 13938 /// location. Useful for error recovery. 13939 bool isUnexpandedParameterPackPermitted(); 13940 13941 /// The context in which an unexpanded parameter pack is 13942 /// being diagnosed. 13943 /// 13944 /// Note that the values of this enumeration line up with the first 13945 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 13946 enum UnexpandedParameterPackContext { 13947 /// An arbitrary expression. 13948 UPPC_Expression = 0, 13949 13950 /// The base type of a class type. 13951 UPPC_BaseType, 13952 13953 /// The type of an arbitrary declaration. 13954 UPPC_DeclarationType, 13955 13956 /// The type of a data member. 13957 UPPC_DataMemberType, 13958 13959 /// The size of a bit-field. 13960 UPPC_BitFieldWidth, 13961 13962 /// The expression in a static assertion. 13963 UPPC_StaticAssertExpression, 13964 13965 /// The fixed underlying type of an enumeration. 13966 UPPC_FixedUnderlyingType, 13967 13968 /// The enumerator value. 13969 UPPC_EnumeratorValue, 13970 13971 /// A using declaration. 13972 UPPC_UsingDeclaration, 13973 13974 /// A friend declaration. 13975 UPPC_FriendDeclaration, 13976 13977 /// A declaration qualifier. 13978 UPPC_DeclarationQualifier, 13979 13980 /// An initializer. 13981 UPPC_Initializer, 13982 13983 /// A default argument. 13984 UPPC_DefaultArgument, 13985 13986 /// The type of a non-type template parameter. 13987 UPPC_NonTypeTemplateParameterType, 13988 13989 /// The type of an exception. 13990 UPPC_ExceptionType, 13991 13992 /// Explicit specialization. 13993 UPPC_ExplicitSpecialization, 13994 13995 /// Partial specialization. 13996 UPPC_PartialSpecialization, 13997 13998 /// Microsoft __if_exists. 13999 UPPC_IfExists, 14000 14001 /// Microsoft __if_not_exists. 14002 UPPC_IfNotExists, 14003 14004 /// Lambda expression. 14005 UPPC_Lambda, 14006 14007 /// Block expression. 14008 UPPC_Block, 14009 14010 /// A type constraint. 14011 UPPC_TypeConstraint, 14012 14013 // A requirement in a requires-expression. 14014 UPPC_Requirement, 14015 14016 // A requires-clause. 14017 UPPC_RequiresClause, 14018 }; 14019 14020 /// Diagnose unexpanded parameter packs. 14021 /// 14022 /// \param Loc The location at which we should emit the diagnostic. 14023 /// 14024 /// \param UPPC The context in which we are diagnosing unexpanded 14025 /// parameter packs. 14026 /// 14027 /// \param Unexpanded the set of unexpanded parameter packs. 14028 /// 14029 /// \returns true if an error occurred, false otherwise. 14030 bool DiagnoseUnexpandedParameterPacks( 14031 SourceLocation Loc, UnexpandedParameterPackContext UPPC, 14032 ArrayRef<UnexpandedParameterPack> Unexpanded); 14033 14034 /// If the given type contains an unexpanded parameter pack, 14035 /// diagnose the error. 14036 /// 14037 /// \param Loc The source location where a diagnostc should be emitted. 14038 /// 14039 /// \param T The type that is being checked for unexpanded parameter 14040 /// packs. 14041 /// 14042 /// \returns true if an error occurred, false otherwise. 14043 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 14044 UnexpandedParameterPackContext UPPC); 14045 14046 /// If the given expression contains an unexpanded parameter 14047 /// pack, diagnose the error. 14048 /// 14049 /// \param E The expression that is being checked for unexpanded 14050 /// parameter packs. 14051 /// 14052 /// \returns true if an error occurred, false otherwise. 14053 bool DiagnoseUnexpandedParameterPack( 14054 Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); 14055 14056 /// If the given requirees-expression contains an unexpanded reference to one 14057 /// of its own parameter packs, diagnose the error. 14058 /// 14059 /// \param RE The requiress-expression that is being checked for unexpanded 14060 /// parameter packs. 14061 /// 14062 /// \returns true if an error occurred, false otherwise. 14063 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); 14064 14065 /// If the given nested-name-specifier contains an unexpanded 14066 /// parameter pack, diagnose the error. 14067 /// 14068 /// \param SS The nested-name-specifier that is being checked for 14069 /// unexpanded parameter packs. 14070 /// 14071 /// \returns true if an error occurred, false otherwise. 14072 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 14073 UnexpandedParameterPackContext UPPC); 14074 14075 /// If the given name contains an unexpanded parameter pack, 14076 /// diagnose the error. 14077 /// 14078 /// \param NameInfo The name (with source location information) that 14079 /// is being checked for unexpanded parameter packs. 14080 /// 14081 /// \returns true if an error occurred, false otherwise. 14082 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 14083 UnexpandedParameterPackContext UPPC); 14084 14085 /// If the given template name contains an unexpanded parameter pack, 14086 /// diagnose the error. 14087 /// 14088 /// \param Loc The location of the template name. 14089 /// 14090 /// \param Template The template name that is being checked for unexpanded 14091 /// parameter packs. 14092 /// 14093 /// \returns true if an error occurred, false otherwise. 14094 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 14095 TemplateName Template, 14096 UnexpandedParameterPackContext UPPC); 14097 14098 /// If the given template argument contains an unexpanded parameter 14099 /// pack, diagnose the error. 14100 /// 14101 /// \param Arg The template argument that is being checked for unexpanded 14102 /// parameter packs. 14103 /// 14104 /// \returns true if an error occurred, false otherwise. 14105 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 14106 UnexpandedParameterPackContext UPPC); 14107 14108 /// Collect the set of unexpanded parameter packs within the given 14109 /// template argument. 14110 /// 14111 /// \param Arg The template argument that will be traversed to find 14112 /// unexpanded parameter packs. 14113 void collectUnexpandedParameterPacks( 14114 TemplateArgument Arg, 14115 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 14116 14117 /// Collect the set of unexpanded parameter packs within the given 14118 /// template argument. 14119 /// 14120 /// \param Arg The template argument that will be traversed to find 14121 /// unexpanded parameter packs. 14122 void collectUnexpandedParameterPacks( 14123 TemplateArgumentLoc Arg, 14124 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 14125 14126 /// Collect the set of unexpanded parameter packs within the given 14127 /// type. 14128 /// 14129 /// \param T The type that will be traversed to find 14130 /// unexpanded parameter packs. 14131 void collectUnexpandedParameterPacks( 14132 QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 14133 14134 /// Collect the set of unexpanded parameter packs within the given 14135 /// type. 14136 /// 14137 /// \param TL The type that will be traversed to find 14138 /// unexpanded parameter packs. 14139 void collectUnexpandedParameterPacks( 14140 TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 14141 14142 /// Collect the set of unexpanded parameter packs within the given 14143 /// nested-name-specifier. 14144 /// 14145 /// \param NNS The nested-name-specifier that will be traversed to find 14146 /// unexpanded parameter packs. 14147 void collectUnexpandedParameterPacks( 14148 NestedNameSpecifierLoc NNS, 14149 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 14150 14151 /// Collect the set of unexpanded parameter packs within the given 14152 /// name. 14153 /// 14154 /// \param NameInfo The name that will be traversed to find 14155 /// unexpanded parameter packs. 14156 void collectUnexpandedParameterPacks( 14157 const DeclarationNameInfo &NameInfo, 14158 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 14159 14160 /// Collect the set of unexpanded parameter packs within the given 14161 /// expression. 14162 static void collectUnexpandedParameterPacks( 14163 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 14164 14165 /// Invoked when parsing a template argument followed by an 14166 /// ellipsis, which creates a pack expansion. 14167 /// 14168 /// \param Arg The template argument preceding the ellipsis, which 14169 /// may already be invalid. 14170 /// 14171 /// \param EllipsisLoc The location of the ellipsis. 14172 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 14173 SourceLocation EllipsisLoc); 14174 14175 /// Invoked when parsing a type followed by an ellipsis, which 14176 /// creates a pack expansion. 14177 /// 14178 /// \param Type The type preceding the ellipsis, which will become 14179 /// the pattern of the pack expansion. 14180 /// 14181 /// \param EllipsisLoc The location of the ellipsis. 14182 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 14183 14184 /// Construct a pack expansion type from the pattern of the pack 14185 /// expansion. 14186 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 14187 SourceLocation EllipsisLoc, 14188 std::optional<unsigned> NumExpansions); 14189 14190 /// Construct a pack expansion type from the pattern of the pack 14191 /// expansion. 14192 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, 14193 SourceLocation EllipsisLoc, 14194 std::optional<unsigned> NumExpansions); 14195 14196 /// Invoked when parsing an expression followed by an ellipsis, which 14197 /// creates a pack expansion. 14198 /// 14199 /// \param Pattern The expression preceding the ellipsis, which will become 14200 /// the pattern of the pack expansion. 14201 /// 14202 /// \param EllipsisLoc The location of the ellipsis. 14203 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 14204 14205 /// Invoked when parsing an expression followed by an ellipsis, which 14206 /// creates a pack expansion. 14207 /// 14208 /// \param Pattern The expression preceding the ellipsis, which will become 14209 /// the pattern of the pack expansion. 14210 /// 14211 /// \param EllipsisLoc The location of the ellipsis. 14212 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 14213 std::optional<unsigned> NumExpansions); 14214 14215 /// Determine whether we could expand a pack expansion with the 14216 /// given set of parameter packs into separate arguments by repeatedly 14217 /// transforming the pattern. 14218 /// 14219 /// \param EllipsisLoc The location of the ellipsis that identifies the 14220 /// pack expansion. 14221 /// 14222 /// \param PatternRange The source range that covers the entire pattern of 14223 /// the pack expansion. 14224 /// 14225 /// \param Unexpanded The set of unexpanded parameter packs within the 14226 /// pattern. 14227 /// 14228 /// \param ShouldExpand Will be set to \c true if the transformer should 14229 /// expand the corresponding pack expansions into separate arguments. When 14230 /// set, \c NumExpansions must also be set. 14231 /// 14232 /// \param RetainExpansion Whether the caller should add an unexpanded 14233 /// pack expansion after all of the expanded arguments. This is used 14234 /// when extending explicitly-specified template argument packs per 14235 /// C++0x [temp.arg.explicit]p9. 14236 /// 14237 /// \param NumExpansions The number of separate arguments that will be in 14238 /// the expanded form of the corresponding pack expansion. This is both an 14239 /// input and an output parameter, which can be set by the caller if the 14240 /// number of expansions is known a priori (e.g., due to a prior substitution) 14241 /// and will be set by the callee when the number of expansions is known. 14242 /// The callee must set this value when \c ShouldExpand is \c true; it may 14243 /// set this value in other cases. 14244 /// 14245 /// \returns true if an error occurred (e.g., because the parameter packs 14246 /// are to be instantiated with arguments of different lengths), false 14247 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 14248 /// must be set. 14249 bool CheckParameterPacksForExpansion( 14250 SourceLocation EllipsisLoc, SourceRange PatternRange, 14251 ArrayRef<UnexpandedParameterPack> Unexpanded, 14252 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, 14253 bool &RetainExpansion, std::optional<unsigned> &NumExpansions); 14254 14255 /// Determine the number of arguments in the given pack expansion 14256 /// type. 14257 /// 14258 /// This routine assumes that the number of arguments in the expansion is 14259 /// consistent across all of the unexpanded parameter packs in its pattern. 14260 /// 14261 /// Returns an empty Optional if the type can't be expanded. 14262 std::optional<unsigned> getNumArgumentsInExpansion( 14263 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); 14264 14265 std::optional<unsigned> getNumArgumentsInExpansionFromUnexpanded( 14266 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, 14267 const MultiLevelTemplateArgumentList &TemplateArgs); 14268 14269 /// Determine whether the given declarator contains any unexpanded 14270 /// parameter packs. 14271 /// 14272 /// This routine is used by the parser to disambiguate function declarators 14273 /// with an ellipsis prior to the ')', e.g., 14274 /// 14275 /// \code 14276 /// void f(T...); 14277 /// \endcode 14278 /// 14279 /// To determine whether we have an (unnamed) function parameter pack or 14280 /// a variadic function. 14281 /// 14282 /// \returns true if the declarator contains any unexpanded parameter packs, 14283 /// false otherwise. 14284 bool containsUnexpandedParameterPacks(Declarator &D); 14285 14286 /// Returns the pattern of the pack expansion for a template argument. 14287 /// 14288 /// \param OrigLoc The template argument to expand. 14289 /// 14290 /// \param Ellipsis Will be set to the location of the ellipsis. 14291 /// 14292 /// \param NumExpansions Will be set to the number of expansions that will 14293 /// be generated from this pack expansion, if known a priori. 14294 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 14295 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, 14296 std::optional<unsigned> &NumExpansions) const; 14297 14298 /// Given a template argument that contains an unexpanded parameter pack, but 14299 /// which has already been substituted, attempt to determine the number of 14300 /// elements that will be produced once this argument is fully-expanded. 14301 /// 14302 /// This is intended for use when transforming 'sizeof...(Arg)' in order to 14303 /// avoid actually expanding the pack where possible. 14304 std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); 14305 14306 /// Called when an expression computing the size of a parameter pack 14307 /// is parsed. 14308 /// 14309 /// \code 14310 /// template<typename ...Types> struct count { 14311 /// static const unsigned value = sizeof...(Types); 14312 /// }; 14313 /// \endcode 14314 /// 14315 // 14316 /// \param OpLoc The location of the "sizeof" keyword. 14317 /// \param Name The name of the parameter pack whose size will be determined. 14318 /// \param NameLoc The source location of the name of the parameter pack. 14319 /// \param RParenLoc The location of the closing parentheses. 14320 ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, 14321 IdentifierInfo &Name, 14322 SourceLocation NameLoc, 14323 SourceLocation RParenLoc); 14324 14325 ExprResult ActOnPackIndexingExpr(Scope *S, Expr *PackExpression, 14326 SourceLocation EllipsisLoc, 14327 SourceLocation LSquareLoc, Expr *IndexExpr, 14328 SourceLocation RSquareLoc); 14329 14330 ExprResult BuildPackIndexingExpr(Expr *PackExpression, 14331 SourceLocation EllipsisLoc, Expr *IndexExpr, 14332 SourceLocation RSquareLoc, 14333 ArrayRef<Expr *> ExpandedExprs = {}, 14334 bool FullySubstituted = false); 14335 14336 /// Handle a C++1z fold-expression: ( expr op ... op expr ). 14337 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, 14338 tok::TokenKind Operator, 14339 SourceLocation EllipsisLoc, Expr *RHS, 14340 SourceLocation RParenLoc); 14341 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, 14342 SourceLocation LParenLoc, Expr *LHS, 14343 BinaryOperatorKind Operator, 14344 SourceLocation EllipsisLoc, Expr *RHS, 14345 SourceLocation RParenLoc, 14346 std::optional<unsigned> NumExpansions); 14347 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 14348 BinaryOperatorKind Operator); 14349 14350 ///@} 14351 14352 // 14353 // 14354 // ------------------------------------------------------------------------- 14355 // 14356 // 14357 14358 /// \name Constraints and Concepts 14359 /// Implementations are in SemaConcept.cpp 14360 ///@{ 14361 14362 public: 14363 void PushSatisfactionStackEntry(const NamedDecl *D, 14364 const llvm::FoldingSetNodeID &ID) { 14365 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl()); 14366 SatisfactionStack.emplace_back(Can, ID); 14367 } 14368 14369 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); } 14370 14371 bool SatisfactionStackContains(const NamedDecl *D, 14372 const llvm::FoldingSetNodeID &ID) const { 14373 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl()); 14374 return llvm::find(SatisfactionStack, SatisfactionStackEntryTy{Can, ID}) != 14375 SatisfactionStack.end(); 14376 } 14377 14378 using SatisfactionStackEntryTy = 14379 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>; 14380 14381 // Resets the current SatisfactionStack for cases where we are instantiating 14382 // constraints as a 'side effect' of normal instantiation in a way that is not 14383 // indicative of recursive definition. 14384 class SatisfactionStackResetRAII { 14385 llvm::SmallVector<SatisfactionStackEntryTy, 10> BackupSatisfactionStack; 14386 Sema &SemaRef; 14387 14388 public: 14389 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) { 14390 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack); 14391 } 14392 14393 ~SatisfactionStackResetRAII() { 14394 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack); 14395 } 14396 }; 14397 14398 void SwapSatisfactionStack( 14399 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) { 14400 SatisfactionStack.swap(NewSS); 14401 } 14402 14403 /// Check whether the given expression is a valid constraint expression. 14404 /// A diagnostic is emitted if it is not, false is returned, and 14405 /// PossibleNonPrimary will be set to true if the failure might be due to a 14406 /// non-primary expression being used as an atomic constraint. 14407 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), 14408 bool *PossibleNonPrimary = nullptr, 14409 bool IsTrailingRequiresClause = false); 14410 14411 /// \brief Check whether the given list of constraint expressions are 14412 /// satisfied (as if in a 'conjunction') given template arguments. 14413 /// \param Template the template-like entity that triggered the constraints 14414 /// check (either a concept or a constrained entity). 14415 /// \param ConstraintExprs a list of constraint expressions, treated as if 14416 /// they were 'AND'ed together. 14417 /// \param TemplateArgLists the list of template arguments to substitute into 14418 /// the constraint expression. 14419 /// \param TemplateIDRange The source range of the template id that 14420 /// caused the constraints check. 14421 /// \param Satisfaction if true is returned, will contain details of the 14422 /// satisfaction, with enough information to diagnose an unsatisfied 14423 /// expression. 14424 /// \returns true if an error occurred and satisfaction could not be checked, 14425 /// false otherwise. 14426 bool CheckConstraintSatisfaction( 14427 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 14428 const MultiLevelTemplateArgumentList &TemplateArgLists, 14429 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) { 14430 llvm::SmallVector<Expr *, 4> Converted; 14431 return CheckConstraintSatisfaction(Template, ConstraintExprs, Converted, 14432 TemplateArgLists, TemplateIDRange, 14433 Satisfaction); 14434 } 14435 14436 /// \brief Check whether the given list of constraint expressions are 14437 /// satisfied (as if in a 'conjunction') given template arguments. 14438 /// Additionally, takes an empty list of Expressions which is populated with 14439 /// the instantiated versions of the ConstraintExprs. 14440 /// \param Template the template-like entity that triggered the constraints 14441 /// check (either a concept or a constrained entity). 14442 /// \param ConstraintExprs a list of constraint expressions, treated as if 14443 /// they were 'AND'ed together. 14444 /// \param ConvertedConstraints a out parameter that will get populated with 14445 /// the instantiated version of the ConstraintExprs if we successfully checked 14446 /// satisfaction. 14447 /// \param TemplateArgList the multi-level list of template arguments to 14448 /// substitute into the constraint expression. This should be relative to the 14449 /// top-level (hence multi-level), since we need to instantiate fully at the 14450 /// time of checking. 14451 /// \param TemplateIDRange The source range of the template id that 14452 /// caused the constraints check. 14453 /// \param Satisfaction if true is returned, will contain details of the 14454 /// satisfaction, with enough information to diagnose an unsatisfied 14455 /// expression. 14456 /// \returns true if an error occurred and satisfaction could not be checked, 14457 /// false otherwise. 14458 bool CheckConstraintSatisfaction( 14459 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 14460 llvm::SmallVectorImpl<Expr *> &ConvertedConstraints, 14461 const MultiLevelTemplateArgumentList &TemplateArgList, 14462 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); 14463 14464 /// \brief Check whether the given non-dependent constraint expression is 14465 /// satisfied. Returns false and updates Satisfaction with the satisfaction 14466 /// verdict if successful, emits a diagnostic and returns true if an error 14467 /// occurred and satisfaction could not be determined. 14468 /// 14469 /// \returns true if an error occurred, false otherwise. 14470 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, 14471 ConstraintSatisfaction &Satisfaction); 14472 14473 /// Check whether the given function decl's trailing requires clause is 14474 /// satisfied, if any. Returns false and updates Satisfaction with the 14475 /// satisfaction verdict if successful, emits a diagnostic and returns true if 14476 /// an error occurred and satisfaction could not be determined. 14477 /// 14478 /// \returns true if an error occurred, false otherwise. 14479 bool CheckFunctionConstraints(const FunctionDecl *FD, 14480 ConstraintSatisfaction &Satisfaction, 14481 SourceLocation UsageLoc = SourceLocation(), 14482 bool ForOverloadResolution = false); 14483 14484 // Calculates whether two constraint expressions are equal irrespective of a 14485 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and 14486 // 'New', which are the "source" of the constraint, since this is necessary 14487 // for figuring out the relative 'depth' of the constraint. The depth of the 14488 // 'primary template' and the 'instantiated from' templates aren't necessarily 14489 // the same, such as a case when one is a 'friend' defined in a class. 14490 bool AreConstraintExpressionsEqual(const NamedDecl *Old, 14491 const Expr *OldConstr, 14492 const TemplateCompareNewDeclInfo &New, 14493 const Expr *NewConstr); 14494 14495 // Calculates whether the friend function depends on an enclosing template for 14496 // the purposes of [temp.friend] p9. 14497 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD); 14498 14499 /// \brief Ensure that the given template arguments satisfy the constraints 14500 /// associated with the given template, emitting a diagnostic if they do not. 14501 /// 14502 /// \param Template The template to which the template arguments are being 14503 /// provided. 14504 /// 14505 /// \param TemplateArgs The converted, canonicalized template arguments. 14506 /// 14507 /// \param TemplateIDRange The source range of the template id that 14508 /// caused the constraints check. 14509 /// 14510 /// \returns true if the constrains are not satisfied or could not be checked 14511 /// for satisfaction, false if the constraints are satisfied. 14512 bool EnsureTemplateArgumentListConstraints( 14513 TemplateDecl *Template, 14514 const MultiLevelTemplateArgumentList &TemplateArgs, 14515 SourceRange TemplateIDRange); 14516 14517 bool CheckInstantiatedFunctionTemplateConstraints( 14518 SourceLocation PointOfInstantiation, FunctionDecl *Decl, 14519 ArrayRef<TemplateArgument> TemplateArgs, 14520 ConstraintSatisfaction &Satisfaction); 14521 14522 /// \brief Emit diagnostics explaining why a constraint expression was deemed 14523 /// unsatisfied. 14524 /// \param First whether this is the first time an unsatisfied constraint is 14525 /// diagnosed for this error. 14526 void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, 14527 bool First = true); 14528 14529 /// \brief Emit diagnostics explaining why a constraint expression was deemed 14530 /// unsatisfied. 14531 void 14532 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, 14533 bool First = true); 14534 14535 const NormalizedConstraint *getNormalizedAssociatedConstraints( 14536 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); 14537 14538 /// \brief Check whether the given declaration's associated constraints are 14539 /// at least as constrained than another declaration's according to the 14540 /// partial ordering of constraints. 14541 /// 14542 /// \param Result If no error occurred, receives the result of true if D1 is 14543 /// at least constrained than D2, and false otherwise. 14544 /// 14545 /// \returns true if an error occurred, false otherwise. 14546 bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef<const Expr *> AC1, 14547 NamedDecl *D2, MutableArrayRef<const Expr *> AC2, 14548 bool &Result); 14549 14550 /// If D1 was not at least as constrained as D2, but would've been if a pair 14551 /// of atomic constraints involved had been declared in a concept and not 14552 /// repeated in two separate places in code. 14553 /// \returns true if such a diagnostic was emitted, false otherwise. 14554 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic( 14555 NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, 14556 ArrayRef<const Expr *> AC2); 14557 14558 private: 14559 /// Caches pairs of template-like decls whose associated constraints were 14560 /// checked for subsumption and whether or not the first's constraints did in 14561 /// fact subsume the second's. 14562 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; 14563 /// Caches the normalized associated constraints of declarations (concepts or 14564 /// constrained declarations). If an error occurred while normalizing the 14565 /// associated constraints of the template or concept, nullptr will be cached 14566 /// here. 14567 llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; 14568 14569 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> 14570 SatisfactionCache; 14571 14572 // The current stack of constraint satisfactions, so we can exit-early. 14573 llvm::SmallVector<SatisfactionStackEntryTy, 10> SatisfactionStack; 14574 14575 /// Used by SetupConstraintCheckingTemplateArgumentsAndScope to set up the 14576 /// LocalInstantiationScope of the current non-lambda function. For lambdas, 14577 /// use LambdaScopeForCallOperatorInstantiationRAII. 14578 bool 14579 SetupConstraintScope(FunctionDecl *FD, 14580 std::optional<ArrayRef<TemplateArgument>> TemplateArgs, 14581 const MultiLevelTemplateArgumentList &MLTAL, 14582 LocalInstantiationScope &Scope); 14583 14584 /// Used during constraint checking, sets up the constraint template argument 14585 /// lists, and calls SetupConstraintScope to set up the 14586 /// LocalInstantiationScope to have the proper set of ParVarDecls configured. 14587 std::optional<MultiLevelTemplateArgumentList> 14588 SetupConstraintCheckingTemplateArgumentsAndScope( 14589 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, 14590 LocalInstantiationScope &Scope); 14591 14592 ///@} 14593 14594 // 14595 // 14596 // ------------------------------------------------------------------------- 14597 // 14598 // 14599 14600 /// \name Types 14601 /// Implementations are in SemaType.cpp 14602 ///@{ 14603 14604 public: 14605 /// A mapping that describes the nullability we've seen in each header file. 14606 FileNullabilityMap NullabilityMap; 14607 14608 static int getPrintable(int I) { return I; } 14609 static unsigned getPrintable(unsigned I) { return I; } 14610 static bool getPrintable(bool B) { return B; } 14611 static const char *getPrintable(const char *S) { return S; } 14612 static StringRef getPrintable(StringRef S) { return S; } 14613 static const std::string &getPrintable(const std::string &S) { return S; } 14614 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 14615 return II; 14616 } 14617 static DeclarationName getPrintable(DeclarationName N) { return N; } 14618 static QualType getPrintable(QualType T) { return T; } 14619 static SourceRange getPrintable(SourceRange R) { return R; } 14620 static SourceRange getPrintable(SourceLocation L) { return L; } 14621 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } 14622 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange(); } 14623 14624 enum class CompleteTypeKind { 14625 /// Apply the normal rules for complete types. In particular, 14626 /// treat all sizeless types as incomplete. 14627 Normal, 14628 14629 /// Relax the normal rules for complete types so that they include 14630 /// sizeless built-in types. 14631 AcceptSizeless, 14632 14633 // FIXME: Eventually we should flip the default to Normal and opt in 14634 // to AcceptSizeless rather than opt out of it. 14635 Default = AcceptSizeless 14636 }; 14637 14638 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 14639 const DeclSpec *DS = nullptr); 14640 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 14641 const DeclSpec *DS = nullptr); 14642 14643 /// Build a pointer type. 14644 /// 14645 /// \param T The type to which we'll be building a pointer. 14646 /// 14647 /// \param Loc The location of the entity whose type involves this 14648 /// pointer type or, if there is no such entity, the location of the 14649 /// type that will have pointer type. 14650 /// 14651 /// \param Entity The name of the entity that involves the pointer 14652 /// type, if known. 14653 /// 14654 /// \returns A suitable pointer type, if there are no 14655 /// errors. Otherwise, returns a NULL type. 14656 QualType BuildPointerType(QualType T, SourceLocation Loc, 14657 DeclarationName Entity); 14658 14659 /// Build a reference type. 14660 /// 14661 /// \param T The type to which we'll be building a reference. 14662 /// 14663 /// \param Loc The location of the entity whose type involves this 14664 /// reference type or, if there is no such entity, the location of the 14665 /// type that will have reference type. 14666 /// 14667 /// \param Entity The name of the entity that involves the reference 14668 /// type, if known. 14669 /// 14670 /// \returns A suitable reference type, if there are no 14671 /// errors. Otherwise, returns a NULL type. 14672 QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, 14673 DeclarationName Entity); 14674 14675 /// Build an array type. 14676 /// 14677 /// \param T The type of each element in the array. 14678 /// 14679 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 14680 /// 14681 /// \param ArraySize Expression describing the size of the array. 14682 /// 14683 /// \param Brackets The range from the opening '[' to the closing ']'. 14684 /// 14685 /// \param Entity The name of the entity that involves the array 14686 /// type, if known. 14687 /// 14688 /// \returns A suitable array type, if there are no errors. Otherwise, 14689 /// returns a NULL type. 14690 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, 14691 unsigned Quals, SourceRange Brackets, 14692 DeclarationName Entity); 14693 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); 14694 14695 /// Build an ext-vector type. 14696 /// 14697 /// Run the required checks for the extended vector type. 14698 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 14699 SourceLocation AttrLoc); 14700 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, 14701 SourceLocation AttrLoc); 14702 14703 QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, 14704 Expr *CountExpr, 14705 bool CountInBytes, 14706 bool OrNull); 14707 14708 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an 14709 /// expression is uninstantiated. If instantiated it will apply the 14710 /// appropriate address space to the type. This function allows dependent 14711 /// template variables to be used in conjunction with the address_space 14712 /// attribute 14713 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 14714 SourceLocation AttrLoc); 14715 14716 /// Same as above, but constructs the AddressSpace index if not provided. 14717 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 14718 SourceLocation AttrLoc); 14719 14720 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); 14721 14722 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 14723 14724 /// Build a function type. 14725 /// 14726 /// This routine checks the function type according to C++ rules and 14727 /// under the assumption that the result type and parameter types have 14728 /// just been instantiated from a template. It therefore duplicates 14729 /// some of the behavior of GetTypeForDeclarator, but in a much 14730 /// simpler form that is only suitable for this narrow use case. 14731 /// 14732 /// \param T The return type of the function. 14733 /// 14734 /// \param ParamTypes The parameter types of the function. This array 14735 /// will be modified to account for adjustments to the types of the 14736 /// function parameters. 14737 /// 14738 /// \param Loc The location of the entity whose type involves this 14739 /// function type or, if there is no such entity, the location of the 14740 /// type that will have function type. 14741 /// 14742 /// \param Entity The name of the entity that involves the function 14743 /// type, if known. 14744 /// 14745 /// \param EPI Extra information about the function type. Usually this will 14746 /// be taken from an existing function with the same prototype. 14747 /// 14748 /// \returns A suitable function type, if there are no errors. The 14749 /// unqualified type will always be a FunctionProtoType. 14750 /// Otherwise, returns a NULL type. 14751 QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, 14752 SourceLocation Loc, DeclarationName Entity, 14753 const FunctionProtoType::ExtProtoInfo &EPI); 14754 14755 /// Build a member pointer type \c T Class::*. 14756 /// 14757 /// \param T the type to which the member pointer refers. 14758 /// \param Class the class type into which the member pointer points. 14759 /// \param Loc the location where this type begins 14760 /// \param Entity the name of the entity that will have this member pointer 14761 /// type 14762 /// 14763 /// \returns a member pointer type, if successful, or a NULL type if there was 14764 /// an error. 14765 QualType BuildMemberPointerType(QualType T, QualType Class, 14766 SourceLocation Loc, DeclarationName Entity); 14767 14768 /// Build a block pointer type. 14769 /// 14770 /// \param T The type to which we'll be building a block pointer. 14771 /// 14772 /// \param Loc The source location, used for diagnostics. 14773 /// 14774 /// \param Entity The name of the entity that involves the block pointer 14775 /// type, if known. 14776 /// 14777 /// \returns A suitable block pointer type, if there are no 14778 /// errors. Otherwise, returns a NULL type. 14779 QualType BuildBlockPointerType(QualType T, SourceLocation Loc, 14780 DeclarationName Entity); 14781 14782 /// Build a paren type including \p T. 14783 QualType BuildParenType(QualType T); 14784 QualType BuildAtomicType(QualType T, SourceLocation Loc); 14785 14786 /// Build a Read-only Pipe type. 14787 /// 14788 /// \param T The type to which we'll be building a Pipe. 14789 /// 14790 /// \param Loc We do not use it for now. 14791 /// 14792 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns 14793 /// a NULL type. 14794 QualType BuildReadPipeType(QualType T, SourceLocation Loc); 14795 14796 /// Build a Write-only Pipe type. 14797 /// 14798 /// \param T The type to which we'll be building a Pipe. 14799 /// 14800 /// \param Loc We do not use it for now. 14801 /// 14802 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns 14803 /// a NULL type. 14804 QualType BuildWritePipeType(QualType T, SourceLocation Loc); 14805 14806 /// Build a bit-precise integer type. 14807 /// 14808 /// \param IsUnsigned Boolean representing the signedness of the type. 14809 /// 14810 /// \param BitWidth Size of this int type in bits, or an expression 14811 /// representing that. 14812 /// 14813 /// \param Loc Location of the keyword. 14814 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); 14815 14816 /// GetTypeForDeclarator - Convert the type for the specified 14817 /// declarator to Type instances. 14818 /// 14819 /// The result of this call will never be null, but the associated 14820 /// type may be a null type if there's an unrecoverable error. 14821 TypeSourceInfo *GetTypeForDeclarator(Declarator &D); 14822 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 14823 14824 /// Package the given type and TSI into a ParsedType. 14825 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 14826 static QualType GetTypeFromParser(ParsedType Ty, 14827 TypeSourceInfo **TInfo = nullptr); 14828 14829 TypeResult ActOnTypeName(Declarator &D); 14830 14831 // Check whether the size of array element of type \p EltTy is a multiple of 14832 // its alignment and return false if it isn't. 14833 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc); 14834 14835 void 14836 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 14837 SourceLocation FallbackLoc, 14838 SourceLocation ConstQualLoc = SourceLocation(), 14839 SourceLocation VolatileQualLoc = SourceLocation(), 14840 SourceLocation RestrictQualLoc = SourceLocation(), 14841 SourceLocation AtomicQualLoc = SourceLocation(), 14842 SourceLocation UnalignedQualLoc = SourceLocation()); 14843 14844 /// Retrieve the keyword associated 14845 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); 14846 14847 /// Adjust the calling convention of a method to be the ABI default if it 14848 /// wasn't specified explicitly. This handles method types formed from 14849 /// function type typedefs and typename template arguments. 14850 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, 14851 bool IsCtorOrDtor, SourceLocation Loc); 14852 14853 // Check if there is an explicit attribute, but only look through parens. 14854 // The intent is to look for an attribute on the current declarator, but not 14855 // one that came from a typedef. 14856 bool hasExplicitCallingConv(QualType T); 14857 14858 /// Check whether a nullability type specifier can be added to the given 14859 /// type through some means not written in source (e.g. API notes). 14860 /// 14861 /// \param Type The type to which the nullability specifier will be 14862 /// added. On success, this type will be updated appropriately. 14863 /// 14864 /// \param Nullability The nullability specifier to add. 14865 /// 14866 /// \param DiagLoc The location to use for diagnostics. 14867 /// 14868 /// \param AllowArrayTypes Whether to accept nullability specifiers on an 14869 /// array type (e.g., because it will decay to a pointer). 14870 /// 14871 /// \param OverrideExisting Whether to override an existing, locally-specified 14872 /// nullability specifier rather than complaining about the conflict. 14873 /// 14874 /// \returns true if nullability cannot be applied, false otherwise. 14875 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, 14876 NullabilityKind Nullability, 14877 SourceLocation DiagLoc, 14878 bool AllowArrayTypes, 14879 bool OverrideExisting); 14880 14881 /// Get the type of expression E, triggering instantiation to complete the 14882 /// type if necessary -- that is, if the expression refers to a templated 14883 /// static data member of incomplete array type. 14884 /// 14885 /// May still return an incomplete type if instantiation was not possible or 14886 /// if the type is incomplete for a different reason. Use 14887 /// RequireCompleteExprType instead if a diagnostic is expected for an 14888 /// incomplete expression type. 14889 QualType getCompletedType(Expr *E); 14890 14891 void completeExprArrayBound(Expr *E); 14892 14893 /// Ensure that the type of the given expression is complete. 14894 /// 14895 /// This routine checks whether the expression \p E has a complete type. If 14896 /// the expression refers to an instantiable construct, that instantiation is 14897 /// performed as needed to complete its type. Furthermore 14898 /// Sema::RequireCompleteType is called for the expression's type (or in the 14899 /// case of a reference type, the referred-to type). 14900 /// 14901 /// \param E The expression whose type is required to be complete. 14902 /// \param Kind Selects which completeness rules should be applied. 14903 /// \param Diagnoser The object that will emit a diagnostic if the type is 14904 /// incomplete. 14905 /// 14906 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false 14907 /// otherwise. 14908 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 14909 TypeDiagnoser &Diagnoser); 14910 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 14911 14912 template <typename... Ts> 14913 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { 14914 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 14915 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 14916 } 14917 14918 /// Retrieve a version of the type 'T' that is elaborated by Keyword, 14919 /// qualified by the nested-name-specifier contained in SS, and that is 14920 /// (re)declared by OwnedTagDecl, which is nullptr if this is not a 14921 /// (re)declaration. 14922 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 14923 const CXXScopeSpec &SS, QualType T, 14924 TagDecl *OwnedTagDecl = nullptr); 14925 14926 // Returns the underlying type of a decltype with the given expression. 14927 QualType getDecltypeForExpr(Expr *E); 14928 14929 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind); 14930 /// If AsUnevaluated is false, E is treated as though it were an evaluated 14931 /// context, such as when building a type for decltype(auto). 14932 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true); 14933 14934 QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, 14935 SourceLocation Loc, 14936 SourceLocation EllipsisLoc); 14937 QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, 14938 SourceLocation Loc, SourceLocation EllipsisLoc, 14939 bool FullySubstituted = false, 14940 ArrayRef<QualType> Expansions = {}); 14941 14942 using UTTKind = UnaryTransformType::UTTKind; 14943 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, 14944 SourceLocation Loc); 14945 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc); 14946 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc); 14947 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc); 14948 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc); 14949 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, 14950 SourceLocation Loc); 14951 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, 14952 SourceLocation Loc); 14953 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, 14954 SourceLocation Loc); 14955 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, 14956 SourceLocation Loc); 14957 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, 14958 SourceLocation Loc); 14959 14960 /// Ensure that the type T is a literal type. 14961 /// 14962 /// This routine checks whether the type @p T is a literal type. If @p T is an 14963 /// incomplete type, an attempt is made to complete it. If @p T is a literal 14964 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type, 14965 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving 14966 /// it the type @p T), along with notes explaining why the type is not a 14967 /// literal type, and returns true. 14968 /// 14969 /// @param Loc The location in the source that the non-literal type 14970 /// diagnostic should refer to. 14971 /// 14972 /// @param T The type that this routine is examining for literalness. 14973 /// 14974 /// @param Diagnoser Emits a diagnostic if T is not a literal type. 14975 /// 14976 /// @returns @c true if @p T is not a literal type and a diagnostic was 14977 /// emitted, @c false otherwise. 14978 bool RequireLiteralType(SourceLocation Loc, QualType T, 14979 TypeDiagnoser &Diagnoser); 14980 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 14981 14982 template <typename... Ts> 14983 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, 14984 const Ts &...Args) { 14985 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 14986 return RequireLiteralType(Loc, T, Diagnoser); 14987 } 14988 14989 bool isCompleteType(SourceLocation Loc, QualType T, 14990 CompleteTypeKind Kind = CompleteTypeKind::Default) { 14991 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); 14992 } 14993 14994 /// Ensure that the type T is a complete type. 14995 /// 14996 /// This routine checks whether the type @p T is complete in any 14997 /// context where a complete type is required. If @p T is a complete 14998 /// type, returns false. If @p T is a class template specialization, 14999 /// this routine then attempts to perform class template 15000 /// instantiation. If instantiation fails, or if @p T is incomplete 15001 /// and cannot be completed, issues the diagnostic @p diag (giving it 15002 /// the type @p T) and returns true. 15003 /// 15004 /// @param Loc The location in the source that the incomplete type 15005 /// diagnostic should refer to. 15006 /// 15007 /// @param T The type that this routine is examining for completeness. 15008 /// 15009 /// @param Kind Selects which completeness rules should be applied. 15010 /// 15011 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 15012 /// @c false otherwise. 15013 bool RequireCompleteType(SourceLocation Loc, QualType T, 15014 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); 15015 bool RequireCompleteType(SourceLocation Loc, QualType T, 15016 CompleteTypeKind Kind, unsigned DiagID); 15017 15018 bool RequireCompleteType(SourceLocation Loc, QualType T, 15019 TypeDiagnoser &Diagnoser) { 15020 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); 15021 } 15022 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { 15023 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); 15024 } 15025 15026 template <typename... Ts> 15027 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, 15028 const Ts &...Args) { 15029 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 15030 return RequireCompleteType(Loc, T, Diagnoser); 15031 } 15032 15033 /// Determine whether a declaration is visible to name lookup. 15034 bool isVisible(const NamedDecl *D) { 15035 return D->isUnconditionallyVisible() || 15036 isAcceptableSlow(D, AcceptableKind::Visible); 15037 } 15038 15039 /// Determine whether a declaration is reachable. 15040 bool isReachable(const NamedDecl *D) { 15041 // All visible declarations are reachable. 15042 return D->isUnconditionallyVisible() || 15043 isAcceptableSlow(D, AcceptableKind::Reachable); 15044 } 15045 15046 /// Determine whether a declaration is acceptable (visible/reachable). 15047 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) { 15048 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D); 15049 } 15050 15051 /// Determine if \p D and \p Suggested have a structurally compatible 15052 /// layout as described in C11 6.2.7/1. 15053 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); 15054 15055 /// Determine if \p D has a visible definition. If not, suggest a declaration 15056 /// that should be made visible to expose the definition. 15057 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 15058 bool OnlyNeedComplete = false); 15059 bool hasVisibleDefinition(const NamedDecl *D) { 15060 NamedDecl *Hidden; 15061 return hasVisibleDefinition(const_cast<NamedDecl *>(D), &Hidden); 15062 } 15063 15064 /// Determine if \p D has a reachable definition. If not, suggest a 15065 /// declaration that should be made reachable to expose the definition. 15066 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, 15067 bool OnlyNeedComplete = false); 15068 bool hasReachableDefinition(NamedDecl *D) { 15069 NamedDecl *Hidden; 15070 return hasReachableDefinition(D, &Hidden); 15071 } 15072 15073 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, 15074 AcceptableKind Kind, 15075 bool OnlyNeedComplete = false); 15076 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) { 15077 NamedDecl *Hidden; 15078 return hasAcceptableDefinition(D, &Hidden, Kind); 15079 } 15080 15081 /// Try to parse the conditional expression attached to an effect attribute 15082 /// (e.g. 'nonblocking'). (c.f. Sema::ActOnNoexceptSpec). Return an empty 15083 /// optional on error. 15084 std::optional<FunctionEffectMode> 15085 ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName); 15086 15087 private: 15088 /// The implementation of RequireCompleteType 15089 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 15090 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); 15091 15092 /// Nullability type specifiers. 15093 IdentifierInfo *Ident__Nonnull = nullptr; 15094 IdentifierInfo *Ident__Nullable = nullptr; 15095 IdentifierInfo *Ident__Nullable_result = nullptr; 15096 IdentifierInfo *Ident__Null_unspecified = nullptr; 15097 15098 ///@} 15099 15100 // 15101 // 15102 // ------------------------------------------------------------------------- 15103 // 15104 // 15105 15106 /// \name FixIt Helpers 15107 /// Implementations are in SemaFixItUtils.cpp 15108 ///@{ 15109 15110 public: 15111 /// Get a string to suggest for zero-initialization of a type. 15112 std::string getFixItZeroInitializerForType(QualType T, 15113 SourceLocation Loc) const; 15114 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 15115 15116 ///@} 15117 15118 // 15119 // 15120 // ------------------------------------------------------------------------- 15121 // 15122 // 15123 15124 /// \name Function Effects 15125 /// Implementations are in SemaFunctionEffects.cpp 15126 ///@{ 15127 public: 15128 struct FunctionEffectDiff { 15129 enum class Kind { Added, Removed, ConditionMismatch }; 15130 15131 FunctionEffect::Kind EffectKind; 15132 Kind DiffKind; 15133 std::optional<FunctionEffectWithCondition> 15134 Old; // Invalid when 'Kind' is 'Added'. 15135 std::optional<FunctionEffectWithCondition> 15136 New; // Invalid when 'Kind' is 'Removed'. 15137 15138 StringRef effectName() const { 15139 if (Old) 15140 return Old.value().Effect.name(); 15141 return New.value().Effect.name(); 15142 } 15143 15144 /// Describes the result of effects differing between a base class's virtual 15145 /// method and an overriding method in a subclass. 15146 enum class OverrideResult { 15147 NoAction, 15148 Warn, 15149 Merge // Merge missing effect from base to derived. 15150 }; 15151 15152 /// Return true if adding or removing the effect as part of a type 15153 /// conversion should generate a diagnostic. 15154 bool shouldDiagnoseConversion(QualType SrcType, 15155 const FunctionEffectsRef &SrcFX, 15156 QualType DstType, 15157 const FunctionEffectsRef &DstFX) const; 15158 15159 /// Return true if adding or removing the effect in a redeclaration should 15160 /// generate a diagnostic. 15161 bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction, 15162 const FunctionEffectsRef &OldFX, 15163 const FunctionDecl &NewFunction, 15164 const FunctionEffectsRef &NewFX) const; 15165 15166 /// Return true if adding or removing the effect in a C++ virtual method 15167 /// override should generate a diagnostic. 15168 OverrideResult shouldDiagnoseMethodOverride( 15169 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX, 15170 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const; 15171 }; 15172 15173 struct FunctionEffectDiffVector : public SmallVector<FunctionEffectDiff> { 15174 /// Caller should short-circuit by checking for equality first. 15175 FunctionEffectDiffVector(const FunctionEffectsRef &Old, 15176 const FunctionEffectsRef &New); 15177 }; 15178 15179 /// All functions/lambdas/blocks which have bodies and which have a non-empty 15180 /// FunctionEffectsRef to be verified. 15181 SmallVector<const Decl *> DeclsWithEffectsToVerify; 15182 15183 /// The union of all effects present on DeclsWithEffectsToVerify. Conditions 15184 /// are all null. 15185 FunctionEffectKindSet AllEffectsToVerify; 15186 15187 public: 15188 /// Warn and return true if adding a function effect to a set would create a 15189 /// conflict. 15190 bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, 15191 const FunctionEffectWithCondition &EC, 15192 SourceLocation NewAttrLoc); 15193 15194 // Report a failure to merge function effects between declarations due to a 15195 // conflict. 15196 void 15197 diagnoseFunctionEffectMergeConflicts(const FunctionEffectSet::Conflicts &Errs, 15198 SourceLocation NewLoc, 15199 SourceLocation OldLoc); 15200 15201 /// Inline checks from the start of maybeAddDeclWithEffects, to 15202 /// minimize performance impact on code not using effects. 15203 template <class FuncOrBlockDecl> 15204 void maybeAddDeclWithEffects(FuncOrBlockDecl *D) { 15205 if (Context.hasAnyFunctionEffects()) 15206 if (FunctionEffectsRef FX = D->getFunctionEffects(); !FX.empty()) 15207 maybeAddDeclWithEffects(D, FX); 15208 } 15209 15210 /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify. 15211 void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX); 15212 15213 /// Unconditionally add a Decl to DeclsWithEfffectsToVerify. 15214 void addDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX); 15215 15216 void performFunctionEffectAnalysis(TranslationUnitDecl *TU); 15217 15218 ///@} 15219 }; 15220 15221 DeductionFailureInfo 15222 MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, 15223 sema::TemplateDeductionInfo &Info); 15224 15225 /// Contains a late templated function. 15226 /// Will be parsed at the end of the translation unit, used by Sema & Parser. 15227 struct LateParsedTemplate { 15228 CachedTokens Toks; 15229 /// The template function declaration to be late parsed. 15230 Decl *D; 15231 /// Floating-point options in the point of definition. 15232 FPOptions FPO; 15233 }; 15234 15235 template <> 15236 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, 15237 PragmaMsStackAction Action, 15238 llvm::StringRef StackSlotLabel, 15239 AlignPackInfo Value); 15240 } // end namespace clang 15241 15242 #endif 15243