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/ASTConcept.h" 19 #include "clang/AST/ASTFwd.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/Availability.h" 22 #include "clang/AST/ComparisonCategories.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprConcepts.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/ExprOpenMP.h" 30 #include "clang/AST/ExternalASTSource.h" 31 #include "clang/AST/LocInfoType.h" 32 #include "clang/AST/MangleNumberingContext.h" 33 #include "clang/AST/NSAPI.h" 34 #include "clang/AST/PrettyPrinter.h" 35 #include "clang/AST/StmtCXX.h" 36 #include "clang/AST/StmtOpenMP.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/TypeOrdering.h" 39 #include "clang/Basic/BitmaskEnum.h" 40 #include "clang/Basic/Builtins.h" 41 #include "clang/Basic/DarwinSDKInfo.h" 42 #include "clang/Basic/ExpressionTraits.h" 43 #include "clang/Basic/Module.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OpenMPKinds.h" 46 #include "clang/Basic/PragmaKinds.h" 47 #include "clang/Basic/Specifiers.h" 48 #include "clang/Basic/TemplateKinds.h" 49 #include "clang/Basic/TypeTraits.h" 50 #include "clang/Sema/AnalysisBasedWarnings.h" 51 #include "clang/Sema/CleanupInfo.h" 52 #include "clang/Sema/DeclSpec.h" 53 #include "clang/Sema/ExternalSemaSource.h" 54 #include "clang/Sema/IdentifierResolver.h" 55 #include "clang/Sema/ObjCMethodList.h" 56 #include "clang/Sema/Ownership.h" 57 #include "clang/Sema/Scope.h" 58 #include "clang/Sema/SemaConcept.h" 59 #include "clang/Sema/TypoCorrection.h" 60 #include "clang/Sema/Weak.h" 61 #include "llvm/ADT/ArrayRef.h" 62 #include "llvm/ADT/SetVector.h" 63 #include "llvm/ADT/SmallBitVector.h" 64 #include "llvm/ADT/SmallPtrSet.h" 65 #include "llvm/ADT/SmallSet.h" 66 #include "llvm/ADT/SmallVector.h" 67 #include "llvm/ADT/TinyPtrVector.h" 68 #include "llvm/Frontend/OpenMP/OMPConstants.h" 69 #include <deque> 70 #include <memory> 71 #include <optional> 72 #include <string> 73 #include <tuple> 74 #include <vector> 75 76 namespace llvm { 77 class APSInt; 78 template <typename ValueT, typename ValueInfoT> class DenseSet; 79 class SmallBitVector; 80 struct InlineAsmIdentifierInfo; 81 } 82 83 namespace clang { 84 class ADLResult; 85 class ASTConsumer; 86 class ASTContext; 87 class ASTMutationListener; 88 class ASTReader; 89 class ASTWriter; 90 class ArrayType; 91 class ParsedAttr; 92 class BindingDecl; 93 class BlockDecl; 94 class CapturedDecl; 95 class CXXBasePath; 96 class CXXBasePaths; 97 class CXXBindTemporaryExpr; 98 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 99 class CXXConstructorDecl; 100 class CXXConversionDecl; 101 class CXXDeleteExpr; 102 class CXXDestructorDecl; 103 class CXXFieldCollector; 104 class CXXMemberCallExpr; 105 class CXXMethodDecl; 106 class CXXScopeSpec; 107 class CXXTemporary; 108 class CXXTryStmt; 109 class CallExpr; 110 class ClassTemplateDecl; 111 class ClassTemplatePartialSpecializationDecl; 112 class ClassTemplateSpecializationDecl; 113 class VarTemplatePartialSpecializationDecl; 114 class CodeCompleteConsumer; 115 class CodeCompletionAllocator; 116 class CodeCompletionTUInfo; 117 class CodeCompletionResult; 118 class CoroutineBodyStmt; 119 class Decl; 120 class DeclAccessPair; 121 class DeclContext; 122 class DeclRefExpr; 123 class DeclaratorDecl; 124 class DeducedTemplateArgument; 125 class DependentDiagnostic; 126 class DesignatedInitExpr; 127 class Designation; 128 class EnableIfAttr; 129 class EnumConstantDecl; 130 class Expr; 131 class ExtVectorType; 132 class FormatAttr; 133 class FriendDecl; 134 class FunctionDecl; 135 class FunctionProtoType; 136 class FunctionTemplateDecl; 137 class ImplicitConversionSequence; 138 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; 139 class InitListExpr; 140 class InitializationKind; 141 class InitializationSequence; 142 class InitializedEntity; 143 class IntegerLiteral; 144 class LabelStmt; 145 class LambdaExpr; 146 class LangOptions; 147 class LocalInstantiationScope; 148 class LookupResult; 149 class MacroInfo; 150 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; 151 class ModuleLoader; 152 class MultiLevelTemplateArgumentList; 153 class NamedDecl; 154 class ObjCCategoryDecl; 155 class ObjCCategoryImplDecl; 156 class ObjCCompatibleAliasDecl; 157 class ObjCContainerDecl; 158 class ObjCImplDecl; 159 class ObjCImplementationDecl; 160 class ObjCInterfaceDecl; 161 class ObjCIvarDecl; 162 template <class T> class ObjCList; 163 class ObjCMessageExpr; 164 class ObjCMethodDecl; 165 class ObjCPropertyDecl; 166 class ObjCProtocolDecl; 167 class OMPThreadPrivateDecl; 168 class OMPRequiresDecl; 169 class OMPDeclareReductionDecl; 170 class OMPDeclareSimdDecl; 171 class OMPClause; 172 struct OMPVarListLocTy; 173 struct OverloadCandidate; 174 enum class OverloadCandidateParamOrder : char; 175 enum OverloadCandidateRewriteKind : unsigned; 176 class OverloadCandidateSet; 177 class OverloadExpr; 178 class ParenListExpr; 179 class ParmVarDecl; 180 class Preprocessor; 181 class PseudoDestructorTypeStorage; 182 class PseudoObjectExpr; 183 class QualType; 184 class StandardConversionSequence; 185 class Stmt; 186 class StringLiteral; 187 class SwitchStmt; 188 class TemplateArgument; 189 class TemplateArgumentList; 190 class TemplateArgumentLoc; 191 class TemplateDecl; 192 class TemplateInstantiationCallback; 193 class TemplateParameterList; 194 class TemplatePartialOrderingContext; 195 class TemplateTemplateParmDecl; 196 class Token; 197 class TypeAliasDecl; 198 class TypedefDecl; 199 class TypedefNameDecl; 200 class TypeLoc; 201 class TypoCorrectionConsumer; 202 class UnqualifiedId; 203 class UnresolvedLookupExpr; 204 class UnresolvedMemberExpr; 205 class UnresolvedSetImpl; 206 class UnresolvedSetIterator; 207 class UsingDecl; 208 class UsingShadowDecl; 209 class ValueDecl; 210 class VarDecl; 211 class VarTemplateSpecializationDecl; 212 class VisibilityAttr; 213 class VisibleDeclConsumer; 214 class IndirectFieldDecl; 215 struct DeductionFailureInfo; 216 class TemplateSpecCandidateSet; 217 218 namespace sema { 219 class AccessedEntity; 220 class BlockScopeInfo; 221 class Capture; 222 class CapturedRegionScopeInfo; 223 class CapturingScopeInfo; 224 class CompoundScopeInfo; 225 class DelayedDiagnostic; 226 class DelayedDiagnosticPool; 227 class FunctionScopeInfo; 228 class LambdaScopeInfo; 229 class PossiblyUnreachableDiag; 230 class RISCVIntrinsicManager; 231 class SemaPPCallbacks; 232 class TemplateDeductionInfo; 233 } 234 235 namespace threadSafety { 236 class BeforeSet; 237 void threadSafetyCleanup(BeforeSet* Cache); 238 } 239 240 // FIXME: No way to easily map from TemplateTypeParmTypes to 241 // TemplateTypeParmDecls, so we have this horrible PointerUnion. 242 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>, 243 SourceLocation> 244 UnexpandedParameterPack; 245 246 /// Describes whether we've seen any nullability information for the given 247 /// file. 248 struct FileNullability { 249 /// The first pointer declarator (of any pointer kind) in the file that does 250 /// not have a corresponding nullability annotation. 251 SourceLocation PointerLoc; 252 253 /// The end location for the first pointer declarator in the file. Used for 254 /// placing fix-its. 255 SourceLocation PointerEndLoc; 256 257 /// Which kind of pointer declarator we saw. 258 uint8_t PointerKind; 259 260 /// Whether we saw any type nullability annotations in the given file. 261 bool SawTypeNullability = false; 262 }; 263 264 /// A mapping from file IDs to a record of whether we've seen nullability 265 /// information in that file. 266 class FileNullabilityMap { 267 /// A mapping from file IDs to the nullability information for each file ID. 268 llvm::DenseMap<FileID, FileNullability> Map; 269 270 /// A single-element cache based on the file ID. 271 struct { 272 FileID File; 273 FileNullability Nullability; 274 } Cache; 275 276 public: 277 FileNullability &operator[](FileID file) { 278 // Check the single-element cache. 279 if (file == Cache.File) 280 return Cache.Nullability; 281 282 // It's not in the single-element cache; flush the cache if we have one. 283 if (!Cache.File.isInvalid()) { 284 Map[Cache.File] = Cache.Nullability; 285 } 286 287 // Pull this entry into the cache. 288 Cache.File = file; 289 Cache.Nullability = Map[file]; 290 return Cache.Nullability; 291 } 292 }; 293 294 /// Tracks expected type during expression parsing, for use in code completion. 295 /// The type is tied to a particular token, all functions that update or consume 296 /// the type take a start location of the token they are looking at as a 297 /// parameter. This avoids updating the type on hot paths in the parser. 298 class PreferredTypeBuilder { 299 public: PreferredTypeBuilder(bool Enabled)300 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} 301 302 void enterCondition(Sema &S, SourceLocation Tok); 303 void enterReturn(Sema &S, SourceLocation Tok); 304 void enterVariableInit(SourceLocation Tok, Decl *D); 305 /// Handles e.g. BaseType{ .D = Tok... 306 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, 307 const Designation &D); 308 /// Computing a type for the function argument may require running 309 /// overloading, so we postpone its computation until it is actually needed. 310 /// 311 /// Clients should be very careful when using this function, as it stores a 312 /// function_ref, clients should make sure all calls to get() with the same 313 /// location happen while function_ref is alive. 314 /// 315 /// The callback should also emit signature help as a side-effect, but only 316 /// if the completion point has been reached. 317 void enterFunctionArgument(SourceLocation Tok, 318 llvm::function_ref<QualType()> ComputeType); 319 320 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); 321 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, 322 SourceLocation OpLoc); 323 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); 324 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); 325 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); 326 /// Handles all type casts, including C-style cast, C++ casts, etc. 327 void enterTypeCast(SourceLocation Tok, QualType CastType); 328 329 /// Get the expected type associated with this location, if any. 330 /// 331 /// If the location is a function argument, determining the expected type 332 /// involves considering all function overloads and the arguments so far. 333 /// In this case, signature help for these function overloads will be reported 334 /// as a side-effect (only if the completion point has been reached). get(SourceLocation Tok)335 QualType get(SourceLocation Tok) const { 336 if (!Enabled || Tok != ExpectedLoc) 337 return QualType(); 338 if (!Type.isNull()) 339 return Type; 340 if (ComputeType) 341 return ComputeType(); 342 return QualType(); 343 } 344 345 private: 346 bool Enabled; 347 /// Start position of a token for which we store expected type. 348 SourceLocation ExpectedLoc; 349 /// Expected type for a token starting at ExpectedLoc. 350 QualType Type; 351 /// A function to compute expected type at ExpectedLoc. It is only considered 352 /// if Type is null. 353 llvm::function_ref<QualType()> ComputeType; 354 }; 355 356 /// Sema - This implements semantic analysis and AST building for C. 357 class Sema final { 358 Sema(const Sema &) = delete; 359 void operator=(const Sema &) = delete; 360 361 ///Source of additional semantic information. 362 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource; 363 364 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 365 366 /// Determine whether two declarations should be linked together, given that 367 /// the old declaration might not be visible and the new declaration might 368 /// not have external linkage. shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)369 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, 370 const NamedDecl *New) { 371 if (isVisible(Old)) 372 return true; 373 // See comment in below overload for why it's safe to compute the linkage 374 // of the new declaration here. 375 if (New->isExternallyDeclarable()) { 376 assert(Old->isExternallyDeclarable() && 377 "should not have found a non-externally-declarable previous decl"); 378 return true; 379 } 380 return false; 381 } 382 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); 383 384 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 385 QualType ResultTy, 386 ArrayRef<QualType> Args); 387 388 public: 389 /// The maximum alignment, same as in llvm::Value. We duplicate them here 390 /// because that allows us not to duplicate the constants in clang code, 391 /// which we must to since we can't directly use the llvm constants. 392 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp 393 /// 394 /// This is the greatest alignment value supported by load, store, and alloca 395 /// instructions, and global values. 396 static const unsigned MaxAlignmentExponent = 32; 397 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent; 398 399 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 400 typedef OpaquePtr<TemplateName> TemplateTy; 401 typedef OpaquePtr<QualType> TypeTy; 402 403 OpenCLOptions OpenCLFeatures; 404 FPOptions CurFPFeatures; 405 406 const LangOptions &LangOpts; 407 Preprocessor &PP; 408 ASTContext &Context; 409 ASTConsumer &Consumer; 410 DiagnosticsEngine &Diags; 411 SourceManager &SourceMgr; 412 api_notes::APINotesManager APINotes; 413 414 /// Flag indicating whether or not to collect detailed statistics. 415 bool CollectStats; 416 417 /// Code-completion consumer. 418 CodeCompleteConsumer *CodeCompleter; 419 420 /// CurContext - This is the current declaration context of parsing. 421 DeclContext *CurContext; 422 423 /// Generally null except when we temporarily switch decl contexts, 424 /// like in \see ActOnObjCTemporaryExitContainerContext. 425 DeclContext *OriginalLexicalContext; 426 427 /// VAListTagName - The declaration name corresponding to __va_list_tag. 428 /// This is used as part of a hack to omit that class from ADL results. 429 DeclarationName VAListTagName; 430 431 bool MSStructPragmaOn; // True when \#pragma ms_struct on 432 433 /// Controls member pointer representation format under the MS ABI. 434 LangOptions::PragmaMSPointersToMembersKind 435 MSPointerToMemberRepresentationMethod; 436 437 /// Stack of active SEH __finally scopes. Can be empty. 438 SmallVector<Scope*, 2> CurrentSEHFinally; 439 440 /// Source location for newly created implicit MSInheritanceAttrs 441 SourceLocation ImplicitMSInheritanceAttrLoc; 442 443 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by 444 /// `TransformTypos` in order to keep track of any TypoExprs that are created 445 /// recursively during typo correction and wipe them away if the correction 446 /// fails. 447 llvm::SmallVector<TypoExpr *, 2> TypoExprs; 448 449 /// pragma clang section kind 450 enum PragmaClangSectionKind { 451 PCSK_Invalid = 0, 452 PCSK_BSS = 1, 453 PCSK_Data = 2, 454 PCSK_Rodata = 3, 455 PCSK_Text = 4, 456 PCSK_Relro = 5 457 }; 458 459 enum PragmaClangSectionAction { 460 PCSA_Set = 0, 461 PCSA_Clear = 1 462 }; 463 464 struct PragmaClangSection { 465 std::string SectionName; 466 bool Valid = false; 467 SourceLocation PragmaLocation; 468 }; 469 470 PragmaClangSection PragmaClangBSSSection; 471 PragmaClangSection PragmaClangDataSection; 472 PragmaClangSection PragmaClangRodataSection; 473 PragmaClangSection PragmaClangRelroSection; 474 PragmaClangSection PragmaClangTextSection; 475 476 enum PragmaMsStackAction { 477 PSK_Reset = 0x0, // #pragma () 478 PSK_Set = 0x1, // #pragma (value) 479 PSK_Push = 0x2, // #pragma (push[, id]) 480 PSK_Pop = 0x4, // #pragma (pop[, id]) 481 PSK_Show = 0x8, // #pragma (show) -- only for "pack"! 482 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) 483 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) 484 }; 485 486 struct PragmaPackInfo { 487 PragmaMsStackAction Action; 488 StringRef SlotLabel; 489 Token Alignment; 490 }; 491 492 // #pragma pack and align. 493 class AlignPackInfo { 494 public: 495 // `Native` represents default align mode, which may vary based on the 496 // platform. 497 enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; 498 499 // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M,unsigned Num,bool IsXL)500 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) 501 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { 502 assert(Num == PackNumber && "The pack number has been truncated."); 503 } 504 505 // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M,bool IsXL)506 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) 507 : PackAttr(false), AlignMode(M), 508 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} 509 AlignPackInfo(bool IsXL)510 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} 511 AlignPackInfo()512 AlignPackInfo() : AlignPackInfo(Native, false) {} 513 514 // When a AlignPackInfo itself cannot be used, this returns an 32-bit 515 // integer encoding for it. This should only be passed to 516 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. getRawEncoding(const AlignPackInfo & Info)517 static uint32_t getRawEncoding(const AlignPackInfo &Info) { 518 std::uint32_t Encoding{}; 519 if (Info.IsXLStack()) 520 Encoding |= IsXLMask; 521 522 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; 523 524 if (Info.IsPackAttr()) 525 Encoding |= PackAttrMask; 526 527 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; 528 529 return Encoding; 530 } 531 getFromRawEncoding(unsigned Encoding)532 static AlignPackInfo getFromRawEncoding(unsigned Encoding) { 533 bool IsXL = static_cast<bool>(Encoding & IsXLMask); 534 AlignPackInfo::Mode M = 535 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); 536 int PackNumber = (Encoding & PackNumMask) >> 4; 537 538 if (Encoding & PackAttrMask) 539 return AlignPackInfo(M, PackNumber, IsXL); 540 541 return AlignPackInfo(M, IsXL); 542 } 543 IsPackAttr()544 bool IsPackAttr() const { return PackAttr; } 545 IsAlignAttr()546 bool IsAlignAttr() const { return !PackAttr; } 547 getAlignMode()548 Mode getAlignMode() const { return AlignMode; } 549 getPackNumber()550 unsigned getPackNumber() const { return PackNumber; } 551 IsPackSet()552 bool IsPackSet() const { 553 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack 554 // attriute on a decl. 555 return PackNumber != UninitPackVal && PackNumber != 0; 556 } 557 IsXLStack()558 bool IsXLStack() const { return XLStack; } 559 560 bool operator==(const AlignPackInfo &Info) const { 561 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == 562 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, 563 Info.XLStack); 564 } 565 566 bool operator!=(const AlignPackInfo &Info) const { 567 return !(*this == Info); 568 } 569 570 private: 571 /// \brief True if this is a pragma pack attribute, 572 /// not a pragma align attribute. 573 bool PackAttr; 574 575 /// \brief The alignment mode that is in effect. 576 Mode AlignMode; 577 578 /// \brief The pack number of the stack. 579 unsigned char PackNumber; 580 581 /// \brief True if it is a XL #pragma align/pack stack. 582 bool XLStack; 583 584 /// \brief Uninitialized pack value. 585 static constexpr unsigned char UninitPackVal = -1; 586 587 // Masks to encode and decode an AlignPackInfo. 588 static constexpr uint32_t IsXLMask{0x0000'0001}; 589 static constexpr uint32_t AlignModeMask{0x0000'0006}; 590 static constexpr uint32_t PackAttrMask{0x00000'0008}; 591 static constexpr uint32_t PackNumMask{0x0000'01F0}; 592 }; 593 594 template<typename ValueType> 595 struct PragmaStack { 596 struct Slot { 597 llvm::StringRef StackSlotLabel; 598 ValueType Value; 599 SourceLocation PragmaLocation; 600 SourceLocation PragmaPushLocation; SlotPragmaStack::Slot601 Slot(llvm::StringRef StackSlotLabel, ValueType Value, 602 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) 603 : StackSlotLabel(StackSlotLabel), Value(Value), 604 PragmaLocation(PragmaLocation), 605 PragmaPushLocation(PragmaPushLocation) {} 606 }; 607 ActPragmaStack608 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, 609 llvm::StringRef StackSlotLabel, ValueType Value) { 610 if (Action == PSK_Reset) { 611 CurrentValue = DefaultValue; 612 CurrentPragmaLocation = PragmaLocation; 613 return; 614 } 615 if (Action & PSK_Push) 616 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, 617 PragmaLocation); 618 else if (Action & PSK_Pop) { 619 if (!StackSlotLabel.empty()) { 620 // If we've got a label, try to find it and jump there. 621 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { 622 return x.StackSlotLabel == StackSlotLabel; 623 }); 624 // If we found the label so pop from there. 625 if (I != Stack.rend()) { 626 CurrentValue = I->Value; 627 CurrentPragmaLocation = I->PragmaLocation; 628 Stack.erase(std::prev(I.base()), Stack.end()); 629 } 630 } else if (!Stack.empty()) { 631 // We do not have a label, just pop the last entry. 632 CurrentValue = Stack.back().Value; 633 CurrentPragmaLocation = Stack.back().PragmaLocation; 634 Stack.pop_back(); 635 } 636 } 637 if (Action & PSK_Set) { 638 CurrentValue = Value; 639 CurrentPragmaLocation = PragmaLocation; 640 } 641 } 642 643 // MSVC seems to add artificial slots to #pragma stacks on entering a C++ 644 // method body to restore the stacks on exit, so it works like this: 645 // 646 // struct S { 647 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) 648 // void Method {} 649 // #pragma <name>(pop, InternalPragmaSlot) 650 // }; 651 // 652 // It works even with #pragma vtordisp, although MSVC doesn't support 653 // #pragma vtordisp(push [, id], n) 654 // syntax. 655 // 656 // Push / pop a named sentinel slot. SentinelActionPragmaStack657 void SentinelAction(PragmaMsStackAction Action, StringRef Label) { 658 assert((Action == PSK_Push || Action == PSK_Pop) && 659 "Can only push / pop #pragma stack sentinels!"); 660 Act(CurrentPragmaLocation, Action, Label, CurrentValue); 661 } 662 663 // Constructors. PragmaStackPragmaStack664 explicit PragmaStack(const ValueType &Default) 665 : DefaultValue(Default), CurrentValue(Default) {} 666 hasValuePragmaStack667 bool hasValue() const { return CurrentValue != DefaultValue; } 668 669 SmallVector<Slot, 2> Stack; 670 ValueType DefaultValue; // Value used for PSK_Reset action. 671 ValueType CurrentValue; 672 SourceLocation CurrentPragmaLocation; 673 }; 674 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 675 // we shouldn't do so if they're in a module). 676 677 /// Whether to insert vtordisps prior to virtual bases in the Microsoft 678 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 679 /// 680 /// 0: Suppress all vtordisps 681 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 682 /// structors 683 /// 2: Always insert vtordisps to support RTTI on partially constructed 684 /// objects 685 PragmaStack<MSVtorDispMode> VtorDispStack; 686 PragmaStack<AlignPackInfo> AlignPackStack; 687 // The current #pragma align/pack values and locations at each #include. 688 struct AlignPackIncludeState { 689 AlignPackInfo CurrentValue; 690 SourceLocation CurrentPragmaLocation; 691 bool HasNonDefaultValue, ShouldWarnOnInclude; 692 }; 693 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; 694 // Segment #pragmas. 695 PragmaStack<StringLiteral *> DataSegStack; 696 PragmaStack<StringLiteral *> BSSSegStack; 697 PragmaStack<StringLiteral *> ConstSegStack; 698 PragmaStack<StringLiteral *> CodeSegStack; 699 700 // #pragma strict_gs_check. 701 PragmaStack<bool> StrictGuardStackCheckStack; 702 703 // This stack tracks the current state of Sema.CurFPFeatures. 704 PragmaStack<FPOptionsOverride> FpPragmaStack; CurFPFeatureOverrides()705 FPOptionsOverride CurFPFeatureOverrides() { 706 FPOptionsOverride result; 707 if (!FpPragmaStack.hasValue()) { 708 result = FPOptionsOverride(); 709 } else { 710 result = FpPragmaStack.CurrentValue; 711 } 712 return result; 713 } 714 715 // Saves the current floating-point pragma stack and clear it in this Sema. 716 class FpPragmaStackSaveRAII { 717 public: FpPragmaStackSaveRAII(Sema & S)718 FpPragmaStackSaveRAII(Sema &S) 719 : S(S), SavedStack(std::move(S.FpPragmaStack)) { 720 S.FpPragmaStack.Stack.clear(); 721 } ~FpPragmaStackSaveRAII()722 ~FpPragmaStackSaveRAII() { S.FpPragmaStack = std::move(SavedStack); } 723 724 private: 725 Sema &S; 726 PragmaStack<FPOptionsOverride> SavedStack; 727 }; 728 resetFPOptions(FPOptions FPO)729 void resetFPOptions(FPOptions FPO) { 730 CurFPFeatures = FPO; 731 FpPragmaStack.CurrentValue = FPO.getChangesFrom(FPOptions(LangOpts)); 732 } 733 734 // RAII object to push / pop sentinel slots for all MS #pragma stacks. 735 // Actions should be performed only if we enter / exit a C++ method body. 736 class PragmaStackSentinelRAII { 737 public: 738 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); 739 ~PragmaStackSentinelRAII(); 740 741 private: 742 Sema &S; 743 StringRef SlotLabel; 744 bool ShouldAct; 745 }; 746 747 /// A mapping that describes the nullability we've seen in each header file. 748 FileNullabilityMap NullabilityMap; 749 750 /// Last section used with #pragma init_seg. 751 StringLiteral *CurInitSeg; 752 SourceLocation CurInitSegLoc; 753 754 /// Sections used with #pragma alloc_text. 755 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap; 756 757 /// VisContext - Manages the stack for \#pragma GCC visibility. 758 void *VisContext; // Really a "PragmaVisStack*" 759 760 /// This an attribute introduced by \#pragma clang attribute. 761 struct PragmaAttributeEntry { 762 SourceLocation Loc; 763 ParsedAttr *Attribute; 764 SmallVector<attr::SubjectMatchRule, 4> MatchRules; 765 bool IsUsed; 766 }; 767 768 /// A push'd group of PragmaAttributeEntries. 769 struct PragmaAttributeGroup { 770 /// The location of the push attribute. 771 SourceLocation Loc; 772 /// The namespace of this push group. 773 const IdentifierInfo *Namespace; 774 SmallVector<PragmaAttributeEntry, 2> Entries; 775 }; 776 777 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; 778 779 /// The declaration that is currently receiving an attribute from the 780 /// #pragma attribute stack. 781 const Decl *PragmaAttributeCurrentTargetDecl; 782 783 /// This represents the last location of a "#pragma clang optimize off" 784 /// directive if such a directive has not been closed by an "on" yet. If 785 /// optimizations are currently "on", this is set to an invalid location. 786 SourceLocation OptimizeOffPragmaLocation; 787 788 /// The "on" or "off" argument passed by \#pragma optimize, that denotes 789 /// whether the optimizations in the list passed to the pragma should be 790 /// turned off or on. This boolean is true by default because command line 791 /// options are honored when `#pragma optimize("", on)`. 792 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing) 793 bool MSPragmaOptimizeIsOn = true; 794 795 /// Set of no-builtin functions listed by \#pragma function. 796 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins; 797 798 /// Flag indicating if Sema is building a recovery call expression. 799 /// 800 /// This flag is used to avoid building recovery call expressions 801 /// if Sema is already doing so, which would cause infinite recursions. 802 bool IsBuildingRecoveryCallExpr; 803 804 /// Used to control the generation of ExprWithCleanups. 805 CleanupInfo Cleanup; 806 807 /// ExprCleanupObjects - This is the stack of objects requiring 808 /// cleanup that are created by the current full expression. 809 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; 810 811 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference 812 /// to a variable (constant) that may or may not be odr-used in this Expr, and 813 /// we won't know until all lvalue-to-rvalue and discarded value conversions 814 /// have been applied to all subexpressions of the enclosing full expression. 815 /// This is cleared at the end of each full expression. 816 using MaybeODRUseExprSet = llvm::SmallSetVector<Expr *, 4>; 817 MaybeODRUseExprSet MaybeODRUseExprs; 818 819 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; 820 821 /// Stack containing information about each of the nested 822 /// function, block, and method scopes that are currently active. 823 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 824 825 /// The index of the first FunctionScope that corresponds to the current 826 /// context. 827 unsigned FunctionScopesStart = 0; 828 829 /// Track the number of currently active capturing scopes. 830 unsigned CapturingFunctionScopes = 0; 831 getFunctionScopes()832 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { 833 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart, 834 FunctionScopes.end()); 835 } 836 837 /// Stack containing information needed when in C++2a an 'auto' is encountered 838 /// in a function declaration parameter type specifier in order to invent a 839 /// corresponding template parameter in the enclosing abbreviated function 840 /// template. This information is also present in LambdaScopeInfo, stored in 841 /// the FunctionScopes stack. 842 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; 843 844 /// The index of the first InventedParameterInfo that refers to the current 845 /// context. 846 unsigned InventedParameterInfosStart = 0; 847 getInventedParameterInfos()848 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { 849 return llvm::ArrayRef(InventedParameterInfos.begin() + 850 InventedParameterInfosStart, 851 InventedParameterInfos.end()); 852 } 853 854 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 855 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 856 ExtVectorDeclsType; 857 858 /// ExtVectorDecls - This is a list all the extended vector types. This allows 859 /// us to associate a raw vector type with one of the ext_vector type names. 860 /// This is only necessary for issuing pretty diagnostics. 861 ExtVectorDeclsType ExtVectorDecls; 862 863 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 864 std::unique_ptr<CXXFieldCollector> FieldCollector; 865 866 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType; 867 868 /// Set containing all declared private fields that are not used. 869 NamedDeclSetType UnusedPrivateFields; 870 871 /// Set containing all typedefs that are likely unused. 872 llvm::SmallSetVector<const TypedefNameDecl *, 4> 873 UnusedLocalTypedefNameCandidates; 874 875 /// Delete-expressions to be analyzed at the end of translation unit 876 /// 877 /// This list contains class members, and locations of delete-expressions 878 /// that could not be proven as to whether they mismatch with new-expression 879 /// used in initializer of the field. 880 typedef std::pair<SourceLocation, bool> DeleteExprLoc; 881 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; 882 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; 883 884 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 885 886 /// PureVirtualClassDiagSet - a set of class declarations which we have 887 /// emitted a list of pure virtual functions. Used to prevent emitting the 888 /// same list more than once. 889 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 890 891 /// ParsingInitForAutoVars - a set of declarations with auto types for which 892 /// we are currently parsing the initializer. 893 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 894 895 /// Look for a locally scoped extern "C" declaration by the given name. 896 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 897 898 typedef LazyVector<VarDecl *, ExternalSemaSource, 899 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 900 TentativeDefinitionsType; 901 902 /// All the tentative definitions encountered in the TU. 903 TentativeDefinitionsType TentativeDefinitions; 904 905 /// All the external declarations encoutered and used in the TU. 906 SmallVector<VarDecl *, 4> ExternalDeclarations; 907 908 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 909 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 910 UnusedFileScopedDeclsType; 911 912 /// The set of file scoped decls seen so far that have not been used 913 /// and must warn if not used. Only contains the first declaration. 914 UnusedFileScopedDeclsType UnusedFileScopedDecls; 915 916 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 917 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 918 DelegatingCtorDeclsType; 919 920 /// All the delegating constructors seen so far in the file, used for 921 /// cycle detection at the end of the TU. 922 DelegatingCtorDeclsType DelegatingCtorDecls; 923 924 /// All the overriding functions seen during a class definition 925 /// that had their exception spec checks delayed, plus the overridden 926 /// function. 927 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> 928 DelayedOverridingExceptionSpecChecks; 929 930 /// All the function redeclarations seen during a class definition that had 931 /// their exception spec checks delayed, plus the prior declaration they 932 /// should be checked against. Except during error recovery, the new decl 933 /// should always be a friend declaration, as that's the only valid way to 934 /// redeclare a special member before its class is complete. 935 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> 936 DelayedEquivalentExceptionSpecChecks; 937 938 typedef llvm::MapVector<const FunctionDecl *, 939 std::unique_ptr<LateParsedTemplate>> 940 LateParsedTemplateMapT; 941 LateParsedTemplateMapT LateParsedTemplateMap; 942 943 /// Callback to the parser to parse templated functions when needed. 944 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 945 typedef void LateTemplateParserCleanupCB(void *P); 946 LateTemplateParserCB *LateTemplateParser; 947 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 948 void *OpaqueParser; 949 SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)950 void SetLateTemplateParser(LateTemplateParserCB *LTP, 951 LateTemplateParserCleanupCB *LTPCleanup, 952 void *P) { 953 LateTemplateParser = LTP; 954 LateTemplateParserCleanup = LTPCleanup; 955 OpaqueParser = P; 956 } 957 958 /// Callback to the parser to parse a type expressed as a string. 959 std::function<TypeResult(StringRef, StringRef, SourceLocation)> 960 ParseTypeFromStringCallback; 961 962 class DelayedDiagnostics; 963 964 class DelayedDiagnosticsState { 965 sema::DelayedDiagnosticPool *SavedPool = nullptr; 966 friend class Sema::DelayedDiagnostics; 967 }; 968 typedef DelayedDiagnosticsState ParsingDeclState; 969 typedef DelayedDiagnosticsState ProcessingContextState; 970 971 /// A class which encapsulates the logic for delaying diagnostics 972 /// during parsing and other processing. 973 class DelayedDiagnostics { 974 /// The current pool of diagnostics into which delayed 975 /// diagnostics should go. 976 sema::DelayedDiagnosticPool *CurPool = nullptr; 977 978 public: 979 DelayedDiagnostics() = default; 980 981 /// Adds a delayed diagnostic. 982 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 983 984 /// Determines whether diagnostics should be delayed. shouldDelayDiagnostics()985 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 986 987 /// Returns the current delayed-diagnostics pool. getCurrentPool()988 sema::DelayedDiagnosticPool *getCurrentPool() const { 989 return CurPool; 990 } 991 992 /// Enter a new scope. Access and deprecation diagnostics will be 993 /// collected in this pool. push(sema::DelayedDiagnosticPool & pool)994 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 995 DelayedDiagnosticsState state; 996 state.SavedPool = CurPool; 997 CurPool = &pool; 998 return state; 999 } 1000 1001 /// Leave a delayed-diagnostic state that was previously pushed. 1002 /// Do not emit any of the diagnostics. This is performed as part 1003 /// of the bookkeeping of popping a pool "properly". popWithoutEmitting(DelayedDiagnosticsState state)1004 void popWithoutEmitting(DelayedDiagnosticsState state) { 1005 CurPool = state.SavedPool; 1006 } 1007 1008 /// Enter a new scope where access and deprecation diagnostics are 1009 /// not delayed. pushUndelayed()1010 DelayedDiagnosticsState pushUndelayed() { 1011 DelayedDiagnosticsState state; 1012 state.SavedPool = CurPool; 1013 CurPool = nullptr; 1014 return state; 1015 } 1016 1017 /// Undo a previous pushUndelayed(). popUndelayed(DelayedDiagnosticsState state)1018 void popUndelayed(DelayedDiagnosticsState state) { 1019 assert(CurPool == nullptr); 1020 CurPool = state.SavedPool; 1021 } 1022 } DelayedDiagnostics; 1023 1024 enum CUDAFunctionTarget { 1025 CFT_Device, 1026 CFT_Global, 1027 CFT_Host, 1028 CFT_HostDevice, 1029 CFT_InvalidTarget 1030 }; 1031 1032 /// A RAII object to temporarily push a declaration context. 1033 class ContextRAII { 1034 private: 1035 Sema &S; 1036 DeclContext *SavedContext; 1037 ProcessingContextState SavedContextState; 1038 QualType SavedCXXThisTypeOverride; 1039 unsigned SavedFunctionScopesStart; 1040 unsigned SavedInventedParameterInfosStart; 1041 1042 public: 1043 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) S(S)1044 : S(S), SavedContext(S.CurContext), 1045 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 1046 SavedCXXThisTypeOverride(S.CXXThisTypeOverride), 1047 SavedFunctionScopesStart(S.FunctionScopesStart), 1048 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) 1049 { 1050 assert(ContextToPush && "pushing null context"); 1051 S.CurContext = ContextToPush; 1052 if (NewThisContext) 1053 S.CXXThisTypeOverride = QualType(); 1054 // Any saved FunctionScopes do not refer to this context. 1055 S.FunctionScopesStart = S.FunctionScopes.size(); 1056 S.InventedParameterInfosStart = S.InventedParameterInfos.size(); 1057 } 1058 pop()1059 void pop() { 1060 if (!SavedContext) return; 1061 S.CurContext = SavedContext; 1062 S.DelayedDiagnostics.popUndelayed(SavedContextState); 1063 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 1064 S.FunctionScopesStart = SavedFunctionScopesStart; 1065 S.InventedParameterInfosStart = SavedInventedParameterInfosStart; 1066 SavedContext = nullptr; 1067 } 1068 ~ContextRAII()1069 ~ContextRAII() { 1070 pop(); 1071 } 1072 }; 1073 1074 /// RAII object to handle the state changes required to synthesize 1075 /// a function body. 1076 class SynthesizedFunctionScope { 1077 Sema &S; 1078 Sema::ContextRAII SavedContext; 1079 bool PushedCodeSynthesisContext = false; 1080 1081 public: SynthesizedFunctionScope(Sema & S,DeclContext * DC)1082 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 1083 : S(S), SavedContext(S, DC) { 1084 auto *FD = dyn_cast<FunctionDecl>(DC); 1085 S.PushFunctionScope(); 1086 S.PushExpressionEvaluationContext( 1087 (FD && FD->isConsteval()) 1088 ? ExpressionEvaluationContext::ImmediateFunctionContext 1089 : ExpressionEvaluationContext::PotentiallyEvaluated); 1090 if (FD) { 1091 FD->setWillHaveBody(true); 1092 S.ExprEvalContexts.back().InImmediateFunctionContext = 1093 FD->isImmediateFunction() || 1094 S.ExprEvalContexts[S.ExprEvalContexts.size() - 2] 1095 .isConstantEvaluated(); 1096 S.ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 1097 S.getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); 1098 } else 1099 assert(isa<ObjCMethodDecl>(DC)); 1100 } 1101 addContextNote(SourceLocation UseLoc)1102 void addContextNote(SourceLocation UseLoc) { 1103 assert(!PushedCodeSynthesisContext); 1104 1105 Sema::CodeSynthesisContext Ctx; 1106 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; 1107 Ctx.PointOfInstantiation = UseLoc; 1108 Ctx.Entity = cast<Decl>(S.CurContext); 1109 S.pushCodeSynthesisContext(Ctx); 1110 1111 PushedCodeSynthesisContext = true; 1112 } 1113 ~SynthesizedFunctionScope()1114 ~SynthesizedFunctionScope() { 1115 if (PushedCodeSynthesisContext) 1116 S.popCodeSynthesisContext(); 1117 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) { 1118 FD->setWillHaveBody(false); 1119 S.CheckImmediateEscalatingFunctionDefinition(FD, S.getCurFunction()); 1120 } 1121 S.PopExpressionEvaluationContext(); 1122 S.PopFunctionScopeInfo(); 1123 } 1124 }; 1125 1126 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before 1127 /// declared. Rare. May alias another identifier, declared or undeclared. 1128 /// 1129 /// For aliases, the target identifier is used as a key for eventual 1130 /// processing when the target is declared. For the single-identifier form, 1131 /// the sole identifier is used as the key. Each entry is a `SetVector` 1132 /// (ordered by parse order) of aliases (identified by the alias name) in case 1133 /// of multiple aliases to the same undeclared identifier. 1134 llvm::MapVector< 1135 IdentifierInfo *, 1136 llvm::SetVector< 1137 WeakInfo, llvm::SmallVector<WeakInfo, 1u>, 1138 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>> 1139 WeakUndeclaredIdentifiers; 1140 1141 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 1142 /// \#pragma redefine_extname before declared. Used in Solaris system headers 1143 /// to define functions that occur in multiple standards to call the version 1144 /// in the currently selected standard. 1145 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 1146 1147 1148 /// Load weak undeclared identifiers from the external source. 1149 void LoadExternalWeakUndeclaredIdentifiers(); 1150 1151 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 1152 /// \#pragma weak during processing of other Decls. 1153 /// I couldn't figure out a clean way to generate these in-line, so 1154 /// we store them here and handle separately -- which is a hack. 1155 /// It would be best to refactor this. 1156 SmallVector<Decl*,2> WeakTopLevelDecl; 1157 1158 IdentifierResolver IdResolver; 1159 1160 /// Translation Unit Scope - useful to Objective-C actions that need 1161 /// to lookup file scope declarations in the "ordinary" C decl namespace. 1162 /// For example, user-defined classes, built-in "id" type, etc. 1163 Scope *TUScope; 1164 1165 /// The C++ "std" namespace, where the standard library resides. 1166 LazyDeclPtr StdNamespace; 1167 1168 /// The C++ "std::bad_alloc" class, which is defined by the C++ 1169 /// standard library. 1170 LazyDeclPtr StdBadAlloc; 1171 1172 /// The C++ "std::align_val_t" enum class, which is defined by the C++ 1173 /// standard library. 1174 LazyDeclPtr StdAlignValT; 1175 1176 /// The C++ "std::initializer_list" template, which is defined in 1177 /// \<initializer_list>. 1178 ClassTemplateDecl *StdInitializerList; 1179 1180 /// The C++ "std::coroutine_traits" template, which is defined in 1181 /// \<coroutine_traits> 1182 ClassTemplateDecl *StdCoroutineTraitsCache; 1183 1184 /// The C++ "type_info" declaration, which is defined in \<typeinfo>. 1185 RecordDecl *CXXTypeInfoDecl; 1186 1187 /// The C++ "std::source_location::__impl" struct, defined in 1188 /// \<source_location>. 1189 RecordDecl *StdSourceLocationImplDecl; 1190 1191 /// Caches identifiers/selectors for NSFoundation APIs. 1192 std::unique_ptr<NSAPI> NSAPIObj; 1193 1194 /// The declaration of the Objective-C NSNumber class. 1195 ObjCInterfaceDecl *NSNumberDecl; 1196 1197 /// The declaration of the Objective-C NSValue class. 1198 ObjCInterfaceDecl *NSValueDecl; 1199 1200 /// Pointer to NSNumber type (NSNumber *). 1201 QualType NSNumberPointer; 1202 1203 /// Pointer to NSValue type (NSValue *). 1204 QualType NSValuePointer; 1205 1206 /// The Objective-C NSNumber methods used to create NSNumber literals. 1207 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 1208 1209 /// The declaration of the Objective-C NSString class. 1210 ObjCInterfaceDecl *NSStringDecl; 1211 1212 /// Pointer to NSString type (NSString *). 1213 QualType NSStringPointer; 1214 1215 /// The declaration of the stringWithUTF8String: method. 1216 ObjCMethodDecl *StringWithUTF8StringMethod; 1217 1218 /// The declaration of the valueWithBytes:objCType: method. 1219 ObjCMethodDecl *ValueWithBytesObjCTypeMethod; 1220 1221 /// The declaration of the Objective-C NSArray class. 1222 ObjCInterfaceDecl *NSArrayDecl; 1223 1224 /// The declaration of the arrayWithObjects:count: method. 1225 ObjCMethodDecl *ArrayWithObjectsMethod; 1226 1227 /// The declaration of the Objective-C NSDictionary class. 1228 ObjCInterfaceDecl *NSDictionaryDecl; 1229 1230 /// The declaration of the dictionaryWithObjects:forKeys:count: method. 1231 ObjCMethodDecl *DictionaryWithObjectsMethod; 1232 1233 /// id<NSCopying> type. 1234 QualType QIDNSCopying; 1235 1236 /// will hold 'respondsToSelector:' 1237 Selector RespondsToSelectorSel; 1238 1239 /// A flag to remember whether the implicit forms of operator new and delete 1240 /// have been declared. 1241 bool GlobalNewDeleteDeclared; 1242 1243 /// Describes how the expressions currently being parsed are 1244 /// evaluated at run-time, if at all. 1245 enum class ExpressionEvaluationContext { 1246 /// The current expression and its subexpressions occur within an 1247 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 1248 /// \c sizeof, where the type of the expression may be significant but 1249 /// no code will be generated to evaluate the value of the expression at 1250 /// run time. 1251 Unevaluated, 1252 1253 /// The current expression occurs within a braced-init-list within 1254 /// an unevaluated operand. This is mostly like a regular unevaluated 1255 /// context, except that we still instantiate constexpr functions that are 1256 /// referenced here so that we can perform narrowing checks correctly. 1257 UnevaluatedList, 1258 1259 /// The current expression occurs within a discarded statement. 1260 /// This behaves largely similarly to an unevaluated operand in preventing 1261 /// definitions from being required, but not in other ways. 1262 DiscardedStatement, 1263 1264 /// The current expression occurs within an unevaluated 1265 /// operand that unconditionally permits abstract references to 1266 /// fields, such as a SIZE operator in MS-style inline assembly. 1267 UnevaluatedAbstract, 1268 1269 /// The current context is "potentially evaluated" in C++11 terms, 1270 /// but the expression is evaluated at compile-time (like the values of 1271 /// cases in a switch statement). 1272 ConstantEvaluated, 1273 1274 /// In addition of being constant evaluated, the current expression 1275 /// occurs in an immediate function context - either a consteval function 1276 /// or a consteval if statement. 1277 ImmediateFunctionContext, 1278 1279 /// The current expression is potentially evaluated at run time, 1280 /// which means that code may be generated to evaluate the value of the 1281 /// expression at run time. 1282 PotentiallyEvaluated, 1283 1284 /// The current expression is potentially evaluated, but any 1285 /// declarations referenced inside that expression are only used if 1286 /// in fact the current expression is used. 1287 /// 1288 /// This value is used when parsing default function arguments, for which 1289 /// we would like to provide diagnostics (e.g., passing non-POD arguments 1290 /// through varargs) but do not want to mark declarations as "referenced" 1291 /// until the default argument is used. 1292 PotentiallyEvaluatedIfUsed 1293 }; 1294 1295 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; 1296 1297 /// Data structure used to record current or nested 1298 /// expression evaluation contexts. 1299 struct ExpressionEvaluationContextRecord { 1300 /// The expression evaluation context. 1301 ExpressionEvaluationContext Context; 1302 1303 /// Whether the enclosing context needed a cleanup. 1304 CleanupInfo ParentCleanup; 1305 1306 /// The number of active cleanup objects when we entered 1307 /// this expression evaluation context. 1308 unsigned NumCleanupObjects; 1309 1310 /// The number of typos encountered during this expression evaluation 1311 /// context (i.e. the number of TypoExprs created). 1312 unsigned NumTypos; 1313 1314 MaybeODRUseExprSet SavedMaybeODRUseExprs; 1315 1316 /// The lambdas that are present within this context, if it 1317 /// is indeed an unevaluated context. 1318 SmallVector<LambdaExpr *, 2> Lambdas; 1319 1320 /// The declaration that provides context for lambda expressions 1321 /// and block literals if the normal declaration context does not 1322 /// suffice, e.g., in a default function argument. 1323 Decl *ManglingContextDecl; 1324 1325 /// If we are processing a decltype type, a set of call expressions 1326 /// for which we have deferred checking the completeness of the return type. 1327 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 1328 1329 /// If we are processing a decltype type, a set of temporary binding 1330 /// expressions for which we have deferred checking the destructor. 1331 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 1332 1333 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; 1334 1335 /// Expressions appearing as the LHS of a volatile assignment in this 1336 /// context. We produce a warning for these when popping the context if 1337 /// they are not discarded-value expressions nor unevaluated operands. 1338 SmallVector<Expr*, 2> VolatileAssignmentLHSs; 1339 1340 /// Set of candidates for starting an immediate invocation. 1341 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; 1342 1343 /// Set of DeclRefExprs referencing a consteval function when used in a 1344 /// context not already known to be immediately invoked. 1345 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; 1346 1347 /// \brief Describes whether we are in an expression constext which we have 1348 /// to handle differently. 1349 enum ExpressionKind { 1350 EK_Decltype, EK_TemplateArgument, EK_Other 1351 } ExprContext; 1352 1353 // A context can be nested in both a discarded statement context and 1354 // an immediate function context, so they need to be tracked independently. 1355 bool InDiscardedStatement; 1356 bool InImmediateFunctionContext; 1357 bool InImmediateEscalatingFunctionContext; 1358 1359 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false; 1360 1361 // We are in a constant context, but we also allow 1362 // non constant expressions, for example for array bounds (which may be 1363 // VLAs). 1364 bool InConditionallyConstantEvaluateContext = false; 1365 1366 // When evaluating immediate functions in the initializer of a default 1367 // argument or default member initializer, this is the declaration whose 1368 // default initializer is being evaluated and the location of the call 1369 // or constructor definition. 1370 struct InitializationContext { InitializationContextExpressionEvaluationContextRecord::InitializationContext1371 InitializationContext(SourceLocation Loc, ValueDecl *Decl, 1372 DeclContext *Context) 1373 : Loc(Loc), Decl(Decl), Context(Context) { 1374 assert(Decl && Context && "invalid initialization context"); 1375 } 1376 1377 SourceLocation Loc; 1378 ValueDecl *Decl = nullptr; 1379 DeclContext *Context = nullptr; 1380 }; 1381 std::optional<InitializationContext> DelayedDefaultInitializationContext; 1382 ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1383 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 1384 unsigned NumCleanupObjects, 1385 CleanupInfo ParentCleanup, 1386 Decl *ManglingContextDecl, 1387 ExpressionKind ExprContext) 1388 : Context(Context), ParentCleanup(ParentCleanup), 1389 NumCleanupObjects(NumCleanupObjects), NumTypos(0), 1390 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext), 1391 InDiscardedStatement(false), InImmediateFunctionContext(false), 1392 InImmediateEscalatingFunctionContext(false) {} 1393 isUnevaluatedExpressionEvaluationContextRecord1394 bool isUnevaluated() const { 1395 return Context == ExpressionEvaluationContext::Unevaluated || 1396 Context == ExpressionEvaluationContext::UnevaluatedAbstract || 1397 Context == ExpressionEvaluationContext::UnevaluatedList; 1398 } 1399 isConstantEvaluatedExpressionEvaluationContextRecord1400 bool isConstantEvaluated() const { 1401 return Context == ExpressionEvaluationContext::ConstantEvaluated || 1402 Context == ExpressionEvaluationContext::ImmediateFunctionContext; 1403 } 1404 isImmediateFunctionContextExpressionEvaluationContextRecord1405 bool isImmediateFunctionContext() const { 1406 return Context == ExpressionEvaluationContext::ImmediateFunctionContext || 1407 (Context == ExpressionEvaluationContext::DiscardedStatement && 1408 InImmediateFunctionContext) || 1409 // C++23 [expr.const]p14: 1410 // An expression or conversion is in an immediate function 1411 // context if it is potentially evaluated and either: 1412 // * its innermost enclosing non-block scope is a function 1413 // parameter scope of an immediate function, or 1414 // * its enclosing statement is enclosed by the compound- 1415 // statement of a consteval if statement. 1416 (Context == ExpressionEvaluationContext::PotentiallyEvaluated && 1417 InImmediateFunctionContext); 1418 } 1419 isDiscardedStatementContextExpressionEvaluationContextRecord1420 bool isDiscardedStatementContext() const { 1421 return Context == ExpressionEvaluationContext::DiscardedStatement || 1422 (Context == 1423 ExpressionEvaluationContext::ImmediateFunctionContext && 1424 InDiscardedStatement); 1425 } 1426 }; 1427 1428 /// A stack of expression evaluation contexts. 1429 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 1430 1431 // Set of failed immediate invocations to avoid double diagnosing. 1432 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations; 1433 1434 /// Emit a warning for all pending noderef expressions that we recorded. 1435 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); 1436 1437 /// Compute the mangling number context for a lambda expression or 1438 /// block literal. Also return the extra mangling decl if any. 1439 /// 1440 /// \param DC - The DeclContext containing the lambda expression or 1441 /// block literal. 1442 std::tuple<MangleNumberingContext *, Decl *> 1443 getCurrentMangleNumberContext(const DeclContext *DC); 1444 1445 1446 /// SpecialMemberOverloadResult - The overloading result for a special member 1447 /// function. 1448 /// 1449 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 1450 /// integer are used to determine whether overload resolution succeeded. 1451 class SpecialMemberOverloadResult { 1452 public: 1453 enum Kind { 1454 NoMemberOrDeleted, 1455 Ambiguous, 1456 Success 1457 }; 1458 1459 private: 1460 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair; 1461 1462 public: SpecialMemberOverloadResult()1463 SpecialMemberOverloadResult() {} SpecialMemberOverloadResult(CXXMethodDecl * MD)1464 SpecialMemberOverloadResult(CXXMethodDecl *MD) 1465 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} 1466 getMethod()1467 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } setMethod(CXXMethodDecl * MD)1468 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 1469 getKind()1470 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } setKind(Kind K)1471 void setKind(Kind K) { Pair.setInt(K); } 1472 }; 1473 1474 class SpecialMemberOverloadResultEntry 1475 : public llvm::FastFoldingSetNode, 1476 public SpecialMemberOverloadResult { 1477 public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1478 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) 1479 : FastFoldingSetNode(ID) 1480 {} 1481 }; 1482 1483 /// A cache of special member function overload resolution results 1484 /// for C++ records. 1485 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; 1486 1487 /// A cache of the flags available in enumerations with the flag_bits 1488 /// attribute. 1489 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; 1490 1491 /// The kind of translation unit we are processing. 1492 /// 1493 /// When we're processing a complete translation unit, Sema will perform 1494 /// end-of-translation-unit semantic tasks (such as creating 1495 /// initializers for tentative definitions in C) once parsing has 1496 /// completed. Modules and precompiled headers perform different kinds of 1497 /// checks. 1498 const TranslationUnitKind TUKind; 1499 1500 llvm::BumpPtrAllocator BumpAlloc; 1501 1502 /// The number of SFINAE diagnostics that have been trapped. 1503 unsigned NumSFINAEErrors; 1504 1505 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 1506 UnparsedDefaultArgInstantiationsMap; 1507 1508 /// A mapping from parameters with unparsed default arguments to the 1509 /// set of instantiations of each parameter. 1510 /// 1511 /// This mapping is a temporary data structure used when parsing 1512 /// nested class templates or nested classes of class templates, 1513 /// where we might end up instantiating an inner class before the 1514 /// default arguments of its methods have been parsed. 1515 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 1516 1517 // Contains the locations of the beginning of unparsed default 1518 // argument locations. 1519 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 1520 1521 /// UndefinedInternals - all the used, undefined objects which require a 1522 /// definition in this translation unit. 1523 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; 1524 1525 /// Determine if VD, which must be a variable or function, is an external 1526 /// symbol that nonetheless can't be referenced from outside this translation 1527 /// unit because its type has no linkage and it's not extern "C". 1528 bool isExternalWithNoLinkageType(const ValueDecl *VD) const; 1529 1530 /// Obtain a sorted list of functions that are undefined but ODR-used. 1531 void getUndefinedButUsed( 1532 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 1533 1534 /// Retrieves list of suspicious delete-expressions that will be checked at 1535 /// the end of translation unit. 1536 const llvm::MapVector<FieldDecl *, DeleteLocs> & 1537 getMismatchingDeleteExpressions() const; 1538 1539 class GlobalMethodPool { 1540 public: 1541 using Lists = std::pair<ObjCMethodList, ObjCMethodList>; 1542 using iterator = llvm::DenseMap<Selector, Lists>::iterator; begin()1543 iterator begin() { return Methods.begin(); } end()1544 iterator end() { return Methods.end(); } find(Selector Sel)1545 iterator find(Selector Sel) { return Methods.find(Sel); } insert(std::pair<Selector,Lists> && Val)1546 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) { 1547 return Methods.insert(Val); 1548 } count(Selector Sel)1549 int count(Selector Sel) const { return Methods.count(Sel); } empty()1550 bool empty() const { return Methods.empty(); } 1551 1552 private: 1553 llvm::DenseMap<Selector, Lists> Methods; 1554 }; 1555 1556 /// Method Pool - allows efficient lookup when typechecking messages to "id". 1557 /// We need to maintain a list, since selectors can have differing signatures 1558 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 1559 /// of selectors are "overloaded"). 1560 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 1561 /// methods inside categories with a particular selector. 1562 GlobalMethodPool MethodPool; 1563 1564 /// Method selectors used in a \@selector expression. Used for implementation 1565 /// of -Wselector. 1566 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; 1567 1568 /// List of SourceLocations where 'self' is implicitly retained inside a 1569 /// block. 1570 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> 1571 ImplicitlyRetainedSelfLocs; 1572 1573 /// Kinds of C++ special members. 1574 enum CXXSpecialMember { 1575 CXXDefaultConstructor, 1576 CXXCopyConstructor, 1577 CXXMoveConstructor, 1578 CXXCopyAssignment, 1579 CXXMoveAssignment, 1580 CXXDestructor, 1581 CXXInvalid 1582 }; 1583 1584 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> 1585 SpecialMemberDecl; 1586 1587 /// The C++ special members which we are currently in the process of 1588 /// declaring. If this process recursively triggers the declaration of the 1589 /// same special member, we should act as if it is not yet declared. 1590 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 1591 1592 /// Kinds of defaulted comparison operator functions. 1593 enum class DefaultedComparisonKind : unsigned char { 1594 /// This is not a defaultable comparison operator. 1595 None, 1596 /// This is an operator== that should be implemented as a series of 1597 /// subobject comparisons. 1598 Equal, 1599 /// This is an operator<=> that should be implemented as a series of 1600 /// subobject comparisons. 1601 ThreeWay, 1602 /// This is an operator!= that should be implemented as a rewrite in terms 1603 /// of a == comparison. 1604 NotEqual, 1605 /// This is an <, <=, >, or >= that should be implemented as a rewrite in 1606 /// terms of a <=> comparison. 1607 Relational, 1608 }; 1609 1610 /// The function definitions which were renamed as part of typo-correction 1611 /// to match their respective declarations. We want to keep track of them 1612 /// to ensure that we don't emit a "redefinition" error if we encounter a 1613 /// correctly named definition after the renamed definition. 1614 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; 1615 1616 /// Stack of types that correspond to the parameter entities that are 1617 /// currently being copy-initialized. Can be empty. 1618 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; 1619 1620 void ReadMethodPool(Selector Sel); 1621 void updateOutOfDateSelector(Selector Sel); 1622 1623 /// Private Helper predicate to check for 'self'. 1624 bool isSelfExpr(Expr *RExpr); 1625 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); 1626 1627 /// Cause the active diagnostic on the DiagosticsEngine to be 1628 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 1629 /// should not be used elsewhere. 1630 void EmitCurrentDiagnostic(unsigned DiagID); 1631 1632 /// Records and restores the CurFPFeatures state on entry/exit of compound 1633 /// statements. 1634 class FPFeaturesStateRAII { 1635 public: 1636 FPFeaturesStateRAII(Sema &S); 1637 ~FPFeaturesStateRAII(); getOverrides()1638 FPOptionsOverride getOverrides() { return OldOverrides; } 1639 1640 private: 1641 Sema& S; 1642 FPOptions OldFPFeaturesState; 1643 FPOptionsOverride OldOverrides; 1644 LangOptions::FPEvalMethodKind OldEvalMethod; 1645 SourceLocation OldFPPragmaLocation; 1646 }; 1647 1648 void addImplicitTypedef(StringRef Name, QualType T); 1649 1650 bool WarnedStackExhausted = false; 1651 1652 /// Increment when we find a reference; decrement when we find an ignored 1653 /// assignment. Ultimately the value is 0 if every reference is an ignored 1654 /// assignment. 1655 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; 1656 1657 /// Indicate RISC-V vector builtin functions enabled or not. 1658 bool DeclareRISCVVBuiltins = false; 1659 1660 /// Indicate RISC-V SiFive vector builtin functions enabled or not. 1661 bool DeclareRISCVSiFiveVectorBuiltins = false; 1662 1663 private: 1664 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager; 1665 1666 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; 1667 1668 bool WarnedDarwinSDKInfoMissing = false; 1669 1670 public: 1671 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 1672 TranslationUnitKind TUKind = TU_Complete, 1673 CodeCompleteConsumer *CompletionConsumer = nullptr); 1674 ~Sema(); 1675 1676 /// Perform initialization that occurs after the parser has been 1677 /// initialized but before it parses anything. 1678 void Initialize(); 1679 1680 /// This virtual key function only exists to limit the emission of debug info 1681 /// describing the Sema class. GCC and Clang only emit debug info for a class 1682 /// with a vtable when the vtable is emitted. Sema is final and not 1683 /// polymorphic, but the debug info size savings are so significant that it is 1684 /// worth adding a vtable just to take advantage of this optimization. 1685 virtual void anchor(); 1686 getLangOpts()1687 const LangOptions &getLangOpts() const { return LangOpts; } getOpenCLOptions()1688 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } getCurFPFeatures()1689 FPOptions &getCurFPFeatures() { return CurFPFeatures; } 1690 getDiagnostics()1691 DiagnosticsEngine &getDiagnostics() const { return Diags; } getSourceManager()1692 SourceManager &getSourceManager() const { return SourceMgr; } getPreprocessor()1693 Preprocessor &getPreprocessor() const { return PP; } getASTContext()1694 ASTContext &getASTContext() const { return Context; } getASTConsumer()1695 ASTConsumer &getASTConsumer() const { return Consumer; } 1696 ASTMutationListener *getASTMutationListener() const; getExternalSource()1697 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); } 1698 1699 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, 1700 StringRef Platform); 1701 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(); 1702 1703 ///Registers an external source. If an external source already exists, 1704 /// creates a multiplex external source and appends to it. 1705 /// 1706 ///\param[in] E - A non-null external sema source. 1707 /// 1708 void addExternalSource(ExternalSemaSource *E); 1709 1710 void PrintStats() const; 1711 1712 /// Warn that the stack is nearly exhausted. 1713 void warnStackExhausted(SourceLocation Loc); 1714 1715 /// Run some code with "sufficient" stack space. (Currently, at least 256K is 1716 /// guaranteed). Produces a warning if we're low on stack space and allocates 1717 /// more in that case. Use this in code that may recurse deeply (for example, 1718 /// in template instantiation) to avoid stack overflow. 1719 void runWithSufficientStackSpace(SourceLocation Loc, 1720 llvm::function_ref<void()> Fn); 1721 1722 /// Helper class that creates diagnostics with optional 1723 /// template instantiation stacks. 1724 /// 1725 /// This class provides a wrapper around the basic DiagnosticBuilder 1726 /// class that emits diagnostics. ImmediateDiagBuilder is 1727 /// responsible for emitting the diagnostic (as DiagnosticBuilder 1728 /// does) and, if the diagnostic comes from inside a template 1729 /// instantiation, printing the template instantiation stack as 1730 /// well. 1731 class ImmediateDiagBuilder : public DiagnosticBuilder { 1732 Sema &SemaRef; 1733 unsigned DiagID; 1734 1735 public: ImmediateDiagBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1736 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 1737 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder && DB,Sema & SemaRef,unsigned DiagID)1738 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) 1739 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} 1740 1741 // This is a cunning lie. DiagnosticBuilder actually performs move 1742 // construction in its copy constructor (but due to varied uses, it's not 1743 // possible to conveniently express this as actual move construction). So 1744 // the default copy ctor here is fine, because the base class disables the 1745 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op 1746 // in that case anwyay. 1747 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; 1748 ~ImmediateDiagBuilder()1749 ~ImmediateDiagBuilder() { 1750 // If we aren't active, there is nothing to do. 1751 if (!isActive()) return; 1752 1753 // Otherwise, we need to emit the diagnostic. First clear the diagnostic 1754 // builder itself so it won't emit the diagnostic in its own destructor. 1755 // 1756 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 1757 // do its own needless checks to see if the diagnostic needs to be 1758 // emitted. However, because we take care to ensure that the builder 1759 // objects never escape, a sufficiently smart compiler will be able to 1760 // eliminate that code. 1761 Clear(); 1762 1763 // Dispatch to Sema to emit the diagnostic. 1764 SemaRef.EmitCurrentDiagnostic(DiagID); 1765 } 1766 1767 /// Teach operator<< to produce an object of the correct type. 1768 template <typename T> 1769 friend const ImmediateDiagBuilder & 1770 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { 1771 const DiagnosticBuilder &BaseDiag = Diag; 1772 BaseDiag << Value; 1773 return Diag; 1774 } 1775 1776 // It is necessary to limit this to rvalue reference to avoid calling this 1777 // function with a bitfield lvalue argument since non-const reference to 1778 // bitfield is not allowed. 1779 template <typename T, 1780 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>> 1781 const ImmediateDiagBuilder &operator<<(T &&V) const { 1782 const DiagnosticBuilder &BaseDiag = *this; 1783 BaseDiag << std::move(V); 1784 return *this; 1785 } 1786 }; 1787 1788 /// A generic diagnostic builder for errors which may or may not be deferred. 1789 /// 1790 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) 1791 /// which are not allowed to appear inside __device__ functions and are 1792 /// allowed to appear in __host__ __device__ functions only if the host+device 1793 /// function is never codegen'ed. 1794 /// 1795 /// To handle this, we use the notion of "deferred diagnostics", where we 1796 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. 1797 /// 1798 /// This class lets you emit either a regular diagnostic, a deferred 1799 /// diagnostic, or no diagnostic at all, according to an argument you pass to 1800 /// its constructor, thus simplifying the process of creating these "maybe 1801 /// deferred" diagnostics. 1802 class SemaDiagnosticBuilder { 1803 public: 1804 enum Kind { 1805 /// Emit no diagnostics. 1806 K_Nop, 1807 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). 1808 K_Immediate, 1809 /// Emit the diagnostic immediately, and, if it's a warning or error, also 1810 /// emit a call stack showing how this function can be reached by an a 1811 /// priori known-emitted function. 1812 K_ImmediateWithCallStack, 1813 /// Create a deferred diagnostic, which is emitted only if the function 1814 /// it's attached to is codegen'ed. Also emit a call stack as with 1815 /// K_ImmediateWithCallStack. 1816 K_Deferred 1817 }; 1818 1819 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, 1820 const FunctionDecl *Fn, Sema &S); 1821 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); 1822 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; 1823 1824 // The copy and move assignment operator is defined as deleted pending 1825 // further motivation. 1826 SemaDiagnosticBuilder &operator=(const SemaDiagnosticBuilder &) = delete; 1827 SemaDiagnosticBuilder &operator=(SemaDiagnosticBuilder &&) = delete; 1828 1829 ~SemaDiagnosticBuilder(); 1830 isImmediate()1831 bool isImmediate() const { return ImmediateDiag.has_value(); } 1832 1833 /// Convertible to bool: True if we immediately emitted an error, false if 1834 /// we didn't emit an error or we created a deferred error. 1835 /// 1836 /// Example usage: 1837 /// 1838 /// if (SemaDiagnosticBuilder(...) << foo << bar) 1839 /// return ExprError(); 1840 /// 1841 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably 1842 /// want to use these instead of creating a SemaDiagnosticBuilder yourself. 1843 operator bool() const { return isImmediate(); } 1844 1845 template <typename T> 1846 friend const SemaDiagnosticBuilder & 1847 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { 1848 if (Diag.ImmediateDiag) 1849 *Diag.ImmediateDiag << Value; 1850 else if (Diag.PartialDiagId) 1851 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second 1852 << Value; 1853 return Diag; 1854 } 1855 1856 // It is necessary to limit this to rvalue reference to avoid calling this 1857 // function with a bitfield lvalue argument since non-const reference to 1858 // bitfield is not allowed. 1859 template <typename T, 1860 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>> 1861 const SemaDiagnosticBuilder &operator<<(T &&V) const { 1862 if (ImmediateDiag) 1863 *ImmediateDiag << std::move(V); 1864 else if (PartialDiagId) 1865 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); 1866 return *this; 1867 } 1868 1869 friend const SemaDiagnosticBuilder & 1870 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { 1871 if (Diag.ImmediateDiag) 1872 PD.Emit(*Diag.ImmediateDiag); 1873 else if (Diag.PartialDiagId) 1874 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; 1875 return Diag; 1876 } 1877 AddFixItHint(const FixItHint & Hint)1878 void AddFixItHint(const FixItHint &Hint) const { 1879 if (ImmediateDiag) 1880 ImmediateDiag->AddFixItHint(Hint); 1881 else if (PartialDiagId) 1882 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); 1883 } 1884 ExprError(const SemaDiagnosticBuilder &)1885 friend ExprResult ExprError(const SemaDiagnosticBuilder &) { 1886 return ExprError(); 1887 } StmtError(const SemaDiagnosticBuilder &)1888 friend StmtResult StmtError(const SemaDiagnosticBuilder &) { 1889 return StmtError(); 1890 } ExprResult()1891 operator ExprResult() const { return ExprError(); } StmtResult()1892 operator StmtResult() const { return StmtError(); } TypeResult()1893 operator TypeResult() const { return TypeError(); } DeclResult()1894 operator DeclResult() const { return DeclResult(true); } MemInitResult()1895 operator MemInitResult() const { return MemInitResult(true); } 1896 1897 private: 1898 Sema &S; 1899 SourceLocation Loc; 1900 unsigned DiagID; 1901 const FunctionDecl *Fn; 1902 bool ShowCallStack; 1903 1904 // Invariant: At most one of these Optionals has a value. 1905 // FIXME: Switch these to a Variant once that exists. 1906 std::optional<ImmediateDiagBuilder> ImmediateDiag; 1907 std::optional<unsigned> PartialDiagId; 1908 }; 1909 1910 /// Is the last error level diagnostic immediate. This is used to determined 1911 /// whether the next info diagnostic should be immediate. 1912 bool IsLastErrorImmediate = true; 1913 1914 /// Emit a diagnostic. 1915 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, 1916 bool DeferHint = false); 1917 1918 /// Emit a partial diagnostic. 1919 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, 1920 bool DeferHint = false); 1921 1922 /// Build a partial diagnostic. 1923 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 1924 1925 /// Whether deferrable diagnostics should be deferred. 1926 bool DeferDiags = false; 1927 1928 /// RAII class to control scope of DeferDiags. 1929 class DeferDiagsRAII { 1930 Sema &S; 1931 bool SavedDeferDiags = false; 1932 1933 public: DeferDiagsRAII(Sema & S,bool DeferDiags)1934 DeferDiagsRAII(Sema &S, bool DeferDiags) 1935 : S(S), SavedDeferDiags(S.DeferDiags) { 1936 S.DeferDiags = DeferDiags; 1937 } ~DeferDiagsRAII()1938 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } 1939 }; 1940 1941 /// Whether uncompilable error has occurred. This includes error happens 1942 /// in deferred diagnostics. 1943 bool hasUncompilableErrorOccurred() const; 1944 1945 bool findMacroSpelling(SourceLocation &loc, StringRef name); 1946 1947 /// Get a string to suggest for zero-initialization of a type. 1948 std::string 1949 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; 1950 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 1951 1952 /// Calls \c Lexer::getLocForEndOfToken() 1953 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 1954 1955 /// Retrieve the module loader associated with the preprocessor. 1956 ModuleLoader &getModuleLoader() const; 1957 1958 /// Invent a new identifier for parameters of abbreviated templates. 1959 IdentifierInfo * 1960 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, 1961 unsigned Index); 1962 1963 void emitAndClearUnusedLocalTypedefWarnings(); 1964 1965 private: 1966 /// Function or variable declarations to be checked for whether the deferred 1967 /// diagnostics should be emitted. 1968 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; 1969 1970 public: 1971 // Emit all deferred diagnostics. 1972 void emitDeferredDiags(); 1973 1974 enum TUFragmentKind { 1975 /// The global module fragment, between 'module;' and a module-declaration. 1976 Global, 1977 /// A normal translation unit fragment. For a non-module unit, this is the 1978 /// entire translation unit. Otherwise, it runs from the module-declaration 1979 /// to the private-module-fragment (if any) or the end of the TU (if not). 1980 Normal, 1981 /// The private module fragment, between 'module :private;' and the end of 1982 /// the translation unit. 1983 Private 1984 }; 1985 1986 void ActOnStartOfTranslationUnit(); 1987 void ActOnEndOfTranslationUnit(); 1988 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); 1989 1990 void CheckDelegatingCtorCycles(); 1991 1992 Scope *getScopeForContext(DeclContext *Ctx); 1993 1994 void PushFunctionScope(); 1995 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 1996 sema::LambdaScopeInfo *PushLambdaScope(); 1997 1998 /// This is used to inform Sema what the current TemplateParameterDepth 1999 /// is during Parsing. Currently it is used to pass on the depth 2000 /// when parsing generic lambda 'auto' parameters. 2001 void RecordParsingTemplateParameterDepth(unsigned Depth); 2002 2003 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 2004 RecordDecl *RD, CapturedRegionKind K, 2005 unsigned OpenMPCaptureLevel = 0); 2006 2007 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short 2008 /// time after they've been popped. 2009 class PoppedFunctionScopeDeleter { 2010 Sema *Self; 2011 2012 public: PoppedFunctionScopeDeleter(Sema * Self)2013 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} 2014 void operator()(sema::FunctionScopeInfo *Scope) const; 2015 }; 2016 2017 using PoppedFunctionScopePtr = 2018 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; 2019 2020 PoppedFunctionScopePtr 2021 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 2022 const Decl *D = nullptr, 2023 QualType BlockType = QualType()); 2024 getCurFunction()2025 sema::FunctionScopeInfo *getCurFunction() const { 2026 return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); 2027 } 2028 2029 sema::FunctionScopeInfo *getEnclosingFunction() const; 2030 2031 void setFunctionHasBranchIntoScope(); 2032 void setFunctionHasBranchProtectedScope(); 2033 void setFunctionHasIndirectGoto(); 2034 void setFunctionHasMustTail(); 2035 2036 void PushCompoundScope(bool IsStmtExpr); 2037 void PopCompoundScope(); 2038 2039 sema::CompoundScopeInfo &getCurCompoundScope() const; 2040 2041 bool hasAnyUnrecoverableErrorsInThisFunction() const; 2042 2043 /// Retrieve the current block, if any. 2044 sema::BlockScopeInfo *getCurBlock(); 2045 2046 /// Get the innermost lambda enclosing the current location, if any. This 2047 /// looks through intervening non-lambda scopes such as local functions and 2048 /// blocks. 2049 sema::LambdaScopeInfo *getEnclosingLambda() const; 2050 2051 /// Retrieve the current lambda scope info, if any. 2052 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most 2053 /// lambda scope info ignoring all inner capturing scopes that are not 2054 /// lambda scopes. 2055 sema::LambdaScopeInfo * 2056 getCurLambda(bool IgnoreNonLambdaCapturingScope = false); 2057 2058 /// Retrieve the current generic lambda info, if any. 2059 sema::LambdaScopeInfo *getCurGenericLambda(); 2060 2061 /// Retrieve the current captured region, if any. 2062 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 2063 2064 /// Retrieve the current function, if any, that should be analyzed for 2065 /// potential availability violations. 2066 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); 2067 2068 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls WeakTopLevelDecls()2069 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 2070 2071 /// Called before parsing a function declarator belonging to a function 2072 /// declaration. 2073 void ActOnStartFunctionDeclarationDeclarator(Declarator &D, 2074 unsigned TemplateParameterDepth); 2075 2076 /// Called after parsing a function declarator belonging to a function 2077 /// declaration. 2078 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); 2079 2080 void ActOnComment(SourceRange Comment); 2081 2082 //===--------------------------------------------------------------------===// 2083 // Type Analysis / Processing: SemaType.cpp. 2084 // 2085 2086 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 2087 const DeclSpec *DS = nullptr); 2088 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 2089 const DeclSpec *DS = nullptr); 2090 QualType BuildPointerType(QualType T, 2091 SourceLocation Loc, DeclarationName Entity); 2092 QualType BuildReferenceType(QualType T, bool LValueRef, 2093 SourceLocation Loc, DeclarationName Entity); 2094 QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, 2095 unsigned Quals, SourceRange Brackets, 2096 DeclarationName Entity); 2097 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); 2098 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 2099 SourceLocation AttrLoc); 2100 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, 2101 SourceLocation AttrLoc); 2102 2103 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 2104 SourceLocation AttrLoc); 2105 2106 /// Same as above, but constructs the AddressSpace index if not provided. 2107 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 2108 SourceLocation AttrLoc); 2109 2110 CodeAlignAttr *BuildCodeAlignAttr(const AttributeCommonInfo &CI, Expr *E); 2111 bool CheckRebuiltStmtAttributes(ArrayRef<const Attr *> Attrs); 2112 2113 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); 2114 2115 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 2116 2117 /// Check an argument list for placeholders that we won't try to 2118 /// handle later. 2119 bool CheckArgsForPlaceholders(MultiExprArg args); 2120 2121 /// Build a function type. 2122 /// 2123 /// This routine checks the function type according to C++ rules and 2124 /// under the assumption that the result type and parameter types have 2125 /// just been instantiated from a template. It therefore duplicates 2126 /// some of the behavior of GetTypeForDeclarator, but in a much 2127 /// simpler form that is only suitable for this narrow use case. 2128 /// 2129 /// \param T The return type of the function. 2130 /// 2131 /// \param ParamTypes The parameter types of the function. This array 2132 /// will be modified to account for adjustments to the types of the 2133 /// function parameters. 2134 /// 2135 /// \param Loc The location of the entity whose type involves this 2136 /// function type or, if there is no such entity, the location of the 2137 /// type that will have function type. 2138 /// 2139 /// \param Entity The name of the entity that involves the function 2140 /// type, if known. 2141 /// 2142 /// \param EPI Extra information about the function type. Usually this will 2143 /// be taken from an existing function with the same prototype. 2144 /// 2145 /// \returns A suitable function type, if there are no errors. The 2146 /// unqualified type will always be a FunctionProtoType. 2147 /// Otherwise, returns a NULL type. 2148 QualType BuildFunctionType(QualType T, 2149 MutableArrayRef<QualType> ParamTypes, 2150 SourceLocation Loc, DeclarationName Entity, 2151 const FunctionProtoType::ExtProtoInfo &EPI); 2152 2153 QualType BuildMemberPointerType(QualType T, QualType Class, 2154 SourceLocation Loc, 2155 DeclarationName Entity); 2156 QualType BuildBlockPointerType(QualType T, 2157 SourceLocation Loc, DeclarationName Entity); 2158 QualType BuildParenType(QualType T); 2159 QualType BuildAtomicType(QualType T, SourceLocation Loc); 2160 QualType BuildReadPipeType(QualType T, 2161 SourceLocation Loc); 2162 QualType BuildWritePipeType(QualType T, 2163 SourceLocation Loc); 2164 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); 2165 2166 TypeSourceInfo *GetTypeForDeclarator(Declarator &D); 2167 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 2168 2169 /// Package the given type and TSI into a ParsedType. 2170 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 2171 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 2172 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 2173 static QualType GetTypeFromParser(ParsedType Ty, 2174 TypeSourceInfo **TInfo = nullptr); 2175 CanThrowResult canThrow(const Stmt *E); 2176 /// Determine whether the callee of a particular function call can throw. 2177 /// E, D and Loc are all optional. 2178 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, 2179 SourceLocation Loc = SourceLocation()); 2180 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 2181 const FunctionProtoType *FPT); 2182 void UpdateExceptionSpec(FunctionDecl *FD, 2183 const FunctionProtoType::ExceptionSpecInfo &ESI); 2184 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); 2185 bool CheckDistantExceptionSpec(QualType T); 2186 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 2187 bool CheckEquivalentExceptionSpec( 2188 const FunctionProtoType *Old, SourceLocation OldLoc, 2189 const FunctionProtoType *New, SourceLocation NewLoc); 2190 bool CheckEquivalentExceptionSpec( 2191 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 2192 const FunctionProtoType *Old, SourceLocation OldLoc, 2193 const FunctionProtoType *New, SourceLocation NewLoc); 2194 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); 2195 bool CheckExceptionSpecSubset( 2196 const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, 2197 const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, 2198 const FunctionProtoType *Superset, bool SkipSupersetFirstParameter, 2199 SourceLocation SuperLoc, const FunctionProtoType *Subset, 2200 bool SkipSubsetFirstParameter, SourceLocation SubLoc); 2201 bool CheckParamExceptionSpec( 2202 const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, 2203 const FunctionProtoType *Target, bool SkipTargetFirstParameter, 2204 SourceLocation TargetLoc, const FunctionProtoType *Source, 2205 bool SkipSourceFirstParameter, SourceLocation SourceLoc); 2206 2207 TypeResult ActOnTypeName(Declarator &D); 2208 2209 /// The parser has parsed the context-sensitive type 'instancetype' 2210 /// in an Objective-C message declaration. Return the appropriate type. 2211 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 2212 2213 /// Abstract class used to diagnose incomplete types. 2214 struct TypeDiagnoser { TypeDiagnoserTypeDiagnoser2215 TypeDiagnoser() {} 2216 2217 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; ~TypeDiagnoserTypeDiagnoser2218 virtual ~TypeDiagnoser() {} 2219 }; 2220 getPrintable(int I)2221 static int getPrintable(int I) { return I; } getPrintable(unsigned I)2222 static unsigned getPrintable(unsigned I) { return I; } getPrintable(bool B)2223 static bool getPrintable(bool B) { return B; } getPrintable(const char * S)2224 static const char * getPrintable(const char *S) { return S; } getPrintable(StringRef S)2225 static StringRef getPrintable(StringRef S) { return S; } getPrintable(const std::string & S)2226 static const std::string &getPrintable(const std::string &S) { return S; } getPrintable(const IdentifierInfo * II)2227 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 2228 return II; 2229 } getPrintable(DeclarationName N)2230 static DeclarationName getPrintable(DeclarationName N) { return N; } getPrintable(QualType T)2231 static QualType getPrintable(QualType T) { return T; } getPrintable(SourceRange R)2232 static SourceRange getPrintable(SourceRange R) { return R; } getPrintable(SourceLocation L)2233 static SourceRange getPrintable(SourceLocation L) { return L; } getPrintable(const Expr * E)2234 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } getPrintable(TypeLoc TL)2235 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 2236 2237 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { 2238 protected: 2239 unsigned DiagID; 2240 std::tuple<const Ts &...> Args; 2241 2242 template <std::size_t... Is> emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)2243 void emit(const SemaDiagnosticBuilder &DB, 2244 std::index_sequence<Is...>) const { 2245 // Apply all tuple elements to the builder in order. 2246 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; 2247 (void)Dummy; 2248 } 2249 2250 public: BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)2251 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) 2252 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { 2253 assert(DiagID != 0 && "no diagnostic for type diagnoser"); 2254 } 2255 diagnose(Sema & S,SourceLocation Loc,QualType T)2256 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 2257 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); 2258 emit(DB, std::index_sequence_for<Ts...>()); 2259 DB << T; 2260 } 2261 }; 2262 2263 /// Do a check to make sure \p Name looks like a legal argument for the 2264 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name 2265 /// is invalid for the given declaration. 2266 /// 2267 /// \p AL is used to provide caret diagnostics in case of a malformed name. 2268 /// 2269 /// \returns true if the name is a valid swift name for \p D, false otherwise. 2270 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, 2271 const ParsedAttr &AL, bool IsAsync); 2272 2273 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type 2274 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. 2275 /// For example, a diagnostic with no other parameters would generally have 2276 /// the form "...%select{incomplete|sizeless}0 type %1...". 2277 template <typename... Ts> 2278 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { 2279 public: SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)2280 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) 2281 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} 2282 diagnose(Sema & S,SourceLocation Loc,QualType T)2283 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 2284 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); 2285 this->emit(DB, std::index_sequence_for<Ts...>()); 2286 DB << T->isSizelessType() << T; 2287 } 2288 }; 2289 2290 enum class CompleteTypeKind { 2291 /// Apply the normal rules for complete types. In particular, 2292 /// treat all sizeless types as incomplete. 2293 Normal, 2294 2295 /// Relax the normal rules for complete types so that they include 2296 /// sizeless built-in types. 2297 AcceptSizeless, 2298 2299 // FIXME: Eventually we should flip the default to Normal and opt in 2300 // to AcceptSizeless rather than opt out of it. 2301 Default = AcceptSizeless 2302 }; 2303 2304 enum class AcceptableKind { Visible, Reachable }; 2305 2306 private: 2307 /// Methods for marking which expressions involve dereferencing a pointer 2308 /// marked with the 'noderef' attribute. Expressions are checked bottom up as 2309 /// they are parsed, meaning that a noderef pointer may not be accessed. For 2310 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the 2311 /// `*p`, but need to check that `address of` is called on it. This requires 2312 /// keeping a container of all pending expressions and checking if the address 2313 /// of them are eventually taken. 2314 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); 2315 void CheckAddressOfNoDeref(const Expr *E); 2316 void CheckMemberAccessOfNoDeref(const MemberExpr *E); 2317 2318 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 2319 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); 2320 2321 struct ModuleScope { 2322 SourceLocation BeginLoc; 2323 clang::Module *Module = nullptr; 2324 VisibleModuleSet OuterVisibleModules; 2325 }; 2326 /// The modules we're currently parsing. 2327 llvm::SmallVector<ModuleScope, 16> ModuleScopes; 2328 2329 /// For an interface unit, this is the implicitly imported interface unit. 2330 clang::Module *ThePrimaryInterface = nullptr; 2331 2332 /// The explicit global module fragment of the current translation unit. 2333 /// The explicit Global Module Fragment, as specified in C++ 2334 /// [module.global.frag]. 2335 clang::Module *TheGlobalModuleFragment = nullptr; 2336 2337 /// The implicit global module fragments of the current translation unit. 2338 /// 2339 /// The contents in the implicit global module fragment can't be discarded. 2340 clang::Module *TheImplicitGlobalModuleFragment = nullptr; 2341 2342 /// Namespace definitions that we will export when they finish. 2343 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; 2344 2345 /// In a C++ standard module, inline declarations require a definition to be 2346 /// present at the end of a definition domain. This set holds the decls to 2347 /// be checked at the end of the TU. 2348 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls; 2349 2350 /// Helper function to judge if we are in module purview. 2351 /// Return false if we are not in a module. 2352 bool isCurrentModulePurview() const; 2353 2354 /// Enter the scope of the explicit global module fragment. 2355 Module *PushGlobalModuleFragment(SourceLocation BeginLoc); 2356 /// Leave the scope of the explicit global module fragment. 2357 void PopGlobalModuleFragment(); 2358 2359 /// Enter the scope of an implicit global module fragment. 2360 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc); 2361 /// Leave the scope of an implicit global module fragment. 2362 void PopImplicitGlobalModuleFragment(); 2363 2364 VisibleModuleSet VisibleModules; 2365 2366 /// Cache for module units which is usable for current module. 2367 llvm::DenseSet<const Module *> UsableModuleUnitsCache; 2368 2369 bool isUsableModule(const Module *M); 2370 2371 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind); 2372 2373 public: 2374 /// Get the module unit whose scope we are currently within. getCurrentModule()2375 Module *getCurrentModule() const { 2376 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; 2377 } 2378 2379 /// Is the module scope we are an implementation unit? currentModuleIsImplementation()2380 bool currentModuleIsImplementation() const { 2381 return ModuleScopes.empty() 2382 ? false 2383 : ModuleScopes.back().Module->isModuleImplementation(); 2384 } 2385 2386 /// Is the module scope we are in a C++ Header Unit? currentModuleIsHeaderUnit()2387 bool currentModuleIsHeaderUnit() const { 2388 return ModuleScopes.empty() ? false 2389 : ModuleScopes.back().Module->isHeaderUnit(); 2390 } 2391 2392 /// Get the module owning an entity. getOwningModule(const Decl * Entity)2393 Module *getOwningModule(const Decl *Entity) { 2394 return Entity->getOwningModule(); 2395 } 2396 2397 /// Make a merged definition of an existing hidden definition \p ND 2398 /// visible at the specified location. 2399 void makeMergedDefinitionVisible(NamedDecl *ND); 2400 2401 bool isModuleVisible(const Module *M, bool ModulePrivate = false); 2402 2403 // When loading a non-modular PCH files, this is used to restore module 2404 // visibility. makeModuleVisible(Module * Mod,SourceLocation ImportLoc)2405 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { 2406 VisibleModules.setVisible(Mod, ImportLoc); 2407 } 2408 2409 /// Determine whether a declaration is visible to name lookup. isVisible(const NamedDecl * D)2410 bool isVisible(const NamedDecl *D) { 2411 return D->isUnconditionallyVisible() || 2412 isAcceptableSlow(D, AcceptableKind::Visible); 2413 } 2414 2415 /// Determine whether a declaration is reachable. isReachable(const NamedDecl * D)2416 bool isReachable(const NamedDecl *D) { 2417 // All visible declarations are reachable. 2418 return D->isUnconditionallyVisible() || 2419 isAcceptableSlow(D, AcceptableKind::Reachable); 2420 } 2421 2422 /// Determine whether a declaration is acceptable (visible/reachable). isAcceptable(const NamedDecl * D,AcceptableKind Kind)2423 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) { 2424 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D); 2425 } 2426 2427 /// Determine whether any declaration of an entity is visible. 2428 bool 2429 hasVisibleDeclaration(const NamedDecl *D, 2430 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 2431 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); 2432 } 2433 2434 bool hasVisibleDeclarationSlow(const NamedDecl *D, 2435 llvm::SmallVectorImpl<Module *> *Modules); 2436 /// Determine whether any declaration of an entity is reachable. 2437 bool 2438 hasReachableDeclaration(const NamedDecl *D, 2439 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 2440 return isReachable(D) || hasReachableDeclarationSlow(D, Modules); 2441 } 2442 bool hasReachableDeclarationSlow( 2443 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2444 2445 bool hasVisibleMergedDefinition(const NamedDecl *Def); 2446 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def); 2447 2448 /// Determine if \p D and \p Suggested have a structurally compatible 2449 /// layout as described in C11 6.2.7/1. 2450 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); 2451 2452 /// Determine if \p D has a visible definition. If not, suggest a declaration 2453 /// that should be made visible to expose the definition. 2454 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 2455 bool OnlyNeedComplete = false); hasVisibleDefinition(const NamedDecl * D)2456 bool hasVisibleDefinition(const NamedDecl *D) { 2457 NamedDecl *Hidden; 2458 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); 2459 } 2460 2461 /// Determine if \p D has a reachable definition. If not, suggest a 2462 /// declaration that should be made reachable to expose the definition. 2463 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, 2464 bool OnlyNeedComplete = false); hasReachableDefinition(NamedDecl * D)2465 bool hasReachableDefinition(NamedDecl *D) { 2466 NamedDecl *Hidden; 2467 return hasReachableDefinition(D, &Hidden); 2468 } 2469 2470 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, 2471 AcceptableKind Kind, 2472 bool OnlyNeedComplete = false); hasAcceptableDefinition(NamedDecl * D,AcceptableKind Kind)2473 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) { 2474 NamedDecl *Hidden; 2475 return hasAcceptableDefinition(D, &Hidden, Kind); 2476 } 2477 2478 /// Determine if the template parameter \p D has a visible default argument. 2479 bool 2480 hasVisibleDefaultArgument(const NamedDecl *D, 2481 llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2482 /// Determine if the template parameter \p D has a reachable default argument. 2483 bool hasReachableDefaultArgument( 2484 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2485 /// Determine if the template parameter \p D has a reachable default argument. 2486 bool hasAcceptableDefaultArgument(const NamedDecl *D, 2487 llvm::SmallVectorImpl<Module *> *Modules, 2488 Sema::AcceptableKind Kind); 2489 2490 /// Determine if there is a visible declaration of \p D that is an explicit 2491 /// specialization declaration for a specialization of a template. (For a 2492 /// member specialization, use hasVisibleMemberSpecialization.) 2493 bool hasVisibleExplicitSpecialization( 2494 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2495 /// Determine if there is a reachable declaration of \p D that is an explicit 2496 /// specialization declaration for a specialization of a template. (For a 2497 /// member specialization, use hasReachableMemberSpecialization.) 2498 bool hasReachableExplicitSpecialization( 2499 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2500 2501 /// Determine if there is a visible declaration of \p D that is a member 2502 /// specialization declaration (as opposed to an instantiated declaration). 2503 bool hasVisibleMemberSpecialization( 2504 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2505 /// Determine if there is a reachable declaration of \p D that is a member 2506 /// specialization declaration (as opposed to an instantiated declaration). 2507 bool hasReachableMemberSpecialization( 2508 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2509 2510 /// Determine if \p A and \p B are equivalent internal linkage declarations 2511 /// from different modules, and thus an ambiguity error can be downgraded to 2512 /// an extension warning. 2513 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 2514 const NamedDecl *B); 2515 void diagnoseEquivalentInternalLinkageDeclarations( 2516 SourceLocation Loc, const NamedDecl *D, 2517 ArrayRef<const NamedDecl *> Equiv); 2518 2519 bool isUsualDeallocationFunction(const CXXMethodDecl *FD); 2520 2521 // Check whether the size of array element of type \p EltTy is a multiple of 2522 // its alignment and return false if it isn't. 2523 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc); 2524 2525 bool isCompleteType(SourceLocation Loc, QualType T, 2526 CompleteTypeKind Kind = CompleteTypeKind::Default) { 2527 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); 2528 } 2529 bool RequireCompleteType(SourceLocation Loc, QualType T, 2530 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); 2531 bool RequireCompleteType(SourceLocation Loc, QualType T, 2532 CompleteTypeKind Kind, unsigned DiagID); 2533 RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)2534 bool RequireCompleteType(SourceLocation Loc, QualType T, 2535 TypeDiagnoser &Diagnoser) { 2536 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); 2537 } RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)2538 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { 2539 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); 2540 } 2541 2542 template <typename... Ts> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2543 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, 2544 const Ts &...Args) { 2545 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2546 return RequireCompleteType(Loc, T, Diagnoser); 2547 } 2548 2549 template <typename... Ts> RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2550 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, 2551 const Ts &... Args) { 2552 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2553 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); 2554 } 2555 2556 /// Get the type of expression E, triggering instantiation to complete the 2557 /// type if necessary -- that is, if the expression refers to a templated 2558 /// static data member of incomplete array type. 2559 /// 2560 /// May still return an incomplete type if instantiation was not possible or 2561 /// if the type is incomplete for a different reason. Use 2562 /// RequireCompleteExprType instead if a diagnostic is expected for an 2563 /// incomplete expression type. 2564 QualType getCompletedType(Expr *E); 2565 2566 void completeExprArrayBound(Expr *E); 2567 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 2568 TypeDiagnoser &Diagnoser); 2569 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 2570 2571 template <typename... Ts> RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2572 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { 2573 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2574 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 2575 } 2576 2577 template <typename... Ts> RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2578 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, 2579 const Ts &... Args) { 2580 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2581 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); 2582 } 2583 2584 bool RequireLiteralType(SourceLocation Loc, QualType T, 2585 TypeDiagnoser &Diagnoser); 2586 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 2587 2588 template <typename... Ts> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2589 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, 2590 const Ts &...Args) { 2591 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2592 return RequireLiteralType(Loc, T, Diagnoser); 2593 } 2594 2595 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 2596 const CXXScopeSpec &SS, QualType T, 2597 TagDecl *OwnedTagDecl = nullptr); 2598 2599 // Returns the underlying type of a decltype with the given expression. 2600 QualType getDecltypeForExpr(Expr *E); 2601 2602 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind); 2603 /// If AsUnevaluated is false, E is treated as though it were an evaluated 2604 /// context, such as when building a type for decltype(auto). 2605 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true); 2606 2607 using UTTKind = UnaryTransformType::UTTKind; 2608 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, 2609 SourceLocation Loc); 2610 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc); 2611 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc); 2612 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc); 2613 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc); 2614 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, 2615 SourceLocation Loc); 2616 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, 2617 SourceLocation Loc); 2618 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, 2619 SourceLocation Loc); 2620 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, 2621 SourceLocation Loc); 2622 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, 2623 SourceLocation Loc); 2624 2625 //===--------------------------------------------------------------------===// 2626 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 2627 // 2628 2629 struct SkipBodyInfo { 2630 SkipBodyInfo() = default; 2631 bool ShouldSkip = false; 2632 bool CheckSameAsPrevious = false; 2633 NamedDecl *Previous = nullptr; 2634 NamedDecl *New = nullptr; 2635 }; 2636 2637 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 2638 2639 void DiagnoseUseOfUnimplementedSelectors(); 2640 2641 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 2642 2643 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 2644 Scope *S, CXXScopeSpec *SS = nullptr, 2645 bool isClassName = false, bool HasTrailingDot = false, 2646 ParsedType ObjectType = nullptr, 2647 bool IsCtorOrDtorName = false, 2648 bool WantNontrivialTypeSourceInfo = false, 2649 bool IsClassTemplateDeductionContext = true, 2650 ImplicitTypenameContext AllowImplicitTypename = 2651 ImplicitTypenameContext::No, 2652 IdentifierInfo **CorrectedII = nullptr); 2653 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 2654 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 2655 void DiagnoseUnknownTypeName(IdentifierInfo *&II, 2656 SourceLocation IILoc, 2657 Scope *S, 2658 CXXScopeSpec *SS, 2659 ParsedType &SuggestedType, 2660 bool IsTemplateName = false); 2661 2662 /// Attempt to behave like MSVC in situations where lookup of an unqualified 2663 /// type name has failed in a dependent context. In these situations, we 2664 /// automatically form a DependentTypeName that will retry lookup in a related 2665 /// scope during instantiation. 2666 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 2667 SourceLocation NameLoc, 2668 bool IsTemplateTypeArg); 2669 2670 /// Describes the result of the name lookup and resolution performed 2671 /// by \c ClassifyName(). 2672 enum NameClassificationKind { 2673 /// This name is not a type or template in this context, but might be 2674 /// something else. 2675 NC_Unknown, 2676 /// Classification failed; an error has been produced. 2677 NC_Error, 2678 /// The name has been typo-corrected to a keyword. 2679 NC_Keyword, 2680 /// The name was classified as a type. 2681 NC_Type, 2682 /// The name was classified as a specific non-type, non-template 2683 /// declaration. ActOnNameClassifiedAsNonType should be called to 2684 /// convert the declaration to an expression. 2685 NC_NonType, 2686 /// The name was classified as an ADL-only function name. 2687 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the 2688 /// result to an expression. 2689 NC_UndeclaredNonType, 2690 /// The name denotes a member of a dependent type that could not be 2691 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to 2692 /// convert the result to an expression. 2693 NC_DependentNonType, 2694 /// The name was classified as an overload set, and an expression 2695 /// representing that overload set has been formed. 2696 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable 2697 /// expression referencing the overload set. 2698 NC_OverloadSet, 2699 /// The name was classified as a template whose specializations are types. 2700 NC_TypeTemplate, 2701 /// The name was classified as a variable template name. 2702 NC_VarTemplate, 2703 /// The name was classified as a function template name. 2704 NC_FunctionTemplate, 2705 /// The name was classified as an ADL-only function template name. 2706 NC_UndeclaredTemplate, 2707 /// The name was classified as a concept name. 2708 NC_Concept, 2709 }; 2710 2711 class NameClassification { 2712 NameClassificationKind Kind; 2713 union { 2714 ExprResult Expr; 2715 NamedDecl *NonTypeDecl; 2716 TemplateName Template; 2717 ParsedType Type; 2718 }; 2719 NameClassification(NameClassificationKind Kind)2720 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 2721 2722 public: NameClassification(ParsedType Type)2723 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 2724 NameClassification(const IdentifierInfo * Keyword)2725 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} 2726 Error()2727 static NameClassification Error() { 2728 return NameClassification(NC_Error); 2729 } 2730 Unknown()2731 static NameClassification Unknown() { 2732 return NameClassification(NC_Unknown); 2733 } 2734 OverloadSet(ExprResult E)2735 static NameClassification OverloadSet(ExprResult E) { 2736 NameClassification Result(NC_OverloadSet); 2737 Result.Expr = E; 2738 return Result; 2739 } 2740 NonType(NamedDecl * D)2741 static NameClassification NonType(NamedDecl *D) { 2742 NameClassification Result(NC_NonType); 2743 Result.NonTypeDecl = D; 2744 return Result; 2745 } 2746 UndeclaredNonType()2747 static NameClassification UndeclaredNonType() { 2748 return NameClassification(NC_UndeclaredNonType); 2749 } 2750 DependentNonType()2751 static NameClassification DependentNonType() { 2752 return NameClassification(NC_DependentNonType); 2753 } 2754 TypeTemplate(TemplateName Name)2755 static NameClassification TypeTemplate(TemplateName Name) { 2756 NameClassification Result(NC_TypeTemplate); 2757 Result.Template = Name; 2758 return Result; 2759 } 2760 VarTemplate(TemplateName Name)2761 static NameClassification VarTemplate(TemplateName Name) { 2762 NameClassification Result(NC_VarTemplate); 2763 Result.Template = Name; 2764 return Result; 2765 } 2766 FunctionTemplate(TemplateName Name)2767 static NameClassification FunctionTemplate(TemplateName Name) { 2768 NameClassification Result(NC_FunctionTemplate); 2769 Result.Template = Name; 2770 return Result; 2771 } 2772 Concept(TemplateName Name)2773 static NameClassification Concept(TemplateName Name) { 2774 NameClassification Result(NC_Concept); 2775 Result.Template = Name; 2776 return Result; 2777 } 2778 UndeclaredTemplate(TemplateName Name)2779 static NameClassification UndeclaredTemplate(TemplateName Name) { 2780 NameClassification Result(NC_UndeclaredTemplate); 2781 Result.Template = Name; 2782 return Result; 2783 } 2784 getKind()2785 NameClassificationKind getKind() const { return Kind; } 2786 getExpression()2787 ExprResult getExpression() const { 2788 assert(Kind == NC_OverloadSet); 2789 return Expr; 2790 } 2791 getType()2792 ParsedType getType() const { 2793 assert(Kind == NC_Type); 2794 return Type; 2795 } 2796 getNonTypeDecl()2797 NamedDecl *getNonTypeDecl() const { 2798 assert(Kind == NC_NonType); 2799 return NonTypeDecl; 2800 } 2801 getTemplateName()2802 TemplateName getTemplateName() const { 2803 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 2804 Kind == NC_VarTemplate || Kind == NC_Concept || 2805 Kind == NC_UndeclaredTemplate); 2806 return Template; 2807 } 2808 getTemplateNameKind()2809 TemplateNameKind getTemplateNameKind() const { 2810 switch (Kind) { 2811 case NC_TypeTemplate: 2812 return TNK_Type_template; 2813 case NC_FunctionTemplate: 2814 return TNK_Function_template; 2815 case NC_VarTemplate: 2816 return TNK_Var_template; 2817 case NC_Concept: 2818 return TNK_Concept_template; 2819 case NC_UndeclaredTemplate: 2820 return TNK_Undeclared_template; 2821 default: 2822 llvm_unreachable("unsupported name classification."); 2823 } 2824 } 2825 }; 2826 2827 /// Perform name lookup on the given name, classifying it based on 2828 /// the results of name lookup and the following token. 2829 /// 2830 /// This routine is used by the parser to resolve identifiers and help direct 2831 /// parsing. When the identifier cannot be found, this routine will attempt 2832 /// to correct the typo and classify based on the resulting name. 2833 /// 2834 /// \param S The scope in which we're performing name lookup. 2835 /// 2836 /// \param SS The nested-name-specifier that precedes the name. 2837 /// 2838 /// \param Name The identifier. If typo correction finds an alternative name, 2839 /// this pointer parameter will be updated accordingly. 2840 /// 2841 /// \param NameLoc The location of the identifier. 2842 /// 2843 /// \param NextToken The token following the identifier. Used to help 2844 /// disambiguate the name. 2845 /// 2846 /// \param CCC The correction callback, if typo correction is desired. 2847 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, 2848 IdentifierInfo *&Name, SourceLocation NameLoc, 2849 const Token &NextToken, 2850 CorrectionCandidateCallback *CCC = nullptr); 2851 2852 /// Act on the result of classifying a name as an undeclared (ADL-only) 2853 /// non-type declaration. 2854 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 2855 SourceLocation NameLoc); 2856 /// Act on the result of classifying a name as an undeclared member of a 2857 /// dependent base class. 2858 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 2859 IdentifierInfo *Name, 2860 SourceLocation NameLoc, 2861 bool IsAddressOfOperand); 2862 /// Act on the result of classifying a name as a specific non-type 2863 /// declaration. 2864 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 2865 NamedDecl *Found, 2866 SourceLocation NameLoc, 2867 const Token &NextToken); 2868 /// Act on the result of classifying a name as an overload set. 2869 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); 2870 2871 /// Describes the detailed kind of a template name. Used in diagnostics. 2872 enum class TemplateNameKindForDiagnostics { 2873 ClassTemplate, 2874 FunctionTemplate, 2875 VarTemplate, 2876 AliasTemplate, 2877 TemplateTemplateParam, 2878 Concept, 2879 DependentTemplate 2880 }; 2881 TemplateNameKindForDiagnostics 2882 getTemplateNameKindForDiagnostics(TemplateName Name); 2883 2884 /// Determine whether it's plausible that E was intended to be a 2885 /// template-name. mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2886 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { 2887 if (!getLangOpts().CPlusPlus || E.isInvalid()) 2888 return false; 2889 Dependent = false; 2890 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) 2891 return !DRE->hasExplicitTemplateArgs(); 2892 if (auto *ME = dyn_cast<MemberExpr>(E.get())) 2893 return !ME->hasExplicitTemplateArgs(); 2894 Dependent = true; 2895 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) 2896 return !DSDRE->hasExplicitTemplateArgs(); 2897 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) 2898 return !DSME->hasExplicitTemplateArgs(); 2899 // Any additional cases recognized here should also be handled by 2900 // diagnoseExprIntendedAsTemplateName. 2901 return false; 2902 } 2903 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 2904 SourceLocation Less, 2905 SourceLocation Greater); 2906 2907 void warnOnReservedIdentifier(const NamedDecl *D); 2908 2909 Decl *ActOnDeclarator(Scope *S, Declarator &D); 2910 2911 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 2912 MultiTemplateParamsArg TemplateParameterLists); 2913 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 2914 QualType &T, SourceLocation Loc, 2915 unsigned FailedFoldDiagID); 2916 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 2917 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 2918 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 2919 DeclarationName Name, SourceLocation Loc, 2920 bool IsTemplateId); 2921 void 2922 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2923 SourceLocation FallbackLoc, 2924 SourceLocation ConstQualLoc = SourceLocation(), 2925 SourceLocation VolatileQualLoc = SourceLocation(), 2926 SourceLocation RestrictQualLoc = SourceLocation(), 2927 SourceLocation AtomicQualLoc = SourceLocation(), 2928 SourceLocation UnalignedQualLoc = SourceLocation()); 2929 2930 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 2931 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 2932 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, 2933 const LookupResult &R); 2934 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); 2935 NamedDecl *getShadowedDeclaration(const BindingDecl *D, 2936 const LookupResult &R); 2937 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 2938 const LookupResult &R); 2939 void CheckShadow(Scope *S, VarDecl *D); 2940 2941 /// Warn if 'E', which is an expression that is about to be modified, refers 2942 /// to a shadowing declaration. 2943 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); 2944 2945 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); 2946 2947 private: 2948 /// Map of current shadowing declarations to shadowed declarations. Warn if 2949 /// it looks like the user is trying to modify the shadowing declaration. 2950 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; 2951 2952 public: 2953 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 2954 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); 2955 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 2956 TypedefNameDecl *NewTD); 2957 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 2958 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2959 TypeSourceInfo *TInfo, 2960 LookupResult &Previous); 2961 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 2962 LookupResult &Previous, bool &Redeclaration); 2963 NamedDecl *ActOnVariableDeclarator( 2964 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 2965 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 2966 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt); 2967 NamedDecl * 2968 ActOnDecompositionDeclarator(Scope *S, Declarator &D, 2969 MultiTemplateParamsArg TemplateParamLists); 2970 void DiagPlaceholderVariableDefinition(SourceLocation Loc); 2971 bool DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, 2972 RecordDecl *ClassDecl, 2973 const IdentifierInfo *Name); 2974 // Returns true if the variable declaration is a redeclaration 2975 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 2976 void CheckVariableDeclarationType(VarDecl *NewVD); 2977 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 2978 Expr *Init); 2979 void CheckCompleteVariableDeclaration(VarDecl *VD); 2980 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); 2981 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 2982 2983 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2984 TypeSourceInfo *TInfo, 2985 LookupResult &Previous, 2986 MultiTemplateParamsArg TemplateParamLists, 2987 bool &AddToScope); 2988 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 2989 2990 enum class CheckConstexprKind { 2991 /// Diagnose issues that are non-constant or that are extensions. 2992 Diagnose, 2993 /// Identify whether this function satisfies the formal rules for constexpr 2994 /// functions in the current lanugage mode (with no extensions). 2995 CheckValid 2996 }; 2997 2998 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, 2999 CheckConstexprKind Kind); 3000 3001 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 3002 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 3003 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 3004 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 3005 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 3006 // Returns true if the function declaration is a redeclaration 3007 bool CheckFunctionDeclaration(Scope *S, 3008 FunctionDecl *NewFD, LookupResult &Previous, 3009 bool IsMemberSpecialization, bool DeclIsDefn); 3010 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); 3011 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 3012 QualType NewT, QualType OldT); 3013 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 3014 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 3015 void ActOnHLSLTopLevelFunction(FunctionDecl *FD); 3016 void CheckHLSLEntryPoint(FunctionDecl *FD); 3017 void CheckHLSLSemanticAnnotation(FunctionDecl *EntryPoint, const Decl *Param, 3018 const HLSLAnnotationAttr *AnnotationAttr); 3019 void DiagnoseHLSLAttrStageMismatch( 3020 const Attr *A, HLSLShaderAttr::ShaderType Stage, 3021 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages); 3022 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 3023 bool IsDefinition); 3024 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); 3025 Decl *ActOnParamDeclarator(Scope *S, Declarator &D, 3026 SourceLocation ExplicitThisLoc = {}); 3027 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 3028 SourceLocation Loc, 3029 QualType T); 3030 QualType AdjustParameterTypeForObjCAutoRefCount(QualType T, 3031 SourceLocation NameLoc, 3032 TypeSourceInfo *TSInfo); 3033 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 3034 SourceLocation NameLoc, IdentifierInfo *Name, 3035 QualType T, TypeSourceInfo *TSInfo, 3036 StorageClass SC); 3037 void ActOnParamDefaultArgument(Decl *param, 3038 SourceLocation EqualLoc, 3039 Expr *defarg); 3040 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, 3041 SourceLocation ArgLoc); 3042 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, 3043 Expr* DefaultArg); 3044 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 3045 SourceLocation EqualLoc); 3046 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 3047 SourceLocation EqualLoc); 3048 3049 // Contexts where using non-trivial C union types can be disallowed. This is 3050 // passed to err_non_trivial_c_union_in_invalid_context. 3051 enum NonTrivialCUnionContext { 3052 // Function parameter. 3053 NTCUC_FunctionParam, 3054 // Function return. 3055 NTCUC_FunctionReturn, 3056 // Default-initialized object. 3057 NTCUC_DefaultInitializedObject, 3058 // Variable with automatic storage duration. 3059 NTCUC_AutoVar, 3060 // Initializer expression that might copy from another object. 3061 NTCUC_CopyInit, 3062 // Assignment. 3063 NTCUC_Assignment, 3064 // Compound literal. 3065 NTCUC_CompoundLiteral, 3066 // Block capture. 3067 NTCUC_BlockCapture, 3068 // lvalue-to-rvalue conversion of volatile type. 3069 NTCUC_LValueToRValueVolatile, 3070 }; 3071 3072 /// Emit diagnostics if the initializer or any of its explicit or 3073 /// implicitly-generated subexpressions require copying or 3074 /// default-initializing a type that is or contains a C union type that is 3075 /// non-trivial to copy or default-initialize. 3076 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); 3077 3078 // These flags are passed to checkNonTrivialCUnion. 3079 enum NonTrivialCUnionKind { 3080 NTCUK_Init = 0x1, 3081 NTCUK_Destruct = 0x2, 3082 NTCUK_Copy = 0x4, 3083 }; 3084 3085 /// Emit diagnostics if a non-trivial C union type or a struct that contains 3086 /// a non-trivial C union is used in an invalid context. 3087 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 3088 NonTrivialCUnionContext UseContext, 3089 unsigned NonTrivialKind); 3090 3091 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); 3092 void ActOnUninitializedDecl(Decl *dcl); 3093 void ActOnInitializerError(Decl *Dcl); 3094 3095 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); 3096 void ActOnCXXForRangeDecl(Decl *D); 3097 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 3098 IdentifierInfo *Ident, 3099 ParsedAttributes &Attrs); 3100 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 3101 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 3102 void CheckStaticLocalForDllExport(VarDecl *VD); 3103 void CheckThreadLocalForLargeAlignment(VarDecl *VD); 3104 void FinalizeDeclaration(Decl *D); 3105 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 3106 ArrayRef<Decl *> Group); 3107 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); 3108 3109 /// Should be called on all declarations that might have attached 3110 /// documentation comments. 3111 void ActOnDocumentableDecl(Decl *D); 3112 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 3113 3114 enum class FnBodyKind { 3115 /// C++ [dcl.fct.def.general]p1 3116 /// function-body: 3117 /// ctor-initializer[opt] compound-statement 3118 /// function-try-block 3119 Other, 3120 /// = default ; 3121 Default, 3122 /// = delete ; 3123 Delete 3124 }; 3125 3126 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 3127 SourceLocation LocAfterDecls); 3128 void CheckForFunctionRedefinition( 3129 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, 3130 SkipBodyInfo *SkipBody = nullptr); 3131 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, 3132 MultiTemplateParamsArg TemplateParamLists, 3133 SkipBodyInfo *SkipBody = nullptr, 3134 FnBodyKind BodyKind = FnBodyKind::Other); 3135 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, 3136 SkipBodyInfo *SkipBody = nullptr, 3137 FnBodyKind BodyKind = FnBodyKind::Other); 3138 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind); 3139 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); 3140 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); 3141 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); 3142 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); isObjCMethodDecl(Decl * D)3143 bool isObjCMethodDecl(Decl *D) { 3144 return D && isa<ObjCMethodDecl>(D); 3145 } 3146 3147 /// Determine whether we can delay parsing the body of a function or 3148 /// function template until it is used, assuming we don't care about emitting 3149 /// code for that function. 3150 /// 3151 /// This will be \c false if we may need the body of the function in the 3152 /// middle of parsing an expression (where it's impractical to switch to 3153 /// parsing a different function), for instance, if it's constexpr in C++11 3154 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 3155 bool canDelayFunctionBody(const Declarator &D); 3156 3157 /// Determine whether we can skip parsing the body of a function 3158 /// definition, assuming we don't care about analyzing its body or emitting 3159 /// code for that function. 3160 /// 3161 /// This will be \c false only if we may need the body of the function in 3162 /// order to parse the rest of the program (for instance, if it is 3163 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 3164 bool canSkipFunctionBody(Decl *D); 3165 3166 /// Determine whether \param D is function like (function or function 3167 /// template) for parsing. 3168 bool isDeclaratorFunctionLike(Declarator &D); 3169 3170 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 3171 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 3172 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 3173 Decl *ActOnSkippedFunctionBody(Decl *Decl); 3174 void ActOnFinishInlineFunctionDef(FunctionDecl *D); 3175 3176 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 3177 /// attribute for which parsing is delayed. 3178 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 3179 3180 /// Diagnose any unused parameters in the given sequence of 3181 /// ParmVarDecl pointers. 3182 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); 3183 3184 /// Diagnose whether the size of parameters or return value of a 3185 /// function or obj-c method definition is pass-by-value and larger than a 3186 /// specified threshold. 3187 void 3188 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, 3189 QualType ReturnTy, NamedDecl *D); 3190 3191 void DiagnoseInvalidJumps(Stmt *Body); 3192 Decl *ActOnFileScopeAsmDecl(Expr *expr, 3193 SourceLocation AsmLoc, 3194 SourceLocation RParenLoc); 3195 3196 Decl *ActOnTopLevelStmtDecl(Stmt *Statement); 3197 3198 /// Handle a C++11 empty-declaration and attribute-declaration. 3199 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, 3200 SourceLocation SemiLoc); 3201 3202 enum class ModuleDeclKind { 3203 Interface, ///< 'export module X;' 3204 Implementation, ///< 'module X;' 3205 PartitionInterface, ///< 'export module X:Y;' 3206 PartitionImplementation, ///< 'module X:Y;' 3207 }; 3208 3209 /// An enumeration to represent the transition of states in parsing module 3210 /// fragments and imports. If we are not parsing a C++20 TU, or we find 3211 /// an error in state transition, the state is set to NotACXX20Module. 3212 enum class ModuleImportState { 3213 FirstDecl, ///< Parsing the first decl in a TU. 3214 GlobalFragment, ///< after 'module;' but before 'module X;' 3215 ImportAllowed, ///< after 'module X;' but before any non-import decl. 3216 ImportFinished, ///< after any non-import decl. 3217 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any 3218 ///< non-import decl. 3219 PrivateFragmentImportFinished, ///< after 'module :private;' but a 3220 ///< non-import decl has already been seen. 3221 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found. 3222 }; 3223 3224 private: 3225 /// The parser has begun a translation unit to be compiled as a C++20 3226 /// Header Unit, helper for ActOnStartOfTranslationUnit() only. 3227 void HandleStartOfHeaderUnit(); 3228 3229 public: 3230 /// The parser has processed a module-declaration that begins the definition 3231 /// of a module interface or implementation. 3232 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, 3233 SourceLocation ModuleLoc, ModuleDeclKind MDK, 3234 ModuleIdPath Path, ModuleIdPath Partition, 3235 ModuleImportState &ImportState); 3236 3237 /// The parser has processed a global-module-fragment declaration that begins 3238 /// the definition of the global module fragment of the current module unit. 3239 /// \param ModuleLoc The location of the 'module' keyword. 3240 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); 3241 3242 /// The parser has processed a private-module-fragment declaration that begins 3243 /// the definition of the private module fragment of the current module unit. 3244 /// \param ModuleLoc The location of the 'module' keyword. 3245 /// \param PrivateLoc The location of the 'private' keyword. 3246 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, 3247 SourceLocation PrivateLoc); 3248 3249 /// The parser has processed a module import declaration. 3250 /// 3251 /// \param StartLoc The location of the first token in the declaration. This 3252 /// could be the location of an '@', 'export', or 'import'. 3253 /// \param ExportLoc The location of the 'export' keyword, if any. 3254 /// \param ImportLoc The location of the 'import' keyword. 3255 /// \param Path The module toplevel name as an access path. 3256 /// \param IsPartition If the name is for a partition. 3257 DeclResult ActOnModuleImport(SourceLocation StartLoc, 3258 SourceLocation ExportLoc, 3259 SourceLocation ImportLoc, ModuleIdPath Path, 3260 bool IsPartition = false); 3261 DeclResult ActOnModuleImport(SourceLocation StartLoc, 3262 SourceLocation ExportLoc, 3263 SourceLocation ImportLoc, Module *M, 3264 ModuleIdPath Path = {}); 3265 3266 /// The parser has processed a module import translated from a 3267 /// #include or similar preprocessing directive. 3268 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 3269 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 3270 3271 /// The parsed has entered a submodule. 3272 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); 3273 /// The parser has left a submodule. 3274 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); 3275 3276 /// Create an implicit import of the given module at the given 3277 /// source location, for error recovery, if possible. 3278 /// 3279 /// This routine is typically used when an entity found by name lookup 3280 /// is actually hidden within a module that we know about but the user 3281 /// has forgotten to import. 3282 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 3283 Module *Mod); 3284 3285 /// Kinds of missing import. Note, the values of these enumerators correspond 3286 /// to %select values in diagnostics. 3287 enum class MissingImportKind { 3288 Declaration, 3289 Definition, 3290 DefaultArgument, 3291 ExplicitSpecialization, 3292 PartialSpecialization 3293 }; 3294 3295 /// Diagnose that the specified declaration needs to be visible but 3296 /// isn't, and suggest a module import that would resolve the problem. 3297 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, 3298 MissingImportKind MIK, bool Recover = true); 3299 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, 3300 SourceLocation DeclLoc, ArrayRef<Module *> Modules, 3301 MissingImportKind MIK, bool Recover); 3302 3303 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 3304 SourceLocation LBraceLoc); 3305 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, 3306 SourceLocation RBraceLoc); 3307 3308 /// We've found a use of a templated declaration that would trigger an 3309 /// implicit instantiation. Check that any relevant explicit specializations 3310 /// and partial specializations are visible/reachable, and diagnose if not. 3311 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); 3312 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec); 3313 3314 /// Retrieve a suitable printing policy for diagnostics. getPrintingPolicy()3315 PrintingPolicy getPrintingPolicy() const { 3316 return getPrintingPolicy(Context, PP); 3317 } 3318 3319 /// Retrieve a suitable printing policy for diagnostics. 3320 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 3321 const Preprocessor &PP); 3322 3323 /// Scope actions. 3324 void ActOnPopScope(SourceLocation Loc, Scope *S); 3325 void ActOnTranslationUnitScope(Scope *S); 3326 3327 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3328 const ParsedAttributesView &DeclAttrs, 3329 RecordDecl *&AnonRecord); 3330 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3331 const ParsedAttributesView &DeclAttrs, 3332 MultiTemplateParamsArg TemplateParams, 3333 bool IsExplicitInstantiation, 3334 RecordDecl *&AnonRecord); 3335 3336 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3337 AccessSpecifier AS, 3338 RecordDecl *Record, 3339 const PrintingPolicy &Policy); 3340 3341 /// Called once it is known whether 3342 /// a tag declaration is an anonymous union or struct. 3343 void ActOnDefinedDeclarationSpecifier(Decl *D); 3344 3345 void DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record); 3346 3347 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3348 RecordDecl *Record); 3349 3350 /// Common ways to introduce type names without a tag for use in diagnostics. 3351 /// Keep in sync with err_tag_reference_non_tag. 3352 enum NonTagKind { 3353 NTK_NonStruct, 3354 NTK_NonClass, 3355 NTK_NonUnion, 3356 NTK_NonEnum, 3357 NTK_Typedef, 3358 NTK_TypeAlias, 3359 NTK_Template, 3360 NTK_TypeAliasTemplate, 3361 NTK_TemplateTemplateArgument, 3362 }; 3363 3364 /// Given a non-tag type declaration, returns an enum useful for indicating 3365 /// what kind of non-tag type this is. 3366 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); 3367 3368 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 3369 TagTypeKind NewTag, bool isDefinition, 3370 SourceLocation NewTagLoc, 3371 const IdentifierInfo *Name); 3372 3373 enum TagUseKind { 3374 TUK_Reference, // Reference to a tag: 'struct foo *X;' 3375 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 3376 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 3377 TUK_Friend // Friend declaration: 'friend struct foo;' 3378 }; 3379 3380 enum OffsetOfKind { 3381 // Not parsing a type within __builtin_offsetof. 3382 OOK_Outside, 3383 // Parsing a type within __builtin_offsetof. 3384 OOK_Builtin, 3385 // Parsing a type within macro "offsetof", defined in __buitin_offsetof 3386 // To improve our diagnostic message. 3387 OOK_Macro, 3388 }; 3389 3390 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 3391 SourceLocation KWLoc, CXXScopeSpec &SS, 3392 IdentifierInfo *Name, SourceLocation NameLoc, 3393 const ParsedAttributesView &Attr, AccessSpecifier AS, 3394 SourceLocation ModulePrivateLoc, 3395 MultiTemplateParamsArg TemplateParameterLists, 3396 bool &OwnedDecl, bool &IsDependent, 3397 SourceLocation ScopedEnumKWLoc, 3398 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 3399 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 3400 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr); 3401 3402 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 3403 unsigned TagSpec, SourceLocation TagLoc, 3404 CXXScopeSpec &SS, IdentifierInfo *Name, 3405 SourceLocation NameLoc, 3406 const ParsedAttributesView &Attr, 3407 MultiTemplateParamsArg TempParamLists); 3408 3409 TypeResult ActOnDependentTag(Scope *S, 3410 unsigned TagSpec, 3411 TagUseKind TUK, 3412 const CXXScopeSpec &SS, 3413 IdentifierInfo *Name, 3414 SourceLocation TagLoc, 3415 SourceLocation NameLoc); 3416 3417 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 3418 IdentifierInfo *ClassName, 3419 SmallVectorImpl<Decl *> &Decls); 3420 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 3421 Declarator &D, Expr *BitfieldWidth); 3422 3423 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 3424 Declarator &D, Expr *BitfieldWidth, 3425 InClassInitStyle InitStyle, 3426 AccessSpecifier AS); 3427 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 3428 SourceLocation DeclStart, Declarator &D, 3429 Expr *BitfieldWidth, 3430 InClassInitStyle InitStyle, 3431 AccessSpecifier AS, 3432 const ParsedAttr &MSPropertyAttr); 3433 3434 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 3435 TypeSourceInfo *TInfo, 3436 RecordDecl *Record, SourceLocation Loc, 3437 bool Mutable, Expr *BitfieldWidth, 3438 InClassInitStyle InitStyle, 3439 SourceLocation TSSL, 3440 AccessSpecifier AS, NamedDecl *PrevDecl, 3441 Declarator *D = nullptr); 3442 3443 bool CheckNontrivialField(FieldDecl *FD); 3444 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 3445 3446 enum TrivialABIHandling { 3447 /// The triviality of a method unaffected by "trivial_abi". 3448 TAH_IgnoreTrivialABI, 3449 3450 /// The triviality of a method affected by "trivial_abi". 3451 TAH_ConsiderTrivialABI 3452 }; 3453 3454 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 3455 TrivialABIHandling TAH = TAH_IgnoreTrivialABI, 3456 bool Diagnose = false); 3457 3458 /// For a defaulted function, the kind of defaulted function that it is. 3459 class DefaultedFunctionKind { 3460 CXXSpecialMember SpecialMember : 8; 3461 DefaultedComparisonKind Comparison : 8; 3462 3463 public: DefaultedFunctionKind()3464 DefaultedFunctionKind() 3465 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { 3466 } DefaultedFunctionKind(CXXSpecialMember CSM)3467 DefaultedFunctionKind(CXXSpecialMember CSM) 3468 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp)3469 DefaultedFunctionKind(DefaultedComparisonKind Comp) 3470 : SpecialMember(CXXInvalid), Comparison(Comp) {} 3471 isSpecialMember()3472 bool isSpecialMember() const { return SpecialMember != CXXInvalid; } isComparison()3473 bool isComparison() const { 3474 return Comparison != DefaultedComparisonKind::None; 3475 } 3476 3477 explicit operator bool() const { 3478 return isSpecialMember() || isComparison(); 3479 } 3480 asSpecialMember()3481 CXXSpecialMember asSpecialMember() const { return SpecialMember; } asComparison()3482 DefaultedComparisonKind asComparison() const { return Comparison; } 3483 3484 /// Get the index of this function kind for use in diagnostics. getDiagnosticIndex()3485 unsigned getDiagnosticIndex() const { 3486 static_assert(CXXInvalid > CXXDestructor, 3487 "invalid should have highest index"); 3488 static_assert((unsigned)DefaultedComparisonKind::None == 0, 3489 "none should be equal to zero"); 3490 return SpecialMember + (unsigned)Comparison; 3491 } 3492 }; 3493 3494 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); 3495 getSpecialMember(const CXXMethodDecl * MD)3496 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { 3497 return getDefaultedFunctionKind(MD).asSpecialMember(); 3498 } getDefaultedComparisonKind(const FunctionDecl * FD)3499 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { 3500 return getDefaultedFunctionKind(FD).asComparison(); 3501 } 3502 3503 void ActOnLastBitfield(SourceLocation DeclStart, 3504 SmallVectorImpl<Decl *> &AllIvarDecls); 3505 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, 3506 Expr *BitWidth, tok::ObjCKeywordKind visibility); 3507 3508 // This is used for both record definitions and ObjC interface declarations. 3509 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, 3510 ArrayRef<Decl *> Fields, SourceLocation LBrac, 3511 SourceLocation RBrac, const ParsedAttributesView &AttrList); 3512 3513 /// ActOnTagStartDefinition - Invoked when we have entered the 3514 /// scope of a tag's definition (e.g., for an enumeration, class, 3515 /// struct, or union). 3516 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 3517 3518 /// Perform ODR-like check for C/ObjC when merging tag types from modules. 3519 /// Differently from C++, actually parse the body and reject / error out 3520 /// in case of a structural mismatch. 3521 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody); 3522 3523 /// Check ODR hashes for C/ObjC when merging types from modules. 3524 /// Differently from C++, actually parse the body and reject in case 3525 /// of a mismatch. 3526 template <typename T, 3527 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>> ActOnDuplicateODRHashDefinition(T * Duplicate,T * Previous)3528 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) { 3529 if (Duplicate->getODRHash() != Previous->getODRHash()) 3530 return false; 3531 3532 // Make the previous decl visible. 3533 makeMergedDefinitionVisible(Previous); 3534 return true; 3535 } 3536 3537 typedef void *SkippedDefinitionContext; 3538 3539 /// Invoked when we enter a tag definition that we're skipping. 3540 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); 3541 3542 void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl); 3543 3544 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 3545 /// C++ record definition's base-specifiers clause and are starting its 3546 /// member declarations. 3547 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 3548 SourceLocation FinalLoc, 3549 bool IsFinalSpelledSealed, 3550 bool IsAbstract, 3551 SourceLocation LBraceLoc); 3552 3553 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 3554 /// the definition of a tag (enumeration, class, struct, or union). 3555 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 3556 SourceRange BraceRange); 3557 3558 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); 3559 3560 void ActOnObjCContainerFinishDefinition(); 3561 3562 /// Invoked when we must temporarily exit the objective-c container 3563 /// scope for parsing/looking-up C constructs. 3564 /// 3565 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 3566 void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx); 3567 void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx); 3568 3569 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 3570 /// error parsing the definition of a tag. 3571 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 3572 3573 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 3574 EnumConstantDecl *LastEnumConst, 3575 SourceLocation IdLoc, 3576 IdentifierInfo *Id, 3577 Expr *val); 3578 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 3579 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 3580 QualType EnumUnderlyingTy, bool IsFixed, 3581 const EnumDecl *Prev); 3582 3583 /// Determine whether the body of an anonymous enumeration should be skipped. 3584 /// \param II The name of the first enumerator. 3585 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 3586 SourceLocation IILoc); 3587 3588 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 3589 SourceLocation IdLoc, IdentifierInfo *Id, 3590 const ParsedAttributesView &Attrs, 3591 SourceLocation EqualLoc, Expr *Val); 3592 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 3593 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, 3594 const ParsedAttributesView &Attr); 3595 3596 /// Set the current declaration context until it gets popped. 3597 void PushDeclContext(Scope *S, DeclContext *DC); 3598 void PopDeclContext(); 3599 3600 /// EnterDeclaratorContext - Used when we must lookup names in the context 3601 /// of a declarator's nested name specifier. 3602 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 3603 void ExitDeclaratorContext(Scope *S); 3604 3605 /// Enter a template parameter scope, after it's been associated with a particular 3606 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts 3607 /// in the correct order. 3608 void EnterTemplatedContext(Scope *S, DeclContext *DC); 3609 3610 /// Push the parameters of D, which must be a function, into scope. 3611 void ActOnReenterFunctionContext(Scope* S, Decl* D); 3612 void ActOnExitFunctionContext(); 3613 3614 /// If \p AllowLambda is true, treat lambda as function. 3615 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const; 3616 3617 /// Returns a pointer to the innermost enclosing function, or nullptr if the 3618 /// current context is not inside a function. If \p AllowLambda is true, 3619 /// this can return the call operator of an enclosing lambda, otherwise 3620 /// lambdas are skipped when looking for an enclosing function. 3621 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const; 3622 3623 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 3624 /// the method decl for the method being parsed. If we're currently 3625 /// in a 'block', this returns the containing context. 3626 ObjCMethodDecl *getCurMethodDecl(); 3627 3628 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 3629 /// or C function we're in, otherwise return null. If we're currently 3630 /// in a 'block', this returns the containing context. 3631 NamedDecl *getCurFunctionOrMethodDecl() const; 3632 3633 /// Add this decl to the scope shadowed decl chains. 3634 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 3635 3636 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 3637 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 3638 /// true if 'D' belongs to the given declaration context. 3639 /// 3640 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 3641 /// enclosing namespace set of the context, rather than contained 3642 /// directly within it. 3643 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 3644 bool AllowInlineNamespace = false) const; 3645 3646 /// Finds the scope corresponding to the given decl context, if it 3647 /// happens to be an enclosing scope. Otherwise return NULL. 3648 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 3649 3650 /// Subroutines of ActOnDeclarator(). 3651 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 3652 TypeSourceInfo *TInfo); 3653 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 3654 3655 /// Describes the kind of merge to perform for availability 3656 /// attributes (including "deprecated", "unavailable", and "availability"). 3657 enum AvailabilityMergeKind { 3658 /// Don't merge availability attributes at all. 3659 AMK_None, 3660 /// Merge availability attributes for a redeclaration, which requires 3661 /// an exact match. 3662 AMK_Redeclaration, 3663 /// Merge availability attributes for an override, which requires 3664 /// an exact match or a weakening of constraints. 3665 AMK_Override, 3666 /// Merge availability attributes for an implementation of 3667 /// a protocol requirement. 3668 AMK_ProtocolImplementation, 3669 /// Merge availability attributes for an implementation of 3670 /// an optional protocol requirement. 3671 AMK_OptionalProtocolImplementation 3672 }; 3673 3674 /// Describes the kind of priority given to an availability attribute. 3675 /// 3676 /// The sum of priorities deteremines the final priority of the attribute. 3677 /// The final priority determines how the attribute will be merged. 3678 /// An attribute with a lower priority will always remove higher priority 3679 /// attributes for the specified platform when it is being applied. An 3680 /// attribute with a higher priority will not be applied if the declaration 3681 /// already has an availability attribute with a lower priority for the 3682 /// specified platform. The final prirority values are not expected to match 3683 /// the values in this enumeration, but instead should be treated as a plain 3684 /// integer value. This enumeration just names the priority weights that are 3685 /// used to calculate that final vaue. 3686 enum AvailabilityPriority : int { 3687 /// The availability attribute was specified explicitly next to the 3688 /// declaration. 3689 AP_Explicit = 0, 3690 3691 /// The availability attribute was applied using '#pragma clang attribute'. 3692 AP_PragmaClangAttribute = 1, 3693 3694 /// The availability attribute for a specific platform was inferred from 3695 /// an availability attribute for another platform. 3696 AP_InferredFromOtherPlatform = 2 3697 }; 3698 3699 /// Attribute merging methods. Return true if a new attribute was added. 3700 AvailabilityAttr * 3701 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, 3702 IdentifierInfo *Platform, bool Implicit, 3703 VersionTuple Introduced, VersionTuple Deprecated, 3704 VersionTuple Obsoleted, bool IsUnavailable, 3705 StringRef Message, bool IsStrict, StringRef Replacement, 3706 AvailabilityMergeKind AMK, int Priority); 3707 TypeVisibilityAttr * 3708 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3709 TypeVisibilityAttr::VisibilityType Vis); 3710 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3711 VisibilityAttr::VisibilityType Vis); 3712 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 3713 StringRef UuidAsWritten, MSGuidDecl *GuidDecl); 3714 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); 3715 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); 3716 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, 3717 const AttributeCommonInfo &CI, 3718 bool BestCase, 3719 MSInheritanceModel Model); 3720 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, 3721 StringRef NewUserDiagnostic); 3722 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3723 IdentifierInfo *Format, int FormatIdx, 3724 int FirstArg); 3725 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3726 StringRef Name); 3727 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3728 StringRef Name); 3729 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, 3730 const AttributeCommonInfo &CI, 3731 const IdentifierInfo *Ident); 3732 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); 3733 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, 3734 StringRef Name); 3735 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, 3736 const AttributeCommonInfo &CI); 3737 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); 3738 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, 3739 const InternalLinkageAttr &AL); 3740 WebAssemblyImportNameAttr *mergeImportNameAttr( 3741 Decl *D, const WebAssemblyImportNameAttr &AL); 3742 WebAssemblyImportModuleAttr *mergeImportModuleAttr( 3743 Decl *D, const WebAssemblyImportModuleAttr &AL); 3744 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); 3745 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, 3746 const EnforceTCBLeafAttr &AL); 3747 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL); 3748 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D, 3749 const AttributeCommonInfo &AL, 3750 int X, int Y, int Z); 3751 HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL, 3752 HLSLShaderAttr::ShaderType ShaderType); 3753 HLSLParamModifierAttr * 3754 mergeHLSLParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, 3755 HLSLParamModifierAttr::Spelling Spelling); 3756 3757 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 3758 AvailabilityMergeKind AMK = AMK_Redeclaration); 3759 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 3760 LookupResult &OldDecls); 3761 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 3762 bool MergeTypeWithOld, bool NewDeclIsDefn); 3763 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3764 Scope *S, bool MergeTypeWithOld); 3765 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 3766 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 3767 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 3768 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 3769 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); 3770 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); 3771 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 3772 3773 // AssignmentAction - This is used by all the assignment diagnostic functions 3774 // to represent what is actually causing the operation 3775 enum AssignmentAction { 3776 AA_Assigning, 3777 AA_Passing, 3778 AA_Returning, 3779 AA_Converting, 3780 AA_Initializing, 3781 AA_Sending, 3782 AA_Casting, 3783 AA_Passing_CFAudited 3784 }; 3785 3786 /// C++ Overloading. 3787 enum OverloadKind { 3788 /// This is a legitimate overload: the existing declarations are 3789 /// functions or function templates with different signatures. 3790 Ovl_Overload, 3791 3792 /// This is not an overload because the signature exactly matches 3793 /// an existing declaration. 3794 Ovl_Match, 3795 3796 /// This is not an overload because the lookup results contain a 3797 /// non-function. 3798 Ovl_NonFunction 3799 }; 3800 OverloadKind CheckOverload(Scope *S, 3801 FunctionDecl *New, 3802 const LookupResult &OldDecls, 3803 NamedDecl *&OldDecl, 3804 bool UseMemberUsingDeclRules); 3805 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, 3806 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true); 3807 3808 // Checks whether MD constitutes an override the base class method BaseMD. 3809 // When checking for overrides, the object object members are ignored. 3810 bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, 3811 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true); 3812 3813 // Calculates whether the expression Constraint depends on an enclosing 3814 // template, for the purposes of [temp.friend] p9. 3815 // TemplateDepth is the 'depth' of the friend function, which is used to 3816 // compare whether a declaration reference is referring to a containing 3817 // template, or just the current friend function. A 'lower' TemplateDepth in 3818 // the AST refers to a 'containing' template. As the constraint is 3819 // uninstantiated, this is relative to the 'top' of the TU. 3820 bool 3821 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, 3822 unsigned TemplateDepth, 3823 const Expr *Constraint); 3824 3825 // Calculates whether the friend function depends on an enclosing template for 3826 // the purposes of [temp.friend] p9. 3827 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD); 3828 3829 enum class AllowedExplicit { 3830 /// Allow no explicit functions to be used. 3831 None, 3832 /// Allow explicit conversion functions but not explicit constructors. 3833 Conversions, 3834 /// Allow both explicit conversion functions and explicit constructors. 3835 All 3836 }; 3837 3838 ImplicitConversionSequence 3839 TryImplicitConversion(Expr *From, QualType ToType, 3840 bool SuppressUserConversions, 3841 AllowedExplicit AllowExplicit, 3842 bool InOverloadResolution, 3843 bool CStyle, 3844 bool AllowObjCWritebackConversion); 3845 3846 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 3847 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 3848 bool IsComplexPromotion(QualType FromType, QualType ToType); 3849 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 3850 bool InOverloadResolution, 3851 QualType& ConvertedType, bool &IncompatibleObjC); 3852 bool isObjCPointerConversion(QualType FromType, QualType ToType, 3853 QualType& ConvertedType, bool &IncompatibleObjC); 3854 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 3855 QualType &ConvertedType); 3856 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 3857 QualType& ConvertedType); 3858 3859 bool FunctionParamTypesAreEqual(ArrayRef<QualType> Old, 3860 ArrayRef<QualType> New, 3861 unsigned *ArgPos = nullptr, 3862 bool Reversed = false); 3863 3864 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3865 const FunctionProtoType *NewType, 3866 unsigned *ArgPos = nullptr, 3867 bool Reversed = false); 3868 3869 bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, 3870 const FunctionDecl *NewFunction, 3871 unsigned *ArgPos = nullptr, 3872 bool Reversed = false); 3873 3874 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3875 QualType FromType, QualType ToType); 3876 3877 void maybeExtendBlockObject(ExprResult &E); 3878 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 3879 bool CheckPointerConversion(Expr *From, QualType ToType, 3880 CastKind &Kind, 3881 CXXCastPath& BasePath, 3882 bool IgnoreBaseAccess, 3883 bool Diagnose = true); 3884 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 3885 bool InOverloadResolution, 3886 QualType &ConvertedType); 3887 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 3888 CastKind &Kind, 3889 CXXCastPath &BasePath, 3890 bool IgnoreBaseAccess); 3891 bool IsQualificationConversion(QualType FromType, QualType ToType, 3892 bool CStyle, bool &ObjCLifetimeConversion); 3893 bool IsFunctionConversion(QualType FromType, QualType ToType, 3894 QualType &ResultTy); 3895 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 3896 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg); 3897 3898 bool CanPerformAggregateInitializationForOverloadResolution( 3899 const InitializedEntity &Entity, InitListExpr *From); 3900 3901 bool IsStringInit(Expr *Init, const ArrayType *AT); 3902 3903 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 3904 ExprResult Init); 3905 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 3906 SourceLocation EqualLoc, 3907 ExprResult Init, 3908 bool TopLevelOfInitList = false, 3909 bool AllowExplicit = false); 3910 ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, 3911 FunctionDecl *Fun); 3912 ExprResult PerformImplicitObjectArgumentInitialization( 3913 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, 3914 CXXMethodDecl *Method); 3915 3916 /// Check that the lifetime of the initializer (and its subobjects) is 3917 /// sufficient for initializing the entity, and perform lifetime extension 3918 /// (when permitted) if not. 3919 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); 3920 3921 ExprResult PerformContextuallyConvertToBool(Expr *From); 3922 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 3923 3924 /// Contexts in which a converted constant expression is required. 3925 enum CCEKind { 3926 CCEK_CaseValue, ///< Expression in a case label. 3927 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 3928 CCEK_TemplateArg, ///< Value of a non-type template parameter. 3929 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. 3930 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier. 3931 CCEK_Noexcept, ///< Condition in a noexcept(bool) specifier. 3932 CCEK_StaticAssertMessageSize, ///< Call to size() in a static assert 3933 ///< message. 3934 CCEK_StaticAssertMessageData, ///< Call to data() in a static assert 3935 ///< message. 3936 }; 3937 3938 ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, 3939 CCEKind CCE, 3940 NamedDecl *Dest = nullptr); 3941 3942 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3943 llvm::APSInt &Value, CCEKind CCE); 3944 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3945 APValue &Value, CCEKind CCE, 3946 NamedDecl *Dest = nullptr); 3947 3948 ExprResult 3949 EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, 3950 CCEKind CCE, bool RequireInt, 3951 const APValue &PreNarrowingValue); 3952 3953 /// Abstract base class used to perform a contextual implicit 3954 /// conversion from an expression to any type passing a filter. 3955 class ContextualImplicitConverter { 3956 public: 3957 bool Suppress; 3958 bool SuppressConversion; 3959 3960 ContextualImplicitConverter(bool Suppress = false, 3961 bool SuppressConversion = false) Suppress(Suppress)3962 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 3963 3964 /// Determine whether the specified type is a valid destination type 3965 /// for this conversion. 3966 virtual bool match(QualType T) = 0; 3967 3968 /// Emits a diagnostic complaining that the expression does not have 3969 /// integral or enumeration type. 3970 virtual SemaDiagnosticBuilder 3971 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 3972 3973 /// Emits a diagnostic when the expression has incomplete class type. 3974 virtual SemaDiagnosticBuilder 3975 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 3976 3977 /// Emits a diagnostic when the only matching conversion function 3978 /// is explicit. 3979 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 3980 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3981 3982 /// Emits a note for the explicit conversion function. 3983 virtual SemaDiagnosticBuilder 3984 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3985 3986 /// Emits a diagnostic when there are multiple possible conversion 3987 /// functions. 3988 virtual SemaDiagnosticBuilder 3989 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 3990 3991 /// Emits a note for one of the candidate conversions. 3992 virtual SemaDiagnosticBuilder 3993 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3994 3995 /// Emits a diagnostic when we picked a conversion function 3996 /// (for cases when we are not allowed to pick a conversion function). 3997 virtual SemaDiagnosticBuilder diagnoseConversion( 3998 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3999 ~ContextualImplicitConverter()4000 virtual ~ContextualImplicitConverter() {} 4001 }; 4002 4003 class ICEConvertDiagnoser : public ContextualImplicitConverter { 4004 bool AllowScopedEnumerations; 4005 4006 public: ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)4007 ICEConvertDiagnoser(bool AllowScopedEnumerations, 4008 bool Suppress, bool SuppressConversion) 4009 : ContextualImplicitConverter(Suppress, SuppressConversion), 4010 AllowScopedEnumerations(AllowScopedEnumerations) {} 4011 4012 /// Match an integral or (possibly scoped) enumeration type. 4013 bool match(QualType T) override; 4014 4015 SemaDiagnosticBuilder diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)4016 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { 4017 return diagnoseNotInt(S, Loc, T); 4018 } 4019 4020 /// Emits a diagnostic complaining that the expression does not have 4021 /// integral or enumeration type. 4022 virtual SemaDiagnosticBuilder 4023 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 4024 }; 4025 4026 /// Perform a contextual implicit conversion. 4027 ExprResult PerformContextualImplicitConversion( 4028 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 4029 4030 4031 enum ObjCSubscriptKind { 4032 OS_Array, 4033 OS_Dictionary, 4034 OS_Error 4035 }; 4036 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 4037 4038 // Note that LK_String is intentionally after the other literals, as 4039 // this is used for diagnostics logic. 4040 enum ObjCLiteralKind { 4041 LK_Array, 4042 LK_Dictionary, 4043 LK_Numeric, 4044 LK_Boxed, 4045 LK_String, 4046 LK_Block, 4047 LK_None 4048 }; 4049 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 4050 4051 ExprResult PerformObjectMemberConversion(Expr *From, 4052 NestedNameSpecifier *Qualifier, 4053 NamedDecl *FoundDecl, 4054 NamedDecl *Member); 4055 4056 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 4057 // TODO: make this is a typesafe union. 4058 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; 4059 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; 4060 4061 using ADLCallKind = CallExpr::ADLCallKind; 4062 4063 void AddOverloadCandidate( 4064 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 4065 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 4066 bool PartialOverloading = false, bool AllowExplicit = true, 4067 bool AllowExplicitConversion = false, 4068 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 4069 ConversionSequenceList EarlyConversions = std::nullopt, 4070 OverloadCandidateParamOrder PO = {}, 4071 bool AggregateCandidateDeduction = false); 4072 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 4073 ArrayRef<Expr *> Args, 4074 OverloadCandidateSet &CandidateSet, 4075 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 4076 bool SuppressUserConversions = false, 4077 bool PartialOverloading = false, 4078 bool FirstArgumentIsBase = false); 4079 void AddMethodCandidate(DeclAccessPair FoundDecl, 4080 QualType ObjectType, 4081 Expr::Classification ObjectClassification, 4082 ArrayRef<Expr *> Args, 4083 OverloadCandidateSet& CandidateSet, 4084 bool SuppressUserConversion = false, 4085 OverloadCandidateParamOrder PO = {}); 4086 void 4087 AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 4088 CXXRecordDecl *ActingContext, QualType ObjectType, 4089 Expr::Classification ObjectClassification, 4090 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 4091 bool SuppressUserConversions = false, 4092 bool PartialOverloading = false, 4093 ConversionSequenceList EarlyConversions = std::nullopt, 4094 OverloadCandidateParamOrder PO = {}); 4095 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 4096 DeclAccessPair FoundDecl, 4097 CXXRecordDecl *ActingContext, 4098 TemplateArgumentListInfo *ExplicitTemplateArgs, 4099 QualType ObjectType, 4100 Expr::Classification ObjectClassification, 4101 ArrayRef<Expr *> Args, 4102 OverloadCandidateSet& CandidateSet, 4103 bool SuppressUserConversions = false, 4104 bool PartialOverloading = false, 4105 OverloadCandidateParamOrder PO = {}); 4106 void AddTemplateOverloadCandidate( 4107 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 4108 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 4109 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 4110 bool PartialOverloading = false, bool AllowExplicit = true, 4111 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 4112 OverloadCandidateParamOrder PO = {}, 4113 bool AggregateCandidateDeduction = false); 4114 bool CheckNonDependentConversions( 4115 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 4116 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 4117 ConversionSequenceList &Conversions, bool SuppressUserConversions, 4118 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), 4119 Expr::Classification ObjectClassification = {}, 4120 OverloadCandidateParamOrder PO = {}); 4121 void AddConversionCandidate( 4122 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 4123 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 4124 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 4125 bool AllowExplicit, bool AllowResultConversion = true); 4126 void AddTemplateConversionCandidate( 4127 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 4128 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 4129 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 4130 bool AllowExplicit, bool AllowResultConversion = true); 4131 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 4132 DeclAccessPair FoundDecl, 4133 CXXRecordDecl *ActingContext, 4134 const FunctionProtoType *Proto, 4135 Expr *Object, ArrayRef<Expr *> Args, 4136 OverloadCandidateSet& CandidateSet); 4137 void AddNonMemberOperatorCandidates( 4138 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, 4139 OverloadCandidateSet &CandidateSet, 4140 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 4141 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 4142 SourceLocation OpLoc, ArrayRef<Expr *> Args, 4143 OverloadCandidateSet &CandidateSet, 4144 OverloadCandidateParamOrder PO = {}); 4145 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 4146 OverloadCandidateSet& CandidateSet, 4147 bool IsAssignmentOperator = false, 4148 unsigned NumContextualBoolArguments = 0); 4149 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 4150 SourceLocation OpLoc, ArrayRef<Expr *> Args, 4151 OverloadCandidateSet& CandidateSet); 4152 void AddArgumentDependentLookupCandidates(DeclarationName Name, 4153 SourceLocation Loc, 4154 ArrayRef<Expr *> Args, 4155 TemplateArgumentListInfo *ExplicitTemplateArgs, 4156 OverloadCandidateSet& CandidateSet, 4157 bool PartialOverloading = false); 4158 4159 // Emit as a 'note' the specific overload candidate 4160 void NoteOverloadCandidate( 4161 const NamedDecl *Found, const FunctionDecl *Fn, 4162 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), 4163 QualType DestType = QualType(), bool TakingAddress = false); 4164 4165 // Emit as a series of 'note's all template and non-templates identified by 4166 // the expression Expr 4167 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), 4168 bool TakingAddress = false); 4169 4170 /// Check the enable_if expressions on the given function. Returns the first 4171 /// failing attribute, or NULL if they were all successful. 4172 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, 4173 ArrayRef<Expr *> Args, 4174 bool MissingImplicitThis = false); 4175 4176 /// Find the failed Boolean condition within a given Boolean 4177 /// constant expression, and describe it with a string. 4178 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); 4179 4180 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 4181 /// non-ArgDependent DiagnoseIfAttrs. 4182 /// 4183 /// Argument-dependent diagnose_if attributes should be checked each time a 4184 /// function is used as a direct callee of a function call. 4185 /// 4186 /// Returns true if any errors were emitted. 4187 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 4188 const Expr *ThisArg, 4189 ArrayRef<const Expr *> Args, 4190 SourceLocation Loc); 4191 4192 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 4193 /// ArgDependent DiagnoseIfAttrs. 4194 /// 4195 /// Argument-independent diagnose_if attributes should be checked on every use 4196 /// of a function. 4197 /// 4198 /// Returns true if any errors were emitted. 4199 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 4200 SourceLocation Loc); 4201 4202 /// Returns whether the given function's address can be taken or not, 4203 /// optionally emitting a diagnostic if the address can't be taken. 4204 /// 4205 /// Returns false if taking the address of the function is illegal. 4206 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 4207 bool Complain = false, 4208 SourceLocation Loc = SourceLocation()); 4209 4210 // [PossiblyAFunctionType] --> [Return] 4211 // NonFunctionType --> NonFunctionType 4212 // R (A) --> R(A) 4213 // R (*)(A) --> R (A) 4214 // R (&)(A) --> R (A) 4215 // R (S::*)(A) --> R (A) 4216 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 4217 4218 FunctionDecl * 4219 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 4220 QualType TargetType, 4221 bool Complain, 4222 DeclAccessPair &Found, 4223 bool *pHadMultipleCandidates = nullptr); 4224 4225 FunctionDecl * 4226 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); 4227 4228 bool resolveAndFixAddressOfSingleOverloadCandidate( 4229 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); 4230 4231 FunctionDecl *ResolveSingleFunctionTemplateSpecialization( 4232 OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr, 4233 TemplateSpecCandidateSet *FailedTSC = nullptr); 4234 4235 bool ResolveAndFixSingleFunctionTemplateSpecialization( 4236 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false, 4237 bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), 4238 QualType DestTypeForComplaining = QualType(), 4239 unsigned DiagIDForComplaining = 0); 4240 4241 ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, 4242 FunctionDecl *Fn); 4243 ExprResult FixOverloadedFunctionReference(ExprResult, 4244 DeclAccessPair FoundDecl, 4245 FunctionDecl *Fn); 4246 4247 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 4248 ArrayRef<Expr *> Args, 4249 OverloadCandidateSet &CandidateSet, 4250 bool PartialOverloading = false); 4251 void AddOverloadedCallCandidates( 4252 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 4253 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); 4254 4255 // An enum used to represent the different possible results of building a 4256 // range-based for loop. 4257 enum ForRangeStatus { 4258 FRS_Success, 4259 FRS_NoViableFunction, 4260 FRS_DiagnosticIssued 4261 }; 4262 4263 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, 4264 SourceLocation RangeLoc, 4265 const DeclarationNameInfo &NameInfo, 4266 LookupResult &MemberLookup, 4267 OverloadCandidateSet *CandidateSet, 4268 Expr *Range, ExprResult *CallExpr); 4269 4270 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 4271 UnresolvedLookupExpr *ULE, 4272 SourceLocation LParenLoc, 4273 MultiExprArg Args, 4274 SourceLocation RParenLoc, 4275 Expr *ExecConfig, 4276 bool AllowTypoCorrection=true, 4277 bool CalleesAddressIsTaken=false); 4278 4279 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 4280 MultiExprArg Args, SourceLocation RParenLoc, 4281 OverloadCandidateSet *CandidateSet, 4282 ExprResult *Result); 4283 4284 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 4285 NestedNameSpecifierLoc NNSLoc, 4286 DeclarationNameInfo DNI, 4287 const UnresolvedSetImpl &Fns, 4288 bool PerformADL = true); 4289 4290 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 4291 UnaryOperatorKind Opc, 4292 const UnresolvedSetImpl &Fns, 4293 Expr *input, bool RequiresADL = true); 4294 4295 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 4296 OverloadedOperatorKind Op, 4297 const UnresolvedSetImpl &Fns, 4298 ArrayRef<Expr *> Args, bool RequiresADL = true); 4299 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 4300 BinaryOperatorKind Opc, 4301 const UnresolvedSetImpl &Fns, 4302 Expr *LHS, Expr *RHS, 4303 bool RequiresADL = true, 4304 bool AllowRewrittenCandidates = true, 4305 FunctionDecl *DefaultedFn = nullptr); 4306 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, 4307 const UnresolvedSetImpl &Fns, 4308 Expr *LHS, Expr *RHS, 4309 FunctionDecl *DefaultedFn); 4310 4311 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 4312 SourceLocation RLoc, Expr *Base, 4313 MultiExprArg Args); 4314 4315 ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 4316 SourceLocation LParenLoc, 4317 MultiExprArg Args, 4318 SourceLocation RParenLoc, 4319 Expr *ExecConfig = nullptr, 4320 bool IsExecConfig = false, 4321 bool AllowRecovery = false); 4322 ExprResult 4323 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 4324 MultiExprArg Args, 4325 SourceLocation RParenLoc); 4326 4327 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 4328 SourceLocation OpLoc, 4329 bool *NoArrowOperatorFound = nullptr); 4330 4331 /// CheckCallReturnType - Checks that a call expression's return type is 4332 /// complete. Returns true on failure. The location passed in is the location 4333 /// that best represents the call. 4334 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 4335 CallExpr *CE, FunctionDecl *FD); 4336 4337 /// Helpers for dealing with blocks and functions. 4338 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 4339 bool CheckParameterNames); 4340 void CheckCXXDefaultArguments(FunctionDecl *FD); 4341 void CheckExtraCXXDefaultArguments(Declarator &D); 4342 Scope *getNonFieldDeclScope(Scope *S); 4343 4344 /// \name Name lookup 4345 /// 4346 /// These routines provide name lookup that is used during semantic 4347 /// analysis to resolve the various kinds of names (identifiers, 4348 /// overloaded operator names, constructor names, etc.) into zero or 4349 /// more declarations within a particular scope. The major entry 4350 /// points are LookupName, which performs unqualified name lookup, 4351 /// and LookupQualifiedName, which performs qualified name lookup. 4352 /// 4353 /// All name lookup is performed based on some specific criteria, 4354 /// which specify what names will be visible to name lookup and how 4355 /// far name lookup should work. These criteria are important both 4356 /// for capturing language semantics (certain lookups will ignore 4357 /// certain names, for example) and for performance, since name 4358 /// lookup is often a bottleneck in the compilation of C++. Name 4359 /// lookup criteria is specified via the LookupCriteria enumeration. 4360 /// 4361 /// The results of name lookup can vary based on the kind of name 4362 /// lookup performed, the current language, and the translation 4363 /// unit. In C, for example, name lookup will either return nothing 4364 /// (no entity found) or a single declaration. In C++, name lookup 4365 /// can additionally refer to a set of overloaded functions or 4366 /// result in an ambiguity. All of the possible results of name 4367 /// lookup are captured by the LookupResult class, which provides 4368 /// the ability to distinguish among them. 4369 //@{ 4370 4371 /// Describes the kind of name lookup to perform. 4372 enum LookupNameKind { 4373 /// Ordinary name lookup, which finds ordinary names (functions, 4374 /// variables, typedefs, etc.) in C and most kinds of names 4375 /// (functions, variables, members, types, etc.) in C++. 4376 LookupOrdinaryName = 0, 4377 /// Tag name lookup, which finds the names of enums, classes, 4378 /// structs, and unions. 4379 LookupTagName, 4380 /// Label name lookup. 4381 LookupLabel, 4382 /// Member name lookup, which finds the names of 4383 /// class/struct/union members. 4384 LookupMemberName, 4385 /// Look up of an operator name (e.g., operator+) for use with 4386 /// operator overloading. This lookup is similar to ordinary name 4387 /// lookup, but will ignore any declarations that are class members. 4388 LookupOperatorName, 4389 /// Look up a name following ~ in a destructor name. This is an ordinary 4390 /// lookup, but prefers tags to typedefs. 4391 LookupDestructorName, 4392 /// Look up of a name that precedes the '::' scope resolution 4393 /// operator in C++. This lookup completely ignores operator, object, 4394 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 4395 LookupNestedNameSpecifierName, 4396 /// Look up a namespace name within a C++ using directive or 4397 /// namespace alias definition, ignoring non-namespace names (C++ 4398 /// [basic.lookup.udir]p1). 4399 LookupNamespaceName, 4400 /// Look up all declarations in a scope with the given name, 4401 /// including resolved using declarations. This is appropriate 4402 /// for checking redeclarations for a using declaration. 4403 LookupUsingDeclName, 4404 /// Look up an ordinary name that is going to be redeclared as a 4405 /// name with linkage. This lookup ignores any declarations that 4406 /// are outside of the current scope unless they have linkage. See 4407 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 4408 LookupRedeclarationWithLinkage, 4409 /// Look up a friend of a local class. This lookup does not look 4410 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 4411 LookupLocalFriendName, 4412 /// Look up the name of an Objective-C protocol. 4413 LookupObjCProtocolName, 4414 /// Look up implicit 'self' parameter of an objective-c method. 4415 LookupObjCImplicitSelfParam, 4416 /// Look up the name of an OpenMP user-defined reduction operation. 4417 LookupOMPReductionName, 4418 /// Look up the name of an OpenMP user-defined mapper. 4419 LookupOMPMapperName, 4420 /// Look up any declaration with any name. 4421 LookupAnyName 4422 }; 4423 4424 /// Specifies whether (or how) name lookup is being performed for a 4425 /// redeclaration (vs. a reference). 4426 enum RedeclarationKind { 4427 /// The lookup is a reference to this name that is not for the 4428 /// purpose of redeclaring the name. 4429 NotForRedeclaration = 0, 4430 /// The lookup results will be used for redeclaration of a name, 4431 /// if an entity by that name already exists and is visible. 4432 ForVisibleRedeclaration, 4433 /// The lookup results will be used for redeclaration of a name 4434 /// with external linkage; non-visible lookup results with external linkage 4435 /// may also be found. 4436 ForExternalRedeclaration 4437 }; 4438 forRedeclarationInCurContext()4439 RedeclarationKind forRedeclarationInCurContext() const { 4440 // A declaration with an owning module for linkage can never link against 4441 // anything that is not visible. We don't need to check linkage here; if 4442 // the context has internal linkage, redeclaration lookup won't find things 4443 // from other TUs, and we can't safely compute linkage yet in general. 4444 if (cast<Decl>(CurContext) 4445 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) 4446 return ForVisibleRedeclaration; 4447 return ForExternalRedeclaration; 4448 } 4449 4450 /// The possible outcomes of name lookup for a literal operator. 4451 enum LiteralOperatorLookupResult { 4452 /// The lookup resulted in an error. 4453 LOLR_Error, 4454 /// The lookup found no match but no diagnostic was issued. 4455 LOLR_ErrorNoDiagnostic, 4456 /// The lookup found a single 'cooked' literal operator, which 4457 /// expects a normal literal to be built and passed to it. 4458 LOLR_Cooked, 4459 /// The lookup found a single 'raw' literal operator, which expects 4460 /// a string literal containing the spelling of the literal token. 4461 LOLR_Raw, 4462 /// The lookup found an overload set of literal operator templates, 4463 /// which expect the characters of the spelling of the literal token to be 4464 /// passed as a non-type template argument pack. 4465 LOLR_Template, 4466 /// The lookup found an overload set of literal operator templates, 4467 /// which expect the character type and characters of the spelling of the 4468 /// string literal token to be passed as template arguments. 4469 LOLR_StringTemplatePack, 4470 }; 4471 4472 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, 4473 CXXSpecialMember SM, 4474 bool ConstArg, 4475 bool VolatileArg, 4476 bool RValueThis, 4477 bool ConstThis, 4478 bool VolatileThis); 4479 4480 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 4481 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 4482 TypoRecoveryCallback; 4483 4484 private: 4485 bool CppLookupName(LookupResult &R, Scope *S); 4486 4487 struct TypoExprState { 4488 std::unique_ptr<TypoCorrectionConsumer> Consumer; 4489 TypoDiagnosticGenerator DiagHandler; 4490 TypoRecoveryCallback RecoveryHandler; 4491 TypoExprState(); 4492 TypoExprState(TypoExprState &&other) noexcept; 4493 TypoExprState &operator=(TypoExprState &&other) noexcept; 4494 }; 4495 4496 /// The set of unhandled TypoExprs and their associated state. 4497 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 4498 4499 /// Creates a new TypoExpr AST node. 4500 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 4501 TypoDiagnosticGenerator TDG, 4502 TypoRecoveryCallback TRC, SourceLocation TypoLoc); 4503 4504 // The set of known/encountered (unique, canonicalized) NamespaceDecls. 4505 // 4506 // The boolean value will be true to indicate that the namespace was loaded 4507 // from an AST/PCH file, or false otherwise. 4508 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 4509 4510 /// Whether we have already loaded known namespaces from an extenal 4511 /// source. 4512 bool LoadedExternalKnownNamespaces; 4513 4514 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and 4515 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 4516 /// should be skipped entirely. 4517 std::unique_ptr<TypoCorrectionConsumer> 4518 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, 4519 Sema::LookupNameKind LookupKind, Scope *S, 4520 CXXScopeSpec *SS, 4521 CorrectionCandidateCallback &CCC, 4522 DeclContext *MemberContext, bool EnteringContext, 4523 const ObjCObjectPointerType *OPT, 4524 bool ErrorRecovery); 4525 4526 public: 4527 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 4528 4529 /// Clears the state of the given TypoExpr. 4530 void clearDelayedTypo(TypoExpr *TE); 4531 4532 /// Look up a name, looking for a single declaration. Return 4533 /// null if the results were absent, ambiguous, or overloaded. 4534 /// 4535 /// It is preferable to use the elaborated form and explicitly handle 4536 /// ambiguity and overloaded. 4537 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 4538 SourceLocation Loc, 4539 LookupNameKind NameKind, 4540 RedeclarationKind Redecl 4541 = NotForRedeclaration); 4542 bool LookupBuiltin(LookupResult &R); 4543 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); 4544 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false, 4545 bool ForceNoCPlusPlus = false); 4546 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 4547 bool InUnqualifiedLookup = false); 4548 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 4549 CXXScopeSpec &SS); 4550 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 4551 bool AllowBuiltinCreation = false, 4552 bool EnteringContext = false); 4553 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 4554 RedeclarationKind Redecl 4555 = NotForRedeclaration); 4556 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 4557 4558 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 4559 UnresolvedSetImpl &Functions); 4560 4561 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 4562 SourceLocation GnuLabelLoc = SourceLocation()); 4563 4564 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 4565 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 4566 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 4567 unsigned Quals); 4568 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 4569 bool RValueThis, unsigned ThisQuals); 4570 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 4571 unsigned Quals); 4572 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 4573 bool RValueThis, unsigned ThisQuals); 4574 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 4575 4576 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, 4577 bool IsUDSuffix); 4578 LiteralOperatorLookupResult 4579 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, 4580 bool AllowRaw, bool AllowTemplate, 4581 bool AllowStringTemplate, bool DiagnoseMissing, 4582 StringLiteral *StringLit = nullptr); 4583 bool isKnownName(StringRef name); 4584 4585 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. 4586 enum class FunctionEmissionStatus { 4587 Emitted, 4588 CUDADiscarded, // Discarded due to CUDA/HIP hostness 4589 OMPDiscarded, // Discarded due to OpenMP hostness 4590 TemplateDiscarded, // Discarded due to uninstantiated templates 4591 Unknown, 4592 }; 4593 FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, 4594 bool Final = false); 4595 4596 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. 4597 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); 4598 4599 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 4600 ArrayRef<Expr *> Args, ADLResult &Functions); 4601 4602 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 4603 VisibleDeclConsumer &Consumer, 4604 bool IncludeGlobalScope = true, 4605 bool LoadExternal = true); 4606 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 4607 VisibleDeclConsumer &Consumer, 4608 bool IncludeGlobalScope = true, 4609 bool IncludeDependentBases = false, 4610 bool LoadExternal = true); 4611 4612 enum CorrectTypoKind { 4613 CTK_NonError, // CorrectTypo used in a non error recovery situation. 4614 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 4615 }; 4616 4617 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 4618 Sema::LookupNameKind LookupKind, 4619 Scope *S, CXXScopeSpec *SS, 4620 CorrectionCandidateCallback &CCC, 4621 CorrectTypoKind Mode, 4622 DeclContext *MemberContext = nullptr, 4623 bool EnteringContext = false, 4624 const ObjCObjectPointerType *OPT = nullptr, 4625 bool RecordFailure = true); 4626 4627 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, 4628 Sema::LookupNameKind LookupKind, Scope *S, 4629 CXXScopeSpec *SS, 4630 CorrectionCandidateCallback &CCC, 4631 TypoDiagnosticGenerator TDG, 4632 TypoRecoveryCallback TRC, CorrectTypoKind Mode, 4633 DeclContext *MemberContext = nullptr, 4634 bool EnteringContext = false, 4635 const ObjCObjectPointerType *OPT = nullptr); 4636 4637 /// Process any TypoExprs in the given Expr and its children, 4638 /// generating diagnostics as appropriate and returning a new Expr if there 4639 /// were typos that were all successfully corrected and ExprError if one or 4640 /// more typos could not be corrected. 4641 /// 4642 /// \param E The Expr to check for TypoExprs. 4643 /// 4644 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its 4645 /// initializer. 4646 /// 4647 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it 4648 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. 4649 /// 4650 /// \param Filter A function applied to a newly rebuilt Expr to determine if 4651 /// it is an acceptable/usable result from a single combination of typo 4652 /// corrections. As long as the filter returns ExprError, different 4653 /// combinations of corrections will be tried until all are exhausted. 4654 ExprResult CorrectDelayedTyposInExpr( 4655 Expr *E, VarDecl *InitDecl = nullptr, 4656 bool RecoverUncorrectedTypos = false, 4657 llvm::function_ref<ExprResult(Expr *)> Filter = 4658 [](Expr *E) -> ExprResult { return E; }); 4659 4660 ExprResult CorrectDelayedTyposInExpr( 4661 ExprResult ER, VarDecl *InitDecl = nullptr, 4662 bool RecoverUncorrectedTypos = false, 4663 llvm::function_ref<ExprResult(Expr *)> Filter = 4664 [](Expr *E) -> ExprResult { return E; }) { 4665 return ER.isInvalid() 4666 ? ER 4667 : CorrectDelayedTyposInExpr(ER.get(), InitDecl, 4668 RecoverUncorrectedTypos, Filter); 4669 } 4670 4671 void diagnoseTypo(const TypoCorrection &Correction, 4672 const PartialDiagnostic &TypoDiag, 4673 bool ErrorRecovery = true); 4674 4675 void diagnoseTypo(const TypoCorrection &Correction, 4676 const PartialDiagnostic &TypoDiag, 4677 const PartialDiagnostic &PrevNote, 4678 bool ErrorRecovery = true); 4679 4680 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); 4681 4682 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 4683 ArrayRef<Expr *> Args, 4684 AssociatedNamespaceSet &AssociatedNamespaces, 4685 AssociatedClassSet &AssociatedClasses); 4686 4687 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 4688 bool ConsiderLinkage, bool AllowInlineNamespace); 4689 4690 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); 4691 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old); 4692 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old); 4693 bool IsRedefinitionInModule(const NamedDecl *New, 4694 const NamedDecl *Old) const; 4695 4696 void DiagnoseAmbiguousLookup(LookupResult &Result); 4697 //@} 4698 4699 /// Attempts to produce a RecoveryExpr after some AST node cannot be created. 4700 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 4701 ArrayRef<Expr *> SubExprs, 4702 QualType T = QualType()); 4703 4704 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 4705 SourceLocation IdLoc, 4706 bool TypoCorrection = false); 4707 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, 4708 SourceLocation Loc); 4709 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 4710 Scope *S, bool ForRedeclaration, 4711 SourceLocation Loc); 4712 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 4713 Scope *S); 4714 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 4715 FunctionDecl *FD); 4716 void AddKnownFunctionAttributes(FunctionDecl *FD); 4717 4718 // More parsing and symbol table subroutines. 4719 4720 void ProcessPragmaWeak(Scope *S, Decl *D); 4721 // Decl attributes - this routine is the top level dispatcher. 4722 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 4723 // Helper for delayed processing of attributes. 4724 void ProcessDeclAttributeDelayed(Decl *D, 4725 const ParsedAttributesView &AttrList); 4726 4727 // Options for ProcessDeclAttributeList(). 4728 struct ProcessDeclAttributeOptions { ProcessDeclAttributeOptionsProcessDeclAttributeOptions4729 ProcessDeclAttributeOptions() 4730 : IncludeCXX11Attributes(true), IgnoreTypeAttributes(false) {} 4731 WithIncludeCXX11AttributesProcessDeclAttributeOptions4732 ProcessDeclAttributeOptions WithIncludeCXX11Attributes(bool Val) { 4733 ProcessDeclAttributeOptions Result = *this; 4734 Result.IncludeCXX11Attributes = Val; 4735 return Result; 4736 } 4737 WithIgnoreTypeAttributesProcessDeclAttributeOptions4738 ProcessDeclAttributeOptions WithIgnoreTypeAttributes(bool Val) { 4739 ProcessDeclAttributeOptions Result = *this; 4740 Result.IgnoreTypeAttributes = Val; 4741 return Result; 4742 } 4743 4744 // Should C++11 attributes be processed? 4745 bool IncludeCXX11Attributes; 4746 4747 // Should any type attributes encountered be ignored? 4748 // If this option is false, a diagnostic will be emitted for any type 4749 // attributes of a kind that does not "slide" from the declaration to 4750 // the decl-specifier-seq. 4751 bool IgnoreTypeAttributes; 4752 }; 4753 4754 void ProcessDeclAttributeList(Scope *S, Decl *D, 4755 const ParsedAttributesView &AttrList, 4756 const ProcessDeclAttributeOptions &Options = 4757 ProcessDeclAttributeOptions()); 4758 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 4759 const ParsedAttributesView &AttrList); 4760 4761 void checkUnusedDeclAttributes(Declarator &D); 4762 4763 /// Handles semantic checking for features that are common to all attributes, 4764 /// such as checking whether a parameter was properly specified, or the 4765 /// correct number of arguments were passed, etc. Returns true if the 4766 /// attribute has been diagnosed. 4767 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, 4768 bool SkipArgCountCheck = false); 4769 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A, 4770 bool SkipArgCountCheck = false); 4771 4772 /// Determine if type T is a valid subject for a nonnull and similar 4773 /// attributes. By default, we look through references (the behavior used by 4774 /// nonnull), but if the second parameter is true, then we treat a reference 4775 /// type as valid. 4776 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 4777 4778 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); 4779 4780 /// Check validaty of calling convention attribute \p attr. If \p FD 4781 /// is not null pointer, use \p FD to determine the CUDA/HIP host/device 4782 /// target. Otherwise, it is specified by \p CFT. 4783 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, 4784 const FunctionDecl *FD = nullptr, 4785 CUDAFunctionTarget CFT = CFT_InvalidTarget); 4786 bool CheckAttrTarget(const ParsedAttr &CurrAttr); 4787 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); 4788 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, 4789 const Expr *E, StringRef &Str, 4790 SourceLocation *ArgLocation = nullptr); 4791 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, 4792 StringRef &Str, 4793 SourceLocation *ArgLocation = nullptr); 4794 llvm::Error isValidSectionSpecifier(StringRef Str); 4795 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); 4796 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); 4797 bool checkTargetVersionAttr(SourceLocation LiteralLoc, StringRef &Str, 4798 bool &isDefault); 4799 bool 4800 checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str, 4801 const StringLiteral *Literal, bool &HasDefault, 4802 bool &HasCommas, bool &HasNotDefault, 4803 SmallVectorImpl<SmallString<64>> &StringsBuffer); 4804 bool checkMSInheritanceAttrOnDefinition( 4805 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4806 MSInheritanceModel SemanticSpelling); 4807 4808 void CheckAlignasUnderalignment(Decl *D); 4809 4810 bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, 4811 const AttributeCommonInfo &A); 4812 bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, 4813 const AttributeCommonInfo &A); 4814 4815 bool CheckCountedByAttr(Scope *Scope, const FieldDecl *FD); 4816 4817 /// Adjust the calling convention of a method to be the ABI default if it 4818 /// wasn't specified explicitly. This handles method types formed from 4819 /// function type typedefs and typename template arguments. 4820 void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, 4821 bool IsCtorOrDtor, SourceLocation Loc); 4822 4823 // Check if there is an explicit attribute, but only look through parens. 4824 // The intent is to look for an attribute on the current declarator, but not 4825 // one that came from a typedef. 4826 bool hasExplicitCallingConv(QualType T); 4827 4828 /// Get the outermost AttributedType node that sets a calling convention. 4829 /// Valid types should not have multiple attributes with different CCs. 4830 const AttributedType *getCallingConvAttributedType(QualType T) const; 4831 4832 /// Check whether a nullability type specifier can be added to the given 4833 /// type through some means not written in source (e.g. API notes). 4834 /// 4835 /// \param Type The type to which the nullability specifier will be 4836 /// added. On success, this type will be updated appropriately. 4837 /// 4838 /// \param Nullability The nullability specifier to add. 4839 /// 4840 /// \param DiagLoc The location to use for diagnostics. 4841 /// 4842 /// \param AllowArrayTypes Whether to accept nullability specifiers on an 4843 /// array type (e.g., because it will decay to a pointer). 4844 /// 4845 /// \param OverrideExisting Whether to override an existing, locally-specified 4846 /// nullability specifier rather than complaining about the conflict. 4847 /// 4848 /// \returns true if nullability cannot be applied, false otherwise. 4849 bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, 4850 NullabilityKind Nullability, 4851 SourceLocation DiagLoc, 4852 bool AllowArrayTypes, 4853 bool OverrideExisting); 4854 4855 /// Process the attributes before creating an attributed statement. Returns 4856 /// the semantic attributes that have been processed. 4857 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs, 4858 SmallVectorImpl<const Attr *> &OutAttrs); 4859 4860 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 4861 ObjCMethodDecl *MethodDecl, 4862 bool IsProtocolMethodDecl); 4863 4864 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 4865 ObjCMethodDecl *Overridden, 4866 bool IsProtocolMethodDecl); 4867 4868 /// WarnExactTypedMethods - This routine issues a warning if method 4869 /// implementation declaration matches exactly that of its declaration. 4870 void WarnExactTypedMethods(ObjCMethodDecl *Method, 4871 ObjCMethodDecl *MethodDecl, 4872 bool IsProtocolMethodDecl); 4873 4874 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 4875 4876 /// CheckImplementationIvars - This routine checks if the instance variables 4877 /// listed in the implelementation match those listed in the interface. 4878 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 4879 ObjCIvarDecl **Fields, unsigned nIvars, 4880 SourceLocation Loc); 4881 4882 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 4883 /// remains unimplemented in the class or category \@implementation. 4884 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 4885 ObjCContainerDecl* IDecl, 4886 bool IncompleteImpl = false); 4887 4888 /// DiagnoseUnimplementedProperties - This routine warns on those properties 4889 /// which must be implemented by this implementation. 4890 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 4891 ObjCContainerDecl *CDecl, 4892 bool SynthesizeProperties); 4893 4894 /// Diagnose any null-resettable synthesized setters. 4895 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); 4896 4897 /// DefaultSynthesizeProperties - This routine default synthesizes all 4898 /// properties which must be synthesized in the class's \@implementation. 4899 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, 4900 ObjCInterfaceDecl *IDecl, 4901 SourceLocation AtEnd); 4902 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); 4903 4904 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 4905 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 4906 /// declared in class 'IFace'. 4907 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 4908 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 4909 4910 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which 4911 /// backs the property is not used in the property's accessor. 4912 void DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4913 const ObjCImplementationDecl *ImplD); 4914 4915 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and 4916 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. 4917 /// It also returns ivar's property on success. 4918 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4919 const ObjCPropertyDecl *&PDecl) const; 4920 4921 /// Called by ActOnProperty to handle \@property declarations in 4922 /// class extensions. 4923 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 4924 SourceLocation AtLoc, 4925 SourceLocation LParenLoc, 4926 FieldDeclarator &FD, 4927 Selector GetterSel, 4928 SourceLocation GetterNameLoc, 4929 Selector SetterSel, 4930 SourceLocation SetterNameLoc, 4931 const bool isReadWrite, 4932 unsigned &Attributes, 4933 const unsigned AttributesAsWritten, 4934 QualType T, 4935 TypeSourceInfo *TSI, 4936 tok::ObjCKeywordKind MethodImplKind); 4937 4938 /// Called by ActOnProperty and HandlePropertyInClassExtension to 4939 /// handle creating the ObjcPropertyDecl for a category or \@interface. 4940 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 4941 ObjCContainerDecl *CDecl, 4942 SourceLocation AtLoc, 4943 SourceLocation LParenLoc, 4944 FieldDeclarator &FD, 4945 Selector GetterSel, 4946 SourceLocation GetterNameLoc, 4947 Selector SetterSel, 4948 SourceLocation SetterNameLoc, 4949 const bool isReadWrite, 4950 const unsigned Attributes, 4951 const unsigned AttributesAsWritten, 4952 QualType T, 4953 TypeSourceInfo *TSI, 4954 tok::ObjCKeywordKind MethodImplKind, 4955 DeclContext *lexicalDC = nullptr); 4956 4957 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 4958 /// warning) when atomic property has one but not the other user-declared 4959 /// setter or getter. 4960 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 4961 ObjCInterfaceDecl* IDecl); 4962 4963 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 4964 4965 void DiagnoseMissingDesignatedInitOverrides( 4966 const ObjCImplementationDecl *ImplD, 4967 const ObjCInterfaceDecl *IFD); 4968 4969 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 4970 4971 enum MethodMatchStrategy { 4972 MMS_loose, 4973 MMS_strict 4974 }; 4975 4976 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 4977 /// true, or false, accordingly. 4978 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 4979 const ObjCMethodDecl *PrevMethod, 4980 MethodMatchStrategy strategy = MMS_strict); 4981 4982 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 4983 /// or protocol against those declared in their implementations. 4984 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 4985 const SelectorSet &ClsMap, 4986 SelectorSet &InsMapSeen, 4987 SelectorSet &ClsMapSeen, 4988 ObjCImplDecl* IMPDecl, 4989 ObjCContainerDecl* IDecl, 4990 bool &IncompleteImpl, 4991 bool ImmediateClass, 4992 bool WarnCategoryMethodImpl=false); 4993 4994 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 4995 /// category matches with those implemented in its primary class and 4996 /// warns each time an exact match is found. 4997 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 4998 4999 /// Add the given method to the list of globally-known methods. 5000 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 5001 5002 /// Returns default addr space for method qualifiers. 5003 LangAS getDefaultCXXMethodAddrSpace() const; 5004 5005 private: 5006 /// AddMethodToGlobalPool - Add an instance or factory method to the global 5007 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 5008 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 5009 5010 /// LookupMethodInGlobalPool - Returns the instance or factory method and 5011 /// optionally warns if there are multiple signatures. 5012 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 5013 bool receiverIdOrClass, 5014 bool instance); 5015 5016 public: 5017 /// - Returns instance or factory methods in global method pool for 5018 /// given selector. It checks the desired kind first, if none is found, and 5019 /// parameter checkTheOther is set, it then checks the other kind. If no such 5020 /// method or only one method is found, function returns false; otherwise, it 5021 /// returns true. 5022 bool 5023 CollectMultipleMethodsInGlobalPool(Selector Sel, 5024 SmallVectorImpl<ObjCMethodDecl*>& Methods, 5025 bool InstanceFirst, bool CheckTheOther, 5026 const ObjCObjectType *TypeBound = nullptr); 5027 5028 bool 5029 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 5030 SourceRange R, bool receiverIdOrClass, 5031 SmallVectorImpl<ObjCMethodDecl*>& Methods); 5032 5033 void 5034 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 5035 Selector Sel, SourceRange R, 5036 bool receiverIdOrClass); 5037 5038 private: 5039 /// - Returns a selector which best matches given argument list or 5040 /// nullptr if none could be found 5041 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 5042 bool IsInstance, 5043 SmallVectorImpl<ObjCMethodDecl*>& Methods); 5044 5045 5046 /// Record the typo correction failure and return an empty correction. 5047 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 5048 bool RecordFailure = true) { 5049 if (RecordFailure) 5050 TypoCorrectionFailures[Typo].insert(TypoLoc); 5051 return TypoCorrection(); 5052 } 5053 5054 public: 5055 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 5056 /// unit are added to a global pool. This allows us to efficiently associate 5057 /// a selector with a method declaraation for purposes of typechecking 5058 /// messages sent to "id" (where the class of the object is unknown). 5059 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 5060 AddMethodToGlobalPool(Method, impl, /*instance*/true); 5061 } 5062 5063 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 5064 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 5065 AddMethodToGlobalPool(Method, impl, /*instance*/false); 5066 } 5067 5068 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 5069 /// pool. 5070 void AddAnyMethodToGlobalPool(Decl *D); 5071 5072 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 5073 /// there are multiple signatures. 5074 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 5075 bool receiverIdOrClass=false) { 5076 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 5077 /*instance*/true); 5078 } 5079 5080 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 5081 /// there are multiple signatures. 5082 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 5083 bool receiverIdOrClass=false) { 5084 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 5085 /*instance*/false); 5086 } 5087 5088 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 5089 QualType ObjectType=QualType()); 5090 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 5091 /// implementation. 5092 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 5093 5094 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 5095 /// initialization. 5096 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 5097 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 5098 5099 //===--------------------------------------------------------------------===// 5100 // Statement Parsing Callbacks: SemaStmt.cpp. 5101 public: 5102 class FullExprArg { 5103 public: FullExprArg()5104 FullExprArg() : E(nullptr) { } FullExprArg(Sema & actions)5105 FullExprArg(Sema &actions) : E(nullptr) { } 5106 release()5107 ExprResult release() { 5108 return E; 5109 } 5110 get()5111 Expr *get() const { return E; } 5112 5113 Expr *operator->() { 5114 return E; 5115 } 5116 5117 private: 5118 // FIXME: No need to make the entire Sema class a friend when it's just 5119 // Sema::MakeFullExpr that needs access to the constructor below. 5120 friend class Sema; 5121 FullExprArg(Expr * expr)5122 explicit FullExprArg(Expr *expr) : E(expr) {} 5123 5124 Expr *E; 5125 }; 5126 MakeFullExpr(Expr * Arg)5127 FullExprArg MakeFullExpr(Expr *Arg) { 5128 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 5129 } MakeFullExpr(Expr * Arg,SourceLocation CC)5130 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 5131 return FullExprArg( 5132 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); 5133 } MakeFullDiscardedValueExpr(Expr * Arg)5134 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 5135 ExprResult FE = 5136 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 5137 /*DiscardedValue*/ true); 5138 return FullExprArg(FE.get()); 5139 } 5140 5141 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); 5142 StmtResult ActOnExprStmtError(); 5143 5144 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 5145 bool HasLeadingEmptyMacro = false); 5146 5147 void ActOnStartOfCompoundStmt(bool IsStmtExpr); 5148 void ActOnAfterCompoundStatementLeadingPragmas(); 5149 void ActOnFinishOfCompoundStmt(); 5150 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 5151 ArrayRef<Stmt *> Elts, bool isStmtExpr); 5152 5153 /// A RAII object to enter scope of a compound statement. 5154 class CompoundScopeRAII { 5155 public: S(S)5156 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { 5157 S.ActOnStartOfCompoundStmt(IsStmtExpr); 5158 } 5159 ~CompoundScopeRAII()5160 ~CompoundScopeRAII() { 5161 S.ActOnFinishOfCompoundStmt(); 5162 } 5163 5164 private: 5165 Sema &S; 5166 }; 5167 5168 /// An RAII helper that pops function a function scope on exit. 5169 struct FunctionScopeRAII { 5170 Sema &S; 5171 bool Active; FunctionScopeRAIIFunctionScopeRAII5172 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAIIFunctionScopeRAII5173 ~FunctionScopeRAII() { 5174 if (Active) 5175 S.PopFunctionScopeInfo(); 5176 } disableFunctionScopeRAII5177 void disable() { Active = false; } 5178 }; 5179 5180 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 5181 SourceLocation StartLoc, 5182 SourceLocation EndLoc); 5183 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 5184 StmtResult ActOnForEachLValueExpr(Expr *E); 5185 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); 5186 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, 5187 SourceLocation DotDotDotLoc, ExprResult RHS, 5188 SourceLocation ColonLoc); 5189 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 5190 5191 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 5192 SourceLocation ColonLoc, 5193 Stmt *SubStmt, Scope *CurScope); 5194 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 5195 SourceLocation ColonLoc, Stmt *SubStmt); 5196 5197 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, 5198 ArrayRef<const Attr *> Attrs, Stmt *SubStmt); 5199 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList, 5200 Stmt *SubStmt); 5201 5202 class ConditionResult; 5203 5204 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, 5205 SourceLocation LParenLoc, Stmt *InitStmt, 5206 ConditionResult Cond, SourceLocation RParenLoc, 5207 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 5208 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, 5209 SourceLocation LParenLoc, Stmt *InitStmt, 5210 ConditionResult Cond, SourceLocation RParenLoc, 5211 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 5212 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 5213 SourceLocation LParenLoc, Stmt *InitStmt, 5214 ConditionResult Cond, 5215 SourceLocation RParenLoc); 5216 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 5217 Stmt *Switch, Stmt *Body); 5218 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, 5219 ConditionResult Cond, SourceLocation RParenLoc, 5220 Stmt *Body); 5221 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 5222 SourceLocation WhileLoc, SourceLocation CondLParen, 5223 Expr *Cond, SourceLocation CondRParen); 5224 5225 StmtResult ActOnForStmt(SourceLocation ForLoc, 5226 SourceLocation LParenLoc, 5227 Stmt *First, 5228 ConditionResult Second, 5229 FullExprArg Third, 5230 SourceLocation RParenLoc, 5231 Stmt *Body); 5232 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 5233 Expr *collection); 5234 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 5235 Stmt *First, Expr *collection, 5236 SourceLocation RParenLoc); 5237 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 5238 5239 enum BuildForRangeKind { 5240 /// Initial building of a for-range statement. 5241 BFRK_Build, 5242 /// Instantiation or recovery rebuild of a for-range statement. Don't 5243 /// attempt any typo-correction. 5244 BFRK_Rebuild, 5245 /// Determining whether a for-range statement could be built. Avoid any 5246 /// unnecessary or irreversible actions. 5247 BFRK_Check 5248 }; 5249 5250 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, 5251 SourceLocation CoawaitLoc, 5252 Stmt *InitStmt, 5253 Stmt *LoopVar, 5254 SourceLocation ColonLoc, Expr *Collection, 5255 SourceLocation RParenLoc, 5256 BuildForRangeKind Kind); 5257 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 5258 SourceLocation CoawaitLoc, 5259 Stmt *InitStmt, 5260 SourceLocation ColonLoc, 5261 Stmt *RangeDecl, Stmt *Begin, Stmt *End, 5262 Expr *Cond, Expr *Inc, 5263 Stmt *LoopVarDecl, 5264 SourceLocation RParenLoc, 5265 BuildForRangeKind Kind); 5266 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 5267 5268 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 5269 SourceLocation LabelLoc, 5270 LabelDecl *TheDecl); 5271 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 5272 SourceLocation StarLoc, 5273 Expr *DestExp); 5274 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 5275 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 5276 5277 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 5278 CapturedRegionKind Kind, unsigned NumParams); 5279 typedef std::pair<StringRef, QualType> CapturedParamNameType; 5280 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 5281 CapturedRegionKind Kind, 5282 ArrayRef<CapturedParamNameType> Params, 5283 unsigned OpenMPCaptureLevel = 0); 5284 StmtResult ActOnCapturedRegionEnd(Stmt *S); 5285 void ActOnCapturedRegionError(); 5286 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 5287 SourceLocation Loc, 5288 unsigned NumParams); 5289 5290 struct NamedReturnInfo { 5291 const VarDecl *Candidate; 5292 5293 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; 5294 Status S; 5295 isMoveEligibleNamedReturnInfo5296 bool isMoveEligible() const { return S != None; }; isCopyElidableNamedReturnInfo5297 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } 5298 }; 5299 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn }; 5300 NamedReturnInfo getNamedReturnInfo( 5301 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal); 5302 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD); 5303 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, 5304 QualType ReturnType); 5305 5306 ExprResult 5307 PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 5308 const NamedReturnInfo &NRInfo, Expr *Value, 5309 bool SupressSimplerImplicitMoves = false); 5310 5311 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 5312 Scope *CurScope); 5313 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 5314 bool AllowRecovery = false); 5315 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 5316 NamedReturnInfo &NRInfo, 5317 bool SupressSimplerImplicitMoves); 5318 5319 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 5320 bool IsVolatile, unsigned NumOutputs, 5321 unsigned NumInputs, IdentifierInfo **Names, 5322 MultiExprArg Constraints, MultiExprArg Exprs, 5323 Expr *AsmString, MultiExprArg Clobbers, 5324 unsigned NumLabels, 5325 SourceLocation RParenLoc); 5326 5327 void FillInlineAsmIdentifierInfo(Expr *Res, 5328 llvm::InlineAsmIdentifierInfo &Info); 5329 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 5330 SourceLocation TemplateKWLoc, 5331 UnqualifiedId &Id, 5332 bool IsUnevaluatedContext); 5333 bool LookupInlineAsmField(StringRef Base, StringRef Member, 5334 unsigned &Offset, SourceLocation AsmLoc); 5335 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, 5336 SourceLocation AsmLoc); 5337 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 5338 ArrayRef<Token> AsmToks, 5339 StringRef AsmString, 5340 unsigned NumOutputs, unsigned NumInputs, 5341 ArrayRef<StringRef> Constraints, 5342 ArrayRef<StringRef> Clobbers, 5343 ArrayRef<Expr*> Exprs, 5344 SourceLocation EndLoc); 5345 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 5346 SourceLocation Location, 5347 bool AlwaysCreate); 5348 5349 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 5350 SourceLocation StartLoc, 5351 SourceLocation IdLoc, IdentifierInfo *Id, 5352 bool Invalid = false); 5353 5354 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 5355 5356 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 5357 Decl *Parm, Stmt *Body); 5358 5359 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 5360 5361 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 5362 MultiStmtArg Catch, Stmt *Finally); 5363 5364 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 5365 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 5366 Scope *CurScope); 5367 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 5368 Expr *operand); 5369 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 5370 Expr *SynchExpr, 5371 Stmt *SynchBody); 5372 5373 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 5374 5375 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 5376 SourceLocation StartLoc, 5377 SourceLocation IdLoc, 5378 IdentifierInfo *Id); 5379 5380 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 5381 5382 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 5383 Decl *ExDecl, Stmt *HandlerBlock); 5384 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 5385 ArrayRef<Stmt *> Handlers); 5386 5387 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 5388 SourceLocation TryLoc, Stmt *TryBlock, 5389 Stmt *Handler); 5390 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 5391 Expr *FilterExpr, 5392 Stmt *Block); 5393 void ActOnStartSEHFinallyBlock(); 5394 void ActOnAbortSEHFinallyBlock(); 5395 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 5396 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 5397 5398 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 5399 5400 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 5401 5402 /// If it's a file scoped decl that must warn if not used, keep track 5403 /// of it. 5404 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 5405 5406 typedef llvm::function_ref<void(SourceLocation Loc, PartialDiagnostic PD)> 5407 DiagReceiverTy; 5408 5409 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 5410 /// whose result is unused, warn. 5411 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID); 5412 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 5413 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D, 5414 DiagReceiverTy DiagReceiver); 5415 void DiagnoseUnusedDecl(const NamedDecl *ND); 5416 void DiagnoseUnusedDecl(const NamedDecl *ND, DiagReceiverTy DiagReceiver); 5417 5418 /// If VD is set but not otherwise used, diagnose, for a parameter or a 5419 /// variable. 5420 void DiagnoseUnusedButSetDecl(const VarDecl *VD, DiagReceiverTy DiagReceiver); 5421 5422 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 5423 /// statement as a \p Body, and it is located on the same line. 5424 /// 5425 /// This helps prevent bugs due to typos, such as: 5426 /// if (condition); 5427 /// do_stuff(); 5428 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 5429 const Stmt *Body, 5430 unsigned DiagID); 5431 5432 /// Warn if a for/while loop statement \p S, which is followed by 5433 /// \p PossibleBody, has a suspicious null statement as a body. 5434 void DiagnoseEmptyLoopBody(const Stmt *S, 5435 const Stmt *PossibleBody); 5436 5437 /// Warn if a value is moved to itself. 5438 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 5439 SourceLocation OpLoc); 5440 5441 /// Returns a field in a CXXRecordDecl that has the same name as the decl \p 5442 /// SelfAssigned when inside a CXXMethodDecl. 5443 const FieldDecl * 5444 getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned); 5445 5446 /// Warn if we're implicitly casting from a _Nullable pointer type to a 5447 /// _Nonnull one. 5448 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, 5449 SourceLocation Loc); 5450 5451 /// Warn when implicitly casting 0 to nullptr. 5452 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); 5453 PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)5454 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 5455 return DelayedDiagnostics.push(pool); 5456 } 5457 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 5458 5459 typedef ProcessingContextState ParsingClassState; PushParsingClass()5460 ParsingClassState PushParsingClass() { 5461 ParsingClassDepth++; 5462 return DelayedDiagnostics.pushUndelayed(); 5463 } PopParsingClass(ParsingClassState state)5464 void PopParsingClass(ParsingClassState state) { 5465 ParsingClassDepth--; 5466 DelayedDiagnostics.popUndelayed(state); 5467 } 5468 5469 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 5470 5471 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 5472 const ObjCInterfaceDecl *UnknownObjCClass, 5473 bool ObjCPropertyAccess, 5474 bool AvoidPartialAvailabilityChecks = false, 5475 ObjCInterfaceDecl *ClassReceiver = nullptr); 5476 5477 bool makeUnavailableInSystemHeader(SourceLocation loc, 5478 UnavailableAttr::ImplicitReason reason); 5479 5480 /// Issue any -Wunguarded-availability warnings in \c FD 5481 void DiagnoseUnguardedAvailabilityViolations(Decl *FD); 5482 5483 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 5484 5485 //===--------------------------------------------------------------------===// 5486 // Expression Parsing Callbacks: SemaExpr.cpp. 5487 5488 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); 5489 // A version of DiagnoseUseOfDecl that should be used if overload resolution 5490 // has been used to find this declaration, which means we don't have to bother 5491 // checking the trailing requires clause. DiagnoseUseOfOverloadedDecl(NamedDecl * D,SourceLocation Loc)5492 bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc) { 5493 return DiagnoseUseOfDecl( 5494 D, Loc, /*UnknownObjCClass=*/nullptr, /*ObjCPropertyAccess=*/false, 5495 /*AvoidPartialAvailabilityChecks=*/false, /*ClassReceiver=*/nullptr, 5496 /*SkipTrailingRequiresClause=*/true); 5497 } 5498 5499 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 5500 const ObjCInterfaceDecl *UnknownObjCClass = nullptr, 5501 bool ObjCPropertyAccess = false, 5502 bool AvoidPartialAvailabilityChecks = false, 5503 ObjCInterfaceDecl *ClassReciever = nullptr, 5504 bool SkipTrailingRequiresClause = false); 5505 void NoteDeletedFunction(FunctionDecl *FD); 5506 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); 5507 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 5508 ObjCMethodDecl *Getter, 5509 SourceLocation Loc); 5510 void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, 5511 ArrayRef<Expr *> Args); 5512 5513 void PushExpressionEvaluationContext( 5514 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, 5515 ExpressionEvaluationContextRecord::ExpressionKind Type = 5516 ExpressionEvaluationContextRecord::EK_Other); 5517 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 5518 void PushExpressionEvaluationContext( 5519 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 5520 ExpressionEvaluationContextRecord::ExpressionKind Type = 5521 ExpressionEvaluationContextRecord::EK_Other); 5522 void PopExpressionEvaluationContext(); 5523 5524 void DiscardCleanupsInEvaluationContext(); 5525 5526 ExprResult TransformToPotentiallyEvaluated(Expr *E); 5527 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo); 5528 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 5529 5530 ExprResult CheckUnevaluatedOperand(Expr *E); 5531 void CheckUnusedVolatileAssignment(Expr *E); 5532 5533 ExprResult ActOnConstantExpression(ExprResult Res); 5534 5535 // Functions for marking a declaration referenced. These functions also 5536 // contain the relevant logic for marking if a reference to a function or 5537 // variable is an odr-use (in the C++11 sense). There are separate variants 5538 // for expressions referring to a decl; these exist because odr-use marking 5539 // needs to be delayed for some constant variables when we build one of the 5540 // named expressions. 5541 // 5542 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and 5543 // should usually be true. This only needs to be set to false if the lack of 5544 // odr-use cannot be determined from the current context (for instance, 5545 // because the name denotes a virtual function and was written without an 5546 // explicit nested-name-specifier). 5547 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); 5548 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 5549 bool MightBeOdrUse = true); 5550 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 5551 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); 5552 void MarkMemberReferenced(MemberExpr *E); 5553 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); 5554 void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, 5555 unsigned CapturingScopeIndex); 5556 5557 ExprResult CheckLValueToRValueConversionOperand(Expr *E); 5558 void CleanupVarDeclMarking(); 5559 5560 enum TryCaptureKind { 5561 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 5562 }; 5563 5564 /// Try to capture the given variable. 5565 /// 5566 /// \param Var The variable to capture. 5567 /// 5568 /// \param Loc The location at which the capture occurs. 5569 /// 5570 /// \param Kind The kind of capture, which may be implicit (for either a 5571 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 5572 /// 5573 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 5574 /// an explicit lambda capture. 5575 /// 5576 /// \param BuildAndDiagnose Whether we are actually supposed to add the 5577 /// captures or diagnose errors. If false, this routine merely check whether 5578 /// the capture can occur without performing the capture itself or complaining 5579 /// if the variable cannot be captured. 5580 /// 5581 /// \param CaptureType Will be set to the type of the field used to capture 5582 /// this variable in the innermost block or lambda. Only valid when the 5583 /// variable can be captured. 5584 /// 5585 /// \param DeclRefType Will be set to the type of a reference to the capture 5586 /// from within the current scope. Only valid when the variable can be 5587 /// captured. 5588 /// 5589 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 5590 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 5591 /// This is useful when enclosing lambdas must speculatively capture 5592 /// variables that may or may not be used in certain specializations of 5593 /// a nested generic lambda. 5594 /// 5595 /// \returns true if an error occurred (i.e., the variable cannot be 5596 /// captured) and false if the capture succeeded. 5597 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, 5598 TryCaptureKind Kind, SourceLocation EllipsisLoc, 5599 bool BuildAndDiagnose, QualType &CaptureType, 5600 QualType &DeclRefType, 5601 const unsigned *const FunctionScopeIndexToStopAt); 5602 5603 /// Try to capture the given variable. 5604 bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, 5605 TryCaptureKind Kind = TryCapture_Implicit, 5606 SourceLocation EllipsisLoc = SourceLocation()); 5607 5608 /// Checks if the variable must be captured. 5609 bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc); 5610 5611 /// Given a variable, determine the type that a reference to that 5612 /// variable will have in the given scope. 5613 QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc); 5614 5615 /// Mark all of the declarations referenced within a particular AST node as 5616 /// referenced. Used when template instantiation instantiates a non-dependent 5617 /// type -- entities referenced by the type are now referenced. 5618 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 5619 void MarkDeclarationsReferencedInExpr( 5620 Expr *E, bool SkipLocalVariables = false, 5621 ArrayRef<const Expr *> StopAt = std::nullopt); 5622 5623 /// Try to recover by turning the given expression into a 5624 /// call. Returns true if recovery was attempted or an error was 5625 /// emitted; this may also leave the ExprResult invalid. 5626 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 5627 bool ForceComplain = false, 5628 bool (*IsPlausibleResult)(QualType) = nullptr); 5629 5630 /// Figure out if an expression could be turned into a call. 5631 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 5632 UnresolvedSetImpl &NonTemplateOverloads); 5633 5634 /// Try to convert an expression \p E to type \p Ty. Returns the result of the 5635 /// conversion. 5636 ExprResult tryConvertExprToType(Expr *E, QualType Ty); 5637 5638 /// Conditionally issue a diagnostic based on the statements's reachability 5639 /// analysis. 5640 /// 5641 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until 5642 /// the function body is parsed, and then do a basic reachability analysis to 5643 /// determine if the statement is reachable. If it is unreachable, the 5644 /// diagnostic will not be emitted. 5645 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 5646 const PartialDiagnostic &PD); 5647 5648 /// Conditionally issue a diagnostic based on the current 5649 /// evaluation context. 5650 /// 5651 /// \param Statement If Statement is non-null, delay reporting the 5652 /// diagnostic until the function body is parsed, and then do a basic 5653 /// reachability analysis to determine if the statement is reachable. 5654 /// If it is unreachable, the diagnostic will not be emitted. 5655 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 5656 const PartialDiagnostic &PD); 5657 /// Similar, but diagnostic is only produced if all the specified statements 5658 /// are reachable. 5659 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 5660 const PartialDiagnostic &PD); 5661 5662 // Primary Expressions. 5663 SourceRange getExprRange(Expr *E) const; 5664 5665 ExprResult ActOnIdExpression( 5666 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5667 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, 5668 CorrectionCandidateCallback *CCC = nullptr, 5669 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); 5670 5671 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 5672 TemplateArgumentListInfo &Buffer, 5673 DeclarationNameInfo &NameInfo, 5674 const TemplateArgumentListInfo *&TemplateArgs); 5675 5676 bool DiagnoseDependentMemberLookup(const LookupResult &R); 5677 5678 bool 5679 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 5680 CorrectionCandidateCallback &CCC, 5681 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 5682 ArrayRef<Expr *> Args = std::nullopt, 5683 DeclContext *LookupCtx = nullptr, 5684 TypoExpr **Out = nullptr); 5685 5686 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 5687 IdentifierInfo *II); 5688 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); 5689 5690 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 5691 IdentifierInfo *II, 5692 bool AllowBuiltinCreation=false); 5693 5694 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 5695 SourceLocation TemplateKWLoc, 5696 const DeclarationNameInfo &NameInfo, 5697 bool isAddressOfOperand, 5698 const TemplateArgumentListInfo *TemplateArgs); 5699 5700 /// If \p D cannot be odr-used in the current expression evaluation context, 5701 /// return a reason explaining why. Otherwise, return NOUR_None. 5702 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); 5703 5704 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 5705 SourceLocation Loc, 5706 const CXXScopeSpec *SS = nullptr); 5707 DeclRefExpr * 5708 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 5709 const DeclarationNameInfo &NameInfo, 5710 const CXXScopeSpec *SS = nullptr, 5711 NamedDecl *FoundD = nullptr, 5712 SourceLocation TemplateKWLoc = SourceLocation(), 5713 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5714 DeclRefExpr * 5715 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 5716 const DeclarationNameInfo &NameInfo, 5717 NestedNameSpecifierLoc NNS, 5718 NamedDecl *FoundD = nullptr, 5719 SourceLocation TemplateKWLoc = SourceLocation(), 5720 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5721 5722 ExprResult 5723 BuildAnonymousStructUnionMemberReference( 5724 const CXXScopeSpec &SS, 5725 SourceLocation nameLoc, 5726 IndirectFieldDecl *indirectField, 5727 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 5728 Expr *baseObjectExpr = nullptr, 5729 SourceLocation opLoc = SourceLocation()); 5730 5731 ExprResult BuildPossibleImplicitMemberExpr( 5732 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, 5733 const TemplateArgumentListInfo *TemplateArgs, const Scope *S, 5734 UnresolvedLookupExpr *AsULE = nullptr); 5735 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 5736 SourceLocation TemplateKWLoc, 5737 LookupResult &R, 5738 const TemplateArgumentListInfo *TemplateArgs, 5739 bool IsDefiniteInstance, 5740 const Scope *S); 5741 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 5742 const LookupResult &R, 5743 bool HasTrailingLParen); 5744 5745 ExprResult 5746 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 5747 const DeclarationNameInfo &NameInfo, 5748 bool IsAddressOfOperand, const Scope *S, 5749 TypeSourceInfo **RecoveryTSI = nullptr); 5750 5751 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 5752 SourceLocation TemplateKWLoc, 5753 const DeclarationNameInfo &NameInfo, 5754 const TemplateArgumentListInfo *TemplateArgs); 5755 5756 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 5757 LookupResult &R, 5758 bool NeedsADL, 5759 bool AcceptInvalidDecl = false); 5760 ExprResult BuildDeclarationNameExpr( 5761 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 5762 NamedDecl *FoundD = nullptr, 5763 const TemplateArgumentListInfo *TemplateArgs = nullptr, 5764 bool AcceptInvalidDecl = false); 5765 5766 ExprResult BuildLiteralOperatorCall(LookupResult &R, 5767 DeclarationNameInfo &SuffixInfo, 5768 ArrayRef<Expr *> Args, 5769 SourceLocation LitEndLoc, 5770 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 5771 5772 // ExpandFunctionLocalPredefinedMacros - Returns a new vector of Tokens, 5773 // where Tokens representing function local predefined macros (such as 5774 // __FUNCTION__) are replaced (expanded) with string-literal Tokens. 5775 std::vector<Token> ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks); 5776 5777 ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK); 5778 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 5779 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 5780 5781 ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 5782 SourceLocation LParen, 5783 SourceLocation RParen, 5784 TypeSourceInfo *TSI); 5785 ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 5786 SourceLocation LParen, 5787 SourceLocation RParen, 5788 ParsedType ParsedTy); 5789 5790 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); 5791 5792 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 5793 ExprResult ActOnCharacterConstant(const Token &Tok, 5794 Scope *UDLScope = nullptr); 5795 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 5796 ExprResult ActOnParenListExpr(SourceLocation L, 5797 SourceLocation R, 5798 MultiExprArg Val); 5799 5800 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 5801 /// fragments (e.g. "foo" "bar" L"baz"). 5802 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 5803 Scope *UDLScope = nullptr); 5804 5805 ExprResult ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks); 5806 5807 /// ControllingExprOrType is either an opaque pointer coming out of a 5808 /// ParsedType or an Expr *. FIXME: it'd be better to split this interface 5809 /// into two so we don't take a void *, but that's awkward because one of 5810 /// the operands is either a ParsedType or an Expr *, which doesn't lend 5811 /// itself to generic code very well. 5812 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 5813 SourceLocation DefaultLoc, 5814 SourceLocation RParenLoc, 5815 bool PredicateIsExpr, 5816 void *ControllingExprOrType, 5817 ArrayRef<ParsedType> ArgTypes, 5818 ArrayRef<Expr *> ArgExprs); 5819 /// ControllingExprOrType is either a TypeSourceInfo * or an Expr *. FIXME: 5820 /// it'd be better to split this interface into two so we don't take a 5821 /// void *, but see the FIXME on ActOnGenericSelectionExpr as to why that 5822 /// isn't a trivial change. 5823 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 5824 SourceLocation DefaultLoc, 5825 SourceLocation RParenLoc, 5826 bool PredicateIsExpr, 5827 void *ControllingExprOrType, 5828 ArrayRef<TypeSourceInfo *> Types, 5829 ArrayRef<Expr *> Exprs); 5830 5831 // Binary/Unary Operators. 'Tok' is the token for the operator. 5832 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 5833 Expr *InputExpr, bool IsAfterAmp = false); 5834 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, 5835 Expr *Input, bool IsAfterAmp = false); 5836 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, 5837 Expr *Input, bool IsAfterAmp = false); 5838 5839 bool isQualifiedMemberAccess(Expr *E); 5840 bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, 5841 const Expr *Op, 5842 const CXXMethodDecl *MD); 5843 5844 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 5845 5846 bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N); 5847 5848 bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, 5849 SourceLocation OpLoc, SourceRange R); 5850 bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, 5851 SourceLocation OpLoc, SourceRange R); 5852 5853 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 5854 SourceLocation OpLoc, 5855 UnaryExprOrTypeTrait ExprKind, 5856 SourceRange R); 5857 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 5858 UnaryExprOrTypeTrait ExprKind); 5859 ExprResult 5860 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 5861 UnaryExprOrTypeTrait ExprKind, 5862 bool IsType, void *TyOrEx, 5863 SourceRange ArgRange); 5864 5865 ExprResult CheckPlaceholderExpr(Expr *E); 5866 bool CheckVecStepExpr(Expr *E); 5867 5868 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 5869 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 5870 SourceRange ExprRange, 5871 UnaryExprOrTypeTrait ExprKind, 5872 StringRef KWName); 5873 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 5874 SourceLocation OpLoc, 5875 IdentifierInfo &Name, 5876 SourceLocation NameLoc, 5877 SourceLocation RParenLoc); 5878 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 5879 tok::TokenKind Kind, Expr *Input); 5880 5881 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 5882 MultiExprArg ArgExprs, 5883 SourceLocation RLoc); 5884 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5885 Expr *Idx, SourceLocation RLoc); 5886 5887 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 5888 Expr *ColumnIdx, 5889 SourceLocation RBLoc); 5890 5891 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5892 Expr *LowerBound, 5893 SourceLocation ColonLocFirst, 5894 SourceLocation ColonLocSecond, 5895 Expr *Length, Expr *Stride, 5896 SourceLocation RBLoc); 5897 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5898 SourceLocation RParenLoc, 5899 ArrayRef<Expr *> Dims, 5900 ArrayRef<SourceRange> Brackets); 5901 5902 /// Data structure for iterator expression. 5903 struct OMPIteratorData { 5904 IdentifierInfo *DeclIdent = nullptr; 5905 SourceLocation DeclIdentLoc; 5906 ParsedType Type; 5907 OMPIteratorExpr::IteratorRange Range; 5908 SourceLocation AssignLoc; 5909 SourceLocation ColonLoc; 5910 SourceLocation SecColonLoc; 5911 }; 5912 5913 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5914 SourceLocation LLoc, SourceLocation RLoc, 5915 ArrayRef<OMPIteratorData> Data); 5916 5917 // This struct is for use by ActOnMemberAccess to allow 5918 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 5919 // changing the access operator from a '.' to a '->' (to see if that is the 5920 // change needed to fix an error about an unknown member, e.g. when the class 5921 // defines a custom operator->). 5922 struct ActOnMemberAccessExtraArgs { 5923 Scope *S; 5924 UnqualifiedId &Id; 5925 Decl *ObjCImpDecl; 5926 }; 5927 5928 ExprResult BuildMemberReferenceExpr( 5929 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 5930 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5931 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 5932 const TemplateArgumentListInfo *TemplateArgs, 5933 const Scope *S, 5934 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5935 5936 ExprResult 5937 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 5938 bool IsArrow, const CXXScopeSpec &SS, 5939 SourceLocation TemplateKWLoc, 5940 NamedDecl *FirstQualifierInScope, LookupResult &R, 5941 const TemplateArgumentListInfo *TemplateArgs, 5942 const Scope *S, 5943 bool SuppressQualifierCheck = false, 5944 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5945 5946 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, 5947 SourceLocation OpLoc, 5948 const CXXScopeSpec &SS, FieldDecl *Field, 5949 DeclAccessPair FoundDecl, 5950 const DeclarationNameInfo &MemberNameInfo); 5951 5952 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 5953 5954 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 5955 const CXXScopeSpec &SS, 5956 const LookupResult &R); 5957 5958 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 5959 bool IsArrow, SourceLocation OpLoc, 5960 const CXXScopeSpec &SS, 5961 SourceLocation TemplateKWLoc, 5962 NamedDecl *FirstQualifierInScope, 5963 const DeclarationNameInfo &NameInfo, 5964 const TemplateArgumentListInfo *TemplateArgs); 5965 5966 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 5967 SourceLocation OpLoc, 5968 tok::TokenKind OpKind, 5969 CXXScopeSpec &SS, 5970 SourceLocation TemplateKWLoc, 5971 UnqualifiedId &Member, 5972 Decl *ObjCImpDecl); 5973 5974 MemberExpr * 5975 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5976 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, 5977 ValueDecl *Member, DeclAccessPair FoundDecl, 5978 bool HadMultipleCandidates, 5979 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5980 ExprValueKind VK, ExprObjectKind OK, 5981 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5982 MemberExpr * 5983 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5984 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, 5985 ValueDecl *Member, DeclAccessPair FoundDecl, 5986 bool HadMultipleCandidates, 5987 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5988 ExprValueKind VK, ExprObjectKind OK, 5989 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5990 5991 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 5992 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5993 FunctionDecl *FDecl, 5994 const FunctionProtoType *Proto, 5995 ArrayRef<Expr *> Args, 5996 SourceLocation RParenLoc, 5997 bool ExecConfig = false); 5998 void CheckStaticArrayArgument(SourceLocation CallLoc, 5999 ParmVarDecl *Param, 6000 const Expr *ArgExpr); 6001 6002 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 6003 /// This provides the location of the left/right parens and a list of comma 6004 /// locations. 6005 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 6006 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6007 Expr *ExecConfig = nullptr); 6008 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 6009 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6010 Expr *ExecConfig = nullptr, 6011 bool IsExecConfig = false, 6012 bool AllowRecovery = false); 6013 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 6014 MultiExprArg CallArgs); 6015 enum class AtomicArgumentOrder { API, AST }; 6016 ExprResult 6017 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 6018 SourceLocation RParenLoc, MultiExprArg Args, 6019 AtomicExpr::AtomicOp Op, 6020 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); 6021 ExprResult 6022 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, 6023 ArrayRef<Expr *> Arg, SourceLocation RParenLoc, 6024 Expr *Config = nullptr, bool IsExecConfig = false, 6025 ADLCallKind UsesADL = ADLCallKind::NotADL); 6026 6027 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 6028 MultiExprArg ExecConfig, 6029 SourceLocation GGGLoc); 6030 6031 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6032 Declarator &D, ParsedType &Ty, 6033 SourceLocation RParenLoc, Expr *CastExpr); 6034 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 6035 TypeSourceInfo *Ty, 6036 SourceLocation RParenLoc, 6037 Expr *Op); 6038 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 6039 6040 /// Build an altivec or OpenCL literal. 6041 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 6042 SourceLocation RParenLoc, Expr *E, 6043 TypeSourceInfo *TInfo); 6044 6045 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 6046 6047 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 6048 ParsedType Ty, 6049 SourceLocation RParenLoc, 6050 Expr *InitExpr); 6051 6052 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 6053 TypeSourceInfo *TInfo, 6054 SourceLocation RParenLoc, 6055 Expr *LiteralExpr); 6056 6057 ExprResult ActOnInitList(SourceLocation LBraceLoc, 6058 MultiExprArg InitArgList, 6059 SourceLocation RBraceLoc); 6060 6061 ExprResult BuildInitList(SourceLocation LBraceLoc, 6062 MultiExprArg InitArgList, 6063 SourceLocation RBraceLoc); 6064 6065 ExprResult ActOnDesignatedInitializer(Designation &Desig, 6066 SourceLocation EqualOrColonLoc, 6067 bool GNUSyntax, 6068 ExprResult Init); 6069 6070 private: 6071 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 6072 6073 public: 6074 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 6075 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 6076 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 6077 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 6078 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 6079 Expr *LHSExpr, Expr *RHSExpr); 6080 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 6081 UnresolvedSetImpl &Functions); 6082 6083 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); 6084 6085 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6086 /// in the case of a the GNU conditional expr extension. 6087 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 6088 SourceLocation ColonLoc, 6089 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 6090 6091 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 6092 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 6093 LabelDecl *TheDecl); 6094 6095 void ActOnStartStmtExpr(); 6096 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 6097 SourceLocation RPLoc); 6098 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 6099 SourceLocation RPLoc, unsigned TemplateDepth); 6100 // Handle the final expression in a statement expression. 6101 ExprResult ActOnStmtExprResult(ExprResult E); 6102 void ActOnStmtExprError(); 6103 6104 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 6105 struct OffsetOfComponent { 6106 SourceLocation LocStart, LocEnd; 6107 bool isBrackets; // true if [expr], false if .ident 6108 union { 6109 IdentifierInfo *IdentInfo; 6110 Expr *E; 6111 } U; 6112 }; 6113 6114 /// __builtin_offsetof(type, a.b[123][456].c) 6115 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 6116 TypeSourceInfo *TInfo, 6117 ArrayRef<OffsetOfComponent> Components, 6118 SourceLocation RParenLoc); 6119 ExprResult ActOnBuiltinOffsetOf(Scope *S, 6120 SourceLocation BuiltinLoc, 6121 SourceLocation TypeLoc, 6122 ParsedType ParsedArgTy, 6123 ArrayRef<OffsetOfComponent> Components, 6124 SourceLocation RParenLoc); 6125 6126 // __builtin_choose_expr(constExpr, expr1, expr2) 6127 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 6128 Expr *CondExpr, Expr *LHSExpr, 6129 Expr *RHSExpr, SourceLocation RPLoc); 6130 6131 // __builtin_va_arg(expr, type) 6132 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 6133 SourceLocation RPLoc); 6134 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 6135 TypeSourceInfo *TInfo, SourceLocation RPLoc); 6136 6137 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FUNCSIG(), 6138 // __builtin_FILE(), __builtin_COLUMN(), __builtin_source_location() 6139 ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, 6140 SourceLocation BuiltinLoc, 6141 SourceLocation RPLoc); 6142 6143 // Build a potentially resolved SourceLocExpr. 6144 ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, 6145 SourceLocation BuiltinLoc, SourceLocation RPLoc, 6146 DeclContext *ParentContext); 6147 6148 // __null 6149 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 6150 6151 bool CheckCaseExpression(Expr *E); 6152 6153 /// Describes the result of an "if-exists" condition check. 6154 enum IfExistsResult { 6155 /// The symbol exists. 6156 IER_Exists, 6157 6158 /// The symbol does not exist. 6159 IER_DoesNotExist, 6160 6161 /// The name is a dependent name, so the results will differ 6162 /// from one instantiation to the next. 6163 IER_Dependent, 6164 6165 /// An error occurred. 6166 IER_Error 6167 }; 6168 6169 IfExistsResult 6170 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 6171 const DeclarationNameInfo &TargetNameInfo); 6172 6173 IfExistsResult 6174 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 6175 bool IsIfExists, CXXScopeSpec &SS, 6176 UnqualifiedId &Name); 6177 6178 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 6179 bool IsIfExists, 6180 NestedNameSpecifierLoc QualifierLoc, 6181 DeclarationNameInfo NameInfo, 6182 Stmt *Nested); 6183 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 6184 bool IsIfExists, 6185 CXXScopeSpec &SS, UnqualifiedId &Name, 6186 Stmt *Nested); 6187 6188 //===------------------------- "Block" Extension ------------------------===// 6189 6190 /// ActOnBlockStart - This callback is invoked when a block literal is 6191 /// started. 6192 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 6193 6194 /// ActOnBlockArguments - This callback allows processing of block arguments. 6195 /// If there are no arguments, this is still invoked. 6196 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 6197 Scope *CurScope); 6198 6199 /// ActOnBlockError - If there is an error parsing a block, this callback 6200 /// is invoked to pop the information about the block from the action impl. 6201 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 6202 6203 /// ActOnBlockStmtExpr - This is called when the body of a block statement 6204 /// literal was successfully completed. ^(int x){...} 6205 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 6206 Scope *CurScope); 6207 6208 //===---------------------------- Clang Extensions ----------------------===// 6209 6210 /// __builtin_convertvector(...) 6211 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 6212 SourceLocation BuiltinLoc, 6213 SourceLocation RParenLoc); 6214 6215 //===---------------------------- OpenCL Features -----------------------===// 6216 6217 /// __builtin_astype(...) 6218 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 6219 SourceLocation BuiltinLoc, 6220 SourceLocation RParenLoc); 6221 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, 6222 SourceLocation BuiltinLoc, 6223 SourceLocation RParenLoc); 6224 6225 //===---------------------------- HLSL Features -------------------------===// 6226 Decl *ActOnStartHLSLBuffer(Scope *BufferScope, bool CBuffer, 6227 SourceLocation KwLoc, IdentifierInfo *Ident, 6228 SourceLocation IdentLoc, SourceLocation LBrace); 6229 void ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace); 6230 6231 //===---------------------------- C++ Features --------------------------===// 6232 6233 // Act on C++ namespaces 6234 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 6235 SourceLocation NamespaceLoc, 6236 SourceLocation IdentLoc, IdentifierInfo *Ident, 6237 SourceLocation LBrace, 6238 const ParsedAttributesView &AttrList, 6239 UsingDirectiveDecl *&UsingDecl, bool IsNested); 6240 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 6241 6242 NamespaceDecl *getStdNamespace() const; 6243 NamespaceDecl *getOrCreateStdNamespace(); 6244 6245 CXXRecordDecl *getStdBadAlloc() const; 6246 EnumDecl *getStdAlignValT() const; 6247 6248 ValueDecl *tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, 6249 const IdentifierInfo *MemberOrBase); 6250 6251 private: 6252 // A cache representing if we've fully checked the various comparison category 6253 // types stored in ASTContext. The bit-index corresponds to the integer value 6254 // of a ComparisonCategoryType enumerator. 6255 llvm::SmallBitVector FullyCheckedComparisonCategories; 6256 6257 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 6258 CXXScopeSpec &SS, 6259 ParsedType TemplateTypeTy, 6260 IdentifierInfo *MemberOrBase); 6261 6262 public: 6263 enum class ComparisonCategoryUsage { 6264 /// The '<=>' operator was used in an expression and a builtin operator 6265 /// was selected. 6266 OperatorInExpression, 6267 /// A defaulted 'operator<=>' needed the comparison category. This 6268 /// typically only applies to 'std::strong_ordering', due to the implicit 6269 /// fallback return value. 6270 DefaultedOperator, 6271 }; 6272 6273 /// Lookup the specified comparison category types in the standard 6274 /// library, an check the VarDecls possibly returned by the operator<=> 6275 /// builtins for that type. 6276 /// 6277 /// \return The type of the comparison category type corresponding to the 6278 /// specified Kind, or a null type if an error occurs 6279 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, 6280 SourceLocation Loc, 6281 ComparisonCategoryUsage Usage); 6282 6283 /// Tests whether Ty is an instance of std::initializer_list and, if 6284 /// it is and Element is not NULL, assigns the element type to Element. 6285 bool isStdInitializerList(QualType Ty, QualType *Element); 6286 6287 /// Looks for the std::initializer_list template and instantiates it 6288 /// with Element, or emits an error if it's not found. 6289 /// 6290 /// \returns The instantiated template, or null on error. 6291 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 6292 6293 /// Determine whether Ctor is an initializer-list constructor, as 6294 /// defined in [dcl.init.list]p2. 6295 bool isInitListConstructor(const FunctionDecl *Ctor); 6296 6297 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, 6298 SourceLocation NamespcLoc, CXXScopeSpec &SS, 6299 SourceLocation IdentLoc, 6300 IdentifierInfo *NamespcName, 6301 const ParsedAttributesView &AttrList); 6302 6303 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 6304 6305 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 6306 SourceLocation NamespaceLoc, 6307 SourceLocation AliasLoc, 6308 IdentifierInfo *Alias, 6309 CXXScopeSpec &SS, 6310 SourceLocation IdentLoc, 6311 IdentifierInfo *Ident); 6312 6313 void FilterUsingLookup(Scope *S, LookupResult &lookup); 6314 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 6315 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, 6316 const LookupResult &PreviousDecls, 6317 UsingShadowDecl *&PrevShadow); 6318 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 6319 NamedDecl *Target, 6320 UsingShadowDecl *PrevDecl); 6321 6322 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6323 bool HasTypenameKeyword, 6324 const CXXScopeSpec &SS, 6325 SourceLocation NameLoc, 6326 const LookupResult &Previous); 6327 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 6328 const CXXScopeSpec &SS, 6329 const DeclarationNameInfo &NameInfo, 6330 SourceLocation NameLoc, 6331 const LookupResult *R = nullptr, 6332 const UsingDecl *UD = nullptr); 6333 6334 NamedDecl *BuildUsingDeclaration( 6335 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 6336 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 6337 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 6338 const ParsedAttributesView &AttrList, bool IsInstantiation, 6339 bool IsUsingIfExists); 6340 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 6341 SourceLocation UsingLoc, 6342 SourceLocation EnumLoc, 6343 SourceLocation NameLoc, 6344 TypeSourceInfo *EnumType, EnumDecl *ED); 6345 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 6346 ArrayRef<NamedDecl *> Expansions); 6347 6348 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 6349 6350 /// Given a derived-class using shadow declaration for a constructor and the 6351 /// correspnding base class constructor, find or create the implicit 6352 /// synthesized derived class constructor to use for this initialization. 6353 CXXConstructorDecl * 6354 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, 6355 ConstructorUsingShadowDecl *DerivedShadow); 6356 6357 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, 6358 SourceLocation UsingLoc, 6359 SourceLocation TypenameLoc, CXXScopeSpec &SS, 6360 UnqualifiedId &Name, SourceLocation EllipsisLoc, 6361 const ParsedAttributesView &AttrList); 6362 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, 6363 SourceLocation UsingLoc, 6364 SourceLocation EnumLoc, 6365 SourceLocation IdentLoc, IdentifierInfo &II, 6366 CXXScopeSpec *SS = nullptr); 6367 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, 6368 MultiTemplateParamsArg TemplateParams, 6369 SourceLocation UsingLoc, UnqualifiedId &Name, 6370 const ParsedAttributesView &AttrList, 6371 TypeResult Type, Decl *DeclFromDeclSpec); 6372 6373 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 6374 /// including handling of its default argument expressions. 6375 /// 6376 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 6377 ExprResult BuildCXXConstructExpr( 6378 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, 6379 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 6380 bool HadMultipleCandidates, bool IsListInitialization, 6381 bool IsStdInitListInitialization, bool RequiresZeroInit, 6382 CXXConstructionKind ConstructKind, SourceRange ParenRange); 6383 6384 /// Build a CXXConstructExpr whose constructor has already been resolved if 6385 /// it denotes an inherited constructor. 6386 ExprResult BuildCXXConstructExpr( 6387 SourceLocation ConstructLoc, QualType DeclInitType, 6388 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, 6389 bool HadMultipleCandidates, bool IsListInitialization, 6390 bool IsStdInitListInitialization, bool RequiresZeroInit, 6391 CXXConstructionKind ConstructKind, SourceRange ParenRange); 6392 6393 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 6394 // the constructor can be elidable? 6395 ExprResult BuildCXXConstructExpr( 6396 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, 6397 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, 6398 bool HadMultipleCandidates, bool IsListInitialization, 6399 bool IsStdInitListInitialization, bool RequiresZeroInit, 6400 CXXConstructionKind ConstructKind, SourceRange ParenRange); 6401 6402 ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, 6403 SourceLocation InitLoc); 6404 6405 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 6406 6407 6408 /// Instantiate or parse a C++ default argument expression as necessary. 6409 /// Return true on error. 6410 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 6411 ParmVarDecl *Param, Expr *Init = nullptr, 6412 bool SkipImmediateInvocations = true); 6413 6414 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 6415 /// the default expr if needed. 6416 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 6417 ParmVarDecl *Param, Expr *Init = nullptr); 6418 6419 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 6420 /// constructed variable. 6421 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 6422 6423 /// Helper class that collects exception specifications for 6424 /// implicitly-declared special member functions. 6425 class ImplicitExceptionSpecification { 6426 // Pointer to allow copying 6427 Sema *Self; 6428 // We order exception specifications thus: 6429 // noexcept is the most restrictive, but is only used in C++11. 6430 // throw() comes next. 6431 // Then a throw(collected exceptions) 6432 // Finally no specification, which is expressed as noexcept(false). 6433 // throw(...) is used instead if any called function uses it. 6434 ExceptionSpecificationType ComputedEST; 6435 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 6436 SmallVector<QualType, 4> Exceptions; 6437 ClearExceptions()6438 void ClearExceptions() { 6439 ExceptionsSeen.clear(); 6440 Exceptions.clear(); 6441 } 6442 6443 public: ImplicitExceptionSpecification(Sema & Self)6444 explicit ImplicitExceptionSpecification(Sema &Self) 6445 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 6446 if (!Self.getLangOpts().CPlusPlus11) 6447 ComputedEST = EST_DynamicNone; 6448 } 6449 6450 /// Get the computed exception specification type. getExceptionSpecType()6451 ExceptionSpecificationType getExceptionSpecType() const { 6452 assert(!isComputedNoexcept(ComputedEST) && 6453 "noexcept(expr) should not be a possible result"); 6454 return ComputedEST; 6455 } 6456 6457 /// The number of exceptions in the exception specification. size()6458 unsigned size() const { return Exceptions.size(); } 6459 6460 /// The set of exceptions in the exception specification. data()6461 const QualType *data() const { return Exceptions.data(); } 6462 6463 /// Integrate another called method into the collected data. 6464 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 6465 6466 /// Integrate an invoked expression into the collected data. CalledExpr(Expr * E)6467 void CalledExpr(Expr *E) { CalledStmt(E); } 6468 6469 /// Integrate an invoked statement into the collected data. 6470 void CalledStmt(Stmt *S); 6471 6472 /// Overwrite an EPI's exception specification with this 6473 /// computed exception specification. getExceptionSpec()6474 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 6475 FunctionProtoType::ExceptionSpecInfo ESI; 6476 ESI.Type = getExceptionSpecType(); 6477 if (ESI.Type == EST_Dynamic) { 6478 ESI.Exceptions = Exceptions; 6479 } else if (ESI.Type == EST_None) { 6480 /// C++11 [except.spec]p14: 6481 /// The exception-specification is noexcept(false) if the set of 6482 /// potential exceptions of the special member function contains "any" 6483 ESI.Type = EST_NoexceptFalse; 6484 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 6485 tok::kw_false).get(); 6486 } 6487 return ESI; 6488 } 6489 }; 6490 6491 /// Evaluate the implicit exception specification for a defaulted 6492 /// special member function. 6493 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); 6494 6495 /// Check the given noexcept-specifier, convert its expression, and compute 6496 /// the appropriate ExceptionSpecificationType. 6497 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr, 6498 ExceptionSpecificationType &EST); 6499 6500 /// Check the given exception-specification and update the 6501 /// exception specification information with the results. 6502 void checkExceptionSpecification(bool IsTopLevel, 6503 ExceptionSpecificationType EST, 6504 ArrayRef<ParsedType> DynamicExceptions, 6505 ArrayRef<SourceRange> DynamicExceptionRanges, 6506 Expr *NoexceptExpr, 6507 SmallVectorImpl<QualType> &Exceptions, 6508 FunctionProtoType::ExceptionSpecInfo &ESI); 6509 6510 /// Determine if we're in a case where we need to (incorrectly) eagerly 6511 /// parse an exception specification to work around a libstdc++ bug. 6512 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 6513 6514 /// Add an exception-specification to the given member function 6515 /// (or member function template). The exception-specification was parsed 6516 /// after the method itself was declared. 6517 void actOnDelayedExceptionSpecification(Decl *Method, 6518 ExceptionSpecificationType EST, 6519 SourceRange SpecificationRange, 6520 ArrayRef<ParsedType> DynamicExceptions, 6521 ArrayRef<SourceRange> DynamicExceptionRanges, 6522 Expr *NoexceptExpr); 6523 6524 class InheritedConstructorInfo; 6525 6526 /// Determine if a special member function should have a deleted 6527 /// definition when it is defaulted. 6528 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6529 InheritedConstructorInfo *ICI = nullptr, 6530 bool Diagnose = false); 6531 6532 /// Produce notes explaining why a defaulted function was defined as deleted. 6533 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); 6534 6535 /// Declare the implicit default constructor for the given class. 6536 /// 6537 /// \param ClassDecl The class declaration into which the implicit 6538 /// default constructor will be added. 6539 /// 6540 /// \returns The implicitly-declared default constructor. 6541 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 6542 CXXRecordDecl *ClassDecl); 6543 6544 /// DefineImplicitDefaultConstructor - Checks for feasibility of 6545 /// defining this constructor as the default constructor. 6546 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 6547 CXXConstructorDecl *Constructor); 6548 6549 /// Declare the implicit destructor for the given class. 6550 /// 6551 /// \param ClassDecl The class declaration into which the implicit 6552 /// destructor will be added. 6553 /// 6554 /// \returns The implicitly-declared destructor. 6555 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 6556 6557 /// DefineImplicitDestructor - Checks for feasibility of 6558 /// defining this destructor as the default destructor. 6559 void DefineImplicitDestructor(SourceLocation CurrentLocation, 6560 CXXDestructorDecl *Destructor); 6561 6562 /// Build an exception spec for destructors that don't have one. 6563 /// 6564 /// C++11 says that user-defined destructors with no exception spec get one 6565 /// that looks as if the destructor was implicitly declared. 6566 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); 6567 6568 /// Define the specified inheriting constructor. 6569 void DefineInheritingConstructor(SourceLocation UseLoc, 6570 CXXConstructorDecl *Constructor); 6571 6572 /// Declare the implicit copy constructor for the given class. 6573 /// 6574 /// \param ClassDecl The class declaration into which the implicit 6575 /// copy constructor will be added. 6576 /// 6577 /// \returns The implicitly-declared copy constructor. 6578 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 6579 6580 /// DefineImplicitCopyConstructor - Checks for feasibility of 6581 /// defining this constructor as the copy constructor. 6582 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 6583 CXXConstructorDecl *Constructor); 6584 6585 /// Declare the implicit move constructor for the given class. 6586 /// 6587 /// \param ClassDecl The Class declaration into which the implicit 6588 /// move constructor will be added. 6589 /// 6590 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 6591 /// declared. 6592 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 6593 6594 /// DefineImplicitMoveConstructor - Checks for feasibility of 6595 /// defining this constructor as the move constructor. 6596 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 6597 CXXConstructorDecl *Constructor); 6598 6599 /// Declare the implicit copy assignment operator for the given class. 6600 /// 6601 /// \param ClassDecl The class declaration into which the implicit 6602 /// copy assignment operator will be added. 6603 /// 6604 /// \returns The implicitly-declared copy assignment operator. 6605 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 6606 6607 /// Defines an implicitly-declared copy assignment operator. 6608 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 6609 CXXMethodDecl *MethodDecl); 6610 6611 /// Declare the implicit move assignment operator for the given class. 6612 /// 6613 /// \param ClassDecl The Class declaration into which the implicit 6614 /// move assignment operator will be added. 6615 /// 6616 /// \returns The implicitly-declared move assignment operator, or NULL if it 6617 /// wasn't declared. 6618 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 6619 6620 /// Defines an implicitly-declared move assignment operator. 6621 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 6622 CXXMethodDecl *MethodDecl); 6623 6624 /// Force the declaration of any implicitly-declared members of this 6625 /// class. 6626 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 6627 6628 /// Check a completed declaration of an implicit special member. 6629 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); 6630 6631 /// Determine whether the given function is an implicitly-deleted 6632 /// special member function. 6633 bool isImplicitlyDeleted(FunctionDecl *FD); 6634 6635 /// Check whether 'this' shows up in the type of a static member 6636 /// function after the (naturally empty) cv-qualifier-seq would be. 6637 /// 6638 /// \returns true if an error occurred. 6639 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 6640 6641 /// Whether this' shows up in the exception specification of a static 6642 /// member function. 6643 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 6644 6645 /// Check whether 'this' shows up in the attributes of the given 6646 /// static member function. 6647 /// 6648 /// \returns true if an error occurred. 6649 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 6650 6651 /// MaybeBindToTemporary - If the passed in expression has a record type with 6652 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 6653 /// it simply returns the passed in expression. 6654 ExprResult MaybeBindToTemporary(Expr *E); 6655 6656 /// Wrap the expression in a ConstantExpr if it is a potential immediate 6657 /// invocation. 6658 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); 6659 6660 bool CheckImmediateEscalatingFunctionDefinition( 6661 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI); 6662 6663 void MarkExpressionAsImmediateEscalating(Expr *E); 6664 6665 void DiagnoseImmediateEscalatingReason(FunctionDecl *FD); 6666 6667 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 6668 QualType DeclInitType, MultiExprArg ArgsPtr, 6669 SourceLocation Loc, 6670 SmallVectorImpl<Expr *> &ConvertedArgs, 6671 bool AllowExplicit = false, 6672 bool IsListInitialization = false); 6673 6674 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 6675 SourceLocation NameLoc, 6676 IdentifierInfo &Name); 6677 6678 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, 6679 Scope *S, CXXScopeSpec &SS, 6680 bool EnteringContext); 6681 ParsedType getDestructorName(IdentifierInfo &II, SourceLocation NameLoc, 6682 Scope *S, CXXScopeSpec &SS, 6683 ParsedType ObjectType, bool EnteringContext); 6684 6685 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, 6686 ParsedType ObjectType); 6687 6688 // Checks that reinterpret casts don't have undefined behavior. 6689 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 6690 bool IsDereference, SourceRange Range); 6691 6692 // Checks that the vector type should be initialized from a scalar 6693 // by splatting the value rather than populating a single element. 6694 // This is the case for AltiVecVector types as well as with 6695 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified. 6696 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy); 6697 6698 // Checks if the -faltivec-src-compat=gcc option is specified. 6699 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are 6700 // treated the same way as they are when trying to initialize 6701 // these vectors on gcc (an error is emitted). 6702 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, 6703 QualType SrcTy); 6704 6705 /// ActOnCXXNamedCast - Parse 6706 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 6707 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 6708 tok::TokenKind Kind, 6709 SourceLocation LAngleBracketLoc, 6710 Declarator &D, 6711 SourceLocation RAngleBracketLoc, 6712 SourceLocation LParenLoc, 6713 Expr *E, 6714 SourceLocation RParenLoc); 6715 6716 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 6717 tok::TokenKind Kind, 6718 TypeSourceInfo *Ty, 6719 Expr *E, 6720 SourceRange AngleBrackets, 6721 SourceRange Parens); 6722 6723 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, 6724 ExprResult Operand, 6725 SourceLocation RParenLoc); 6726 6727 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, 6728 Expr *Operand, SourceLocation RParenLoc); 6729 6730 ExprResult BuildCXXTypeId(QualType TypeInfoType, 6731 SourceLocation TypeidLoc, 6732 TypeSourceInfo *Operand, 6733 SourceLocation RParenLoc); 6734 ExprResult BuildCXXTypeId(QualType TypeInfoType, 6735 SourceLocation TypeidLoc, 6736 Expr *Operand, 6737 SourceLocation RParenLoc); 6738 6739 /// ActOnCXXTypeid - Parse typeid( something ). 6740 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 6741 SourceLocation LParenLoc, bool isType, 6742 void *TyOrExpr, 6743 SourceLocation RParenLoc); 6744 6745 ExprResult BuildCXXUuidof(QualType TypeInfoType, 6746 SourceLocation TypeidLoc, 6747 TypeSourceInfo *Operand, 6748 SourceLocation RParenLoc); 6749 ExprResult BuildCXXUuidof(QualType TypeInfoType, 6750 SourceLocation TypeidLoc, 6751 Expr *Operand, 6752 SourceLocation RParenLoc); 6753 6754 /// ActOnCXXUuidof - Parse __uuidof( something ). 6755 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 6756 SourceLocation LParenLoc, bool isType, 6757 void *TyOrExpr, 6758 SourceLocation RParenLoc); 6759 6760 /// Handle a C++1z fold-expression: ( expr op ... op expr ). 6761 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, 6762 tok::TokenKind Operator, 6763 SourceLocation EllipsisLoc, Expr *RHS, 6764 SourceLocation RParenLoc); 6765 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, 6766 SourceLocation LParenLoc, Expr *LHS, 6767 BinaryOperatorKind Operator, 6768 SourceLocation EllipsisLoc, Expr *RHS, 6769 SourceLocation RParenLoc, 6770 std::optional<unsigned> NumExpansions); 6771 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 6772 BinaryOperatorKind Operator); 6773 6774 //// ActOnCXXThis - Parse 'this' pointer. 6775 ExprResult ActOnCXXThis(SourceLocation loc); 6776 6777 /// Build a CXXThisExpr and mark it referenced in the current context. 6778 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); 6779 void MarkThisReferenced(CXXThisExpr *This); 6780 6781 /// Try to retrieve the type of the 'this' pointer. 6782 /// 6783 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 6784 QualType getCurrentThisType(); 6785 6786 /// When non-NULL, the C++ 'this' expression is allowed despite the 6787 /// current context not being a non-static member function. In such cases, 6788 /// this provides the type used for 'this'. 6789 QualType CXXThisTypeOverride; 6790 6791 /// RAII object used to temporarily allow the C++ 'this' expression 6792 /// to be used, with the given qualifiers on the current class type. 6793 class CXXThisScopeRAII { 6794 Sema &S; 6795 QualType OldCXXThisTypeOverride; 6796 bool Enabled; 6797 6798 public: 6799 /// Introduce a new scope where 'this' may be allowed (when enabled), 6800 /// using the given declaration (which is either a class template or a 6801 /// class) along with the given qualifiers. 6802 /// along with the qualifiers placed on '*this'. 6803 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, 6804 bool Enabled = true); 6805 6806 ~CXXThisScopeRAII(); 6807 }; 6808 6809 /// Make sure the value of 'this' is actually available in the current 6810 /// context, if it is a potentially evaluated context. 6811 /// 6812 /// \param Loc The location at which the capture of 'this' occurs. 6813 /// 6814 /// \param Explicit Whether 'this' is explicitly captured in a lambda 6815 /// capture list. 6816 /// 6817 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 6818 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 6819 /// This is useful when enclosing lambdas must speculatively capture 6820 /// 'this' that may or may not be used in certain specializations of 6821 /// a nested generic lambda (depending on whether the name resolves to 6822 /// a non-static member function or a static function). 6823 /// \return returns 'true' if failed, 'false' if success. 6824 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 6825 bool BuildAndDiagnose = true, 6826 const unsigned *const FunctionScopeIndexToStopAt = nullptr, 6827 bool ByCopy = false); 6828 6829 /// Determine whether the given type is the type of *this that is used 6830 /// outside of the body of a member function for a type that is currently 6831 /// being defined. 6832 bool isThisOutsideMemberFunctionBody(QualType BaseType); 6833 6834 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 6835 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 6836 6837 6838 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 6839 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 6840 6841 ExprResult 6842 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, 6843 SourceLocation AtLoc, SourceLocation RParen); 6844 6845 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 6846 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 6847 6848 //// ActOnCXXThrow - Parse throw expressions. 6849 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 6850 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 6851 bool IsThrownVarInScope); 6852 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); 6853 6854 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 6855 /// Can be interpreted either as function-style casting ("int(x)") 6856 /// or class type construction ("ClassType(x,y,z)") 6857 /// or creation of a value-initialized type ("int()"). 6858 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 6859 SourceLocation LParenOrBraceLoc, 6860 MultiExprArg Exprs, 6861 SourceLocation RParenOrBraceLoc, 6862 bool ListInitialization); 6863 6864 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 6865 SourceLocation LParenLoc, 6866 MultiExprArg Exprs, 6867 SourceLocation RParenLoc, 6868 bool ListInitialization); 6869 6870 /// ActOnCXXNew - Parsed a C++ 'new' expression. 6871 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 6872 SourceLocation PlacementLParen, 6873 MultiExprArg PlacementArgs, 6874 SourceLocation PlacementRParen, 6875 SourceRange TypeIdParens, Declarator &D, 6876 Expr *Initializer); 6877 ExprResult 6878 BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, 6879 MultiExprArg PlacementArgs, SourceLocation PlacementRParen, 6880 SourceRange TypeIdParens, QualType AllocType, 6881 TypeSourceInfo *AllocTypeInfo, std::optional<Expr *> ArraySize, 6882 SourceRange DirectInitRange, Expr *Initializer); 6883 6884 /// Determine whether \p FD is an aligned allocation or deallocation 6885 /// function that is unavailable. 6886 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; 6887 6888 /// Produce diagnostics if \p FD is an aligned allocation or deallocation 6889 /// function that is unavailable. 6890 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 6891 SourceLocation Loc); 6892 6893 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 6894 SourceRange R); 6895 6896 /// The scope in which to find allocation functions. 6897 enum AllocationFunctionScope { 6898 /// Only look for allocation functions in the global scope. 6899 AFS_Global, 6900 /// Only look for allocation functions in the scope of the 6901 /// allocated class. 6902 AFS_Class, 6903 /// Look for allocation functions in both the global scope 6904 /// and in the scope of the allocated class. 6905 AFS_Both 6906 }; 6907 6908 /// Finds the overloads of operator new and delete that are appropriate 6909 /// for the allocation. 6910 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 6911 AllocationFunctionScope NewScope, 6912 AllocationFunctionScope DeleteScope, 6913 QualType AllocType, bool IsArray, 6914 bool &PassAlignment, MultiExprArg PlaceArgs, 6915 FunctionDecl *&OperatorNew, 6916 FunctionDecl *&OperatorDelete, 6917 bool Diagnose = true); 6918 void DeclareGlobalNewDelete(); 6919 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 6920 ArrayRef<QualType> Params); 6921 6922 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 6923 DeclarationName Name, FunctionDecl *&Operator, 6924 bool Diagnose = true, bool WantSize = false, 6925 bool WantAligned = false); 6926 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 6927 bool CanProvideSize, 6928 bool Overaligned, 6929 DeclarationName Name); 6930 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, 6931 CXXRecordDecl *RD); 6932 6933 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 6934 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 6935 bool UseGlobal, bool ArrayForm, 6936 Expr *Operand); 6937 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 6938 bool IsDelete, bool CallCanBeVirtual, 6939 bool WarnOnNonAbstractTypes, 6940 SourceLocation DtorLoc); 6941 6942 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 6943 Expr *Operand, SourceLocation RParen); 6944 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 6945 SourceLocation RParen); 6946 6947 /// Parsed one of the type trait support pseudo-functions. 6948 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6949 ArrayRef<ParsedType> Args, 6950 SourceLocation RParenLoc); 6951 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6952 ArrayRef<TypeSourceInfo *> Args, 6953 SourceLocation RParenLoc); 6954 6955 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support 6956 /// pseudo-functions. 6957 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 6958 SourceLocation KWLoc, 6959 ParsedType LhsTy, 6960 Expr *DimExpr, 6961 SourceLocation RParen); 6962 6963 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 6964 SourceLocation KWLoc, 6965 TypeSourceInfo *TSInfo, 6966 Expr *DimExpr, 6967 SourceLocation RParen); 6968 6969 /// ActOnExpressionTrait - Parsed one of the unary type trait support 6970 /// pseudo-functions. 6971 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 6972 SourceLocation KWLoc, 6973 Expr *Queried, 6974 SourceLocation RParen); 6975 6976 ExprResult BuildExpressionTrait(ExpressionTrait OET, 6977 SourceLocation KWLoc, 6978 Expr *Queried, 6979 SourceLocation RParen); 6980 6981 ExprResult ActOnStartCXXMemberReference(Scope *S, 6982 Expr *Base, 6983 SourceLocation OpLoc, 6984 tok::TokenKind OpKind, 6985 ParsedType &ObjectType, 6986 bool &MayBePseudoDestructor); 6987 6988 ExprResult BuildPseudoDestructorExpr(Expr *Base, 6989 SourceLocation OpLoc, 6990 tok::TokenKind OpKind, 6991 const CXXScopeSpec &SS, 6992 TypeSourceInfo *ScopeType, 6993 SourceLocation CCLoc, 6994 SourceLocation TildeLoc, 6995 PseudoDestructorTypeStorage DestroyedType); 6996 6997 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6998 SourceLocation OpLoc, 6999 tok::TokenKind OpKind, 7000 CXXScopeSpec &SS, 7001 UnqualifiedId &FirstTypeName, 7002 SourceLocation CCLoc, 7003 SourceLocation TildeLoc, 7004 UnqualifiedId &SecondTypeName); 7005 7006 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 7007 SourceLocation OpLoc, 7008 tok::TokenKind OpKind, 7009 SourceLocation TildeLoc, 7010 const DeclSpec& DS); 7011 7012 /// MaybeCreateExprWithCleanups - If the current full-expression 7013 /// requires any cleanups, surround it with a ExprWithCleanups node. 7014 /// Otherwise, just returns the passed-in expression. 7015 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 7016 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 7017 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 7018 7019 MaterializeTemporaryExpr * 7020 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 7021 bool BoundToLvalueReference); 7022 ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)7023 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { 7024 return ActOnFinishFullExpr( 7025 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); 7026 } 7027 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 7028 bool DiscardedValue, bool IsConstexpr = false, 7029 bool IsTemplateArgument = false); 7030 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 7031 7032 // Marks SS invalid if it represents an incomplete type. 7033 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 7034 // Complete an enum decl, maybe without a scope spec. 7035 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, 7036 CXXScopeSpec *SS = nullptr); 7037 7038 DeclContext *computeDeclContext(QualType T); 7039 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 7040 bool EnteringContext = false); 7041 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 7042 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 7043 7044 /// The parser has parsed a global nested-name-specifier '::'. 7045 /// 7046 /// \param CCLoc The location of the '::'. 7047 /// 7048 /// \param SS The nested-name-specifier, which will be updated in-place 7049 /// to reflect the parsed nested-name-specifier. 7050 /// 7051 /// \returns true if an error occurred, false otherwise. 7052 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 7053 7054 /// The parser has parsed a '__super' nested-name-specifier. 7055 /// 7056 /// \param SuperLoc The location of the '__super' keyword. 7057 /// 7058 /// \param ColonColonLoc The location of the '::'. 7059 /// 7060 /// \param SS The nested-name-specifier, which will be updated in-place 7061 /// to reflect the parsed nested-name-specifier. 7062 /// 7063 /// \returns true if an error occurred, false otherwise. 7064 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 7065 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 7066 7067 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, 7068 bool *CanCorrect = nullptr); 7069 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 7070 7071 /// Keeps information about an identifier in a nested-name-spec. 7072 /// 7073 struct NestedNameSpecInfo { 7074 /// The type of the object, if we're parsing nested-name-specifier in 7075 /// a member access expression. 7076 ParsedType ObjectType; 7077 7078 /// The identifier preceding the '::'. 7079 IdentifierInfo *Identifier; 7080 7081 /// The location of the identifier. 7082 SourceLocation IdentifierLoc; 7083 7084 /// The location of the '::'. 7085 SourceLocation CCLoc; 7086 7087 /// Creates info object for the most typical case. 7088 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 7089 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) ObjectTypeNestedNameSpecInfo7090 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), 7091 CCLoc(ColonColonLoc) { 7092 } 7093 NestedNameSpecInfoNestedNameSpecInfo7094 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 7095 SourceLocation ColonColonLoc, QualType ObjectType) 7096 : ObjectType(ParsedType::make(ObjectType)), Identifier(II), 7097 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { 7098 } 7099 }; 7100 7101 bool BuildCXXNestedNameSpecifier(Scope *S, 7102 NestedNameSpecInfo &IdInfo, 7103 bool EnteringContext, 7104 CXXScopeSpec &SS, 7105 NamedDecl *ScopeLookupResult, 7106 bool ErrorRecoveryLookup, 7107 bool *IsCorrectedToColon = nullptr, 7108 bool OnlyNamespace = false); 7109 7110 /// The parser has parsed a nested-name-specifier 'identifier::'. 7111 /// 7112 /// \param S The scope in which this nested-name-specifier occurs. 7113 /// 7114 /// \param IdInfo Parser information about an identifier in the 7115 /// nested-name-spec. 7116 /// 7117 /// \param EnteringContext Whether we're entering the context nominated by 7118 /// this nested-name-specifier. 7119 /// 7120 /// \param SS The nested-name-specifier, which is both an input 7121 /// parameter (the nested-name-specifier before this type) and an 7122 /// output parameter (containing the full nested-name-specifier, 7123 /// including this new type). 7124 /// 7125 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 7126 /// are allowed. The bool value pointed by this parameter is set to 'true' 7127 /// if the identifier is treated as if it was followed by ':', not '::'. 7128 /// 7129 /// \param OnlyNamespace If true, only considers namespaces in lookup. 7130 /// 7131 /// \returns true if an error occurred, false otherwise. 7132 bool ActOnCXXNestedNameSpecifier(Scope *S, 7133 NestedNameSpecInfo &IdInfo, 7134 bool EnteringContext, 7135 CXXScopeSpec &SS, 7136 bool *IsCorrectedToColon = nullptr, 7137 bool OnlyNamespace = false); 7138 7139 ExprResult ActOnDecltypeExpression(Expr *E); 7140 7141 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 7142 const DeclSpec &DS, 7143 SourceLocation ColonColonLoc); 7144 7145 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 7146 NestedNameSpecInfo &IdInfo, 7147 bool EnteringContext); 7148 7149 bool IsInvalidSMECallConversion(QualType FromType, QualType ToType); 7150 7151 /// The parser has parsed a nested-name-specifier 7152 /// 'template[opt] template-name < template-args >::'. 7153 /// 7154 /// \param S The scope in which this nested-name-specifier occurs. 7155 /// 7156 /// \param SS The nested-name-specifier, which is both an input 7157 /// parameter (the nested-name-specifier before this type) and an 7158 /// output parameter (containing the full nested-name-specifier, 7159 /// including this new type). 7160 /// 7161 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 7162 /// \param TemplateName the template name. 7163 /// \param TemplateNameLoc The location of the template name. 7164 /// \param LAngleLoc The location of the opening angle bracket ('<'). 7165 /// \param TemplateArgs The template arguments. 7166 /// \param RAngleLoc The location of the closing angle bracket ('>'). 7167 /// \param CCLoc The location of the '::'. 7168 /// 7169 /// \param EnteringContext Whether we're entering the context of the 7170 /// nested-name-specifier. 7171 /// 7172 /// 7173 /// \returns true if an error occurred, false otherwise. 7174 bool ActOnCXXNestedNameSpecifier(Scope *S, 7175 CXXScopeSpec &SS, 7176 SourceLocation TemplateKWLoc, 7177 TemplateTy TemplateName, 7178 SourceLocation TemplateNameLoc, 7179 SourceLocation LAngleLoc, 7180 ASTTemplateArgsPtr TemplateArgs, 7181 SourceLocation RAngleLoc, 7182 SourceLocation CCLoc, 7183 bool EnteringContext); 7184 7185 /// Given a C++ nested-name-specifier, produce an annotation value 7186 /// that the parser can use later to reconstruct the given 7187 /// nested-name-specifier. 7188 /// 7189 /// \param SS A nested-name-specifier. 7190 /// 7191 /// \returns A pointer containing all of the information in the 7192 /// nested-name-specifier \p SS. 7193 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 7194 7195 /// Given an annotation pointer for a nested-name-specifier, restore 7196 /// the nested-name-specifier structure. 7197 /// 7198 /// \param Annotation The annotation pointer, produced by 7199 /// \c SaveNestedNameSpecifierAnnotation(). 7200 /// 7201 /// \param AnnotationRange The source range corresponding to the annotation. 7202 /// 7203 /// \param SS The nested-name-specifier that will be updated with the contents 7204 /// of the annotation pointer. 7205 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 7206 SourceRange AnnotationRange, 7207 CXXScopeSpec &SS); 7208 7209 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 7210 7211 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 7212 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 7213 /// After this method is called, according to [C++ 3.4.3p3], names should be 7214 /// looked up in the declarator-id's scope, until the declarator is parsed and 7215 /// ActOnCXXExitDeclaratorScope is called. 7216 /// The 'SS' should be a non-empty valid CXXScopeSpec. 7217 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 7218 7219 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 7220 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 7221 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 7222 /// Used to indicate that names should revert to being looked up in the 7223 /// defining scope. 7224 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 7225 7226 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 7227 /// initializer for the declaration 'Dcl'. 7228 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 7229 /// static data member of class X, names should be looked up in the scope of 7230 /// class X. 7231 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 7232 7233 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 7234 /// initializer for the declaration 'Dcl'. 7235 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 7236 7237 /// Create a new lambda closure type. 7238 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 7239 TypeSourceInfo *Info, 7240 unsigned LambdaDependencyKind, 7241 LambdaCaptureDefault CaptureDefault); 7242 7243 /// Number lambda for linkage purposes if necessary. 7244 void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, 7245 std::optional<CXXRecordDecl::LambdaNumbering> 7246 NumberingOverride = std::nullopt); 7247 7248 /// Endow the lambda scope info with the relevant properties. 7249 void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, 7250 SourceRange IntroducerRange, 7251 LambdaCaptureDefault CaptureDefault, 7252 SourceLocation CaptureDefaultLoc, bool ExplicitParams, 7253 bool Mutable); 7254 7255 CXXMethodDecl *CreateLambdaCallOperator(SourceRange IntroducerRange, 7256 CXXRecordDecl *Class); 7257 7258 void AddTemplateParametersToLambdaCallOperator( 7259 CXXMethodDecl *CallOperator, CXXRecordDecl *Class, 7260 TemplateParameterList *TemplateParams); 7261 7262 void CompleteLambdaCallOperator( 7263 CXXMethodDecl *Method, SourceLocation LambdaLoc, 7264 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, 7265 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, 7266 StorageClass SC, ArrayRef<ParmVarDecl *> Params, 7267 bool HasExplicitResultType); 7268 7269 void DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method); 7270 7271 /// Perform initialization analysis of the init-capture and perform 7272 /// any implicit conversions such as an lvalue-to-rvalue conversion if 7273 /// not being used to initialize a reference. actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)7274 ParsedType actOnLambdaInitCaptureInitialization( 7275 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 7276 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { 7277 return ParsedType::make(buildLambdaInitCaptureInitialization( 7278 Loc, ByRef, EllipsisLoc, std::nullopt, Id, 7279 InitKind != LambdaCaptureInitKind::CopyInit, Init)); 7280 } 7281 QualType buildLambdaInitCaptureInitialization( 7282 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 7283 std::optional<unsigned> NumExpansions, IdentifierInfo *Id, 7284 bool DirectInit, Expr *&Init); 7285 7286 /// Create a dummy variable within the declcontext of the lambda's 7287 /// call operator, for name lookup purposes for a lambda init capture. 7288 /// 7289 /// CodeGen handles emission of lambda captures, ignoring these dummy 7290 /// variables appropriately. 7291 VarDecl *createLambdaInitCaptureVarDecl( 7292 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, 7293 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx); 7294 7295 /// Add an init-capture to a lambda scope. 7296 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef); 7297 7298 /// Note that we have finished the explicit captures for the 7299 /// given lambda. 7300 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 7301 7302 /// Deduce a block or lambda's return type based on the return 7303 /// statements present in the body. 7304 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 7305 7306 /// Once the Lambdas capture are known, we can start to create the closure, 7307 /// call operator method, and keep track of the captures. 7308 /// We do the capture lookup here, but they are not actually captured until 7309 /// after we know what the qualifiers of the call operator are. 7310 void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, 7311 Scope *CurContext); 7312 7313 /// This is called after parsing the explicit template parameter list 7314 /// on a lambda (if it exists) in C++2a. 7315 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, 7316 SourceLocation LAngleLoc, 7317 ArrayRef<NamedDecl *> TParams, 7318 SourceLocation RAngleLoc, 7319 ExprResult RequiresClause); 7320 7321 void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, 7322 SourceLocation MutableLoc); 7323 7324 void ActOnLambdaClosureParameters( 7325 Scope *LambdaScope, 7326 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo); 7327 7328 /// ActOnStartOfLambdaDefinition - This is called just before we start 7329 /// parsing the body of a lambda; it analyzes the explicit captures and 7330 /// arguments, and sets up various data-structures for the body of the 7331 /// lambda. 7332 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 7333 Declarator &ParamInfo, const DeclSpec &DS); 7334 7335 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 7336 /// is invoked to pop the information about the lambda. 7337 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 7338 bool IsInstantiation = false); 7339 7340 /// ActOnLambdaExpr - This is called when the body of a lambda expression 7341 /// was successfully completed. 7342 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body); 7343 7344 /// Does copying/destroying the captured variable have side effects? 7345 bool CaptureHasSideEffects(const sema::Capture &From); 7346 7347 /// Diagnose if an explicit lambda capture is unused. Returns true if a 7348 /// diagnostic is emitted. 7349 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 7350 const sema::Capture &From); 7351 7352 /// Build a FieldDecl suitable to hold the given capture. 7353 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); 7354 7355 /// Initialize the given capture with a suitable expression. 7356 ExprResult BuildCaptureInit(const sema::Capture &Capture, 7357 SourceLocation ImplicitCaptureLoc, 7358 bool IsOpenMPMapping = false); 7359 7360 /// Complete a lambda-expression having processed and attached the 7361 /// lambda body. 7362 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 7363 sema::LambdaScopeInfo *LSI); 7364 7365 /// Get the return type to use for a lambda's conversion function(s) to 7366 /// function pointer type, given the type of the call operator. 7367 QualType 7368 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, 7369 CallingConv CC); 7370 7371 /// Define the "body" of the conversion from a lambda object to a 7372 /// function pointer. 7373 /// 7374 /// This routine doesn't actually define a sensible body; rather, it fills 7375 /// in the initialization expression needed to copy the lambda object into 7376 /// the block, and IR generation actually generates the real body of the 7377 /// block pointer conversion. 7378 void DefineImplicitLambdaToFunctionPointerConversion( 7379 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 7380 7381 /// Define the "body" of the conversion from a lambda object to a 7382 /// block pointer. 7383 /// 7384 /// This routine doesn't actually define a sensible body; rather, it fills 7385 /// in the initialization expression needed to copy the lambda object into 7386 /// the block, and IR generation actually generates the real body of the 7387 /// block pointer conversion. 7388 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 7389 CXXConversionDecl *Conv); 7390 7391 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 7392 SourceLocation ConvLocation, 7393 CXXConversionDecl *Conv, 7394 Expr *Src); 7395 7396 sema::LambdaScopeInfo *RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator); 7397 7398 class LambdaScopeForCallOperatorInstantiationRAII 7399 : private FunctionScopeRAII { 7400 public: 7401 LambdaScopeForCallOperatorInstantiationRAII( 7402 Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, 7403 LocalInstantiationScope &Scope, 7404 bool ShouldAddDeclsFromParentScope = true); 7405 }; 7406 7407 /// Check whether the given expression is a valid constraint expression. 7408 /// A diagnostic is emitted if it is not, false is returned, and 7409 /// PossibleNonPrimary will be set to true if the failure might be due to a 7410 /// non-primary expression being used as an atomic constraint. 7411 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), 7412 bool *PossibleNonPrimary = nullptr, 7413 bool IsTrailingRequiresClause = false); 7414 7415 private: 7416 /// Caches pairs of template-like decls whose associated constraints were 7417 /// checked for subsumption and whether or not the first's constraints did in 7418 /// fact subsume the second's. 7419 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; 7420 /// Caches the normalized associated constraints of declarations (concepts or 7421 /// constrained declarations). If an error occurred while normalizing the 7422 /// associated constraints of the template or concept, nullptr will be cached 7423 /// here. 7424 llvm::DenseMap<NamedDecl *, NormalizedConstraint *> 7425 NormalizationCache; 7426 7427 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> 7428 SatisfactionCache; 7429 7430 /// Introduce the instantiated local variables into the local 7431 /// instantiation scope. 7432 void addInstantiatedLocalVarsToScope(FunctionDecl *Function, 7433 const FunctionDecl *PatternDecl, 7434 LocalInstantiationScope &Scope); 7435 /// Introduce the instantiated function parameters into the local 7436 /// instantiation scope, and set the parameter names to those used 7437 /// in the template. 7438 bool addInstantiatedParametersToScope( 7439 FunctionDecl *Function, const FunctionDecl *PatternDecl, 7440 LocalInstantiationScope &Scope, 7441 const MultiLevelTemplateArgumentList &TemplateArgs); 7442 7443 /// Introduce the instantiated captures of the lambda into the local 7444 /// instantiation scope. 7445 bool addInstantiatedCapturesToScope( 7446 FunctionDecl *Function, const FunctionDecl *PatternDecl, 7447 LocalInstantiationScope &Scope, 7448 const MultiLevelTemplateArgumentList &TemplateArgs); 7449 7450 /// used by SetupConstraintCheckingTemplateArgumentsAndScope to recursively(in 7451 /// the case of lambdas) set up the LocalInstantiationScope of the current 7452 /// function. 7453 bool SetupConstraintScope( 7454 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, 7455 MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope); 7456 7457 /// Used during constraint checking, sets up the constraint template argument 7458 /// lists, and calls SetupConstraintScope to set up the 7459 /// LocalInstantiationScope to have the proper set of ParVarDecls configured. 7460 std::optional<MultiLevelTemplateArgumentList> 7461 SetupConstraintCheckingTemplateArgumentsAndScope( 7462 FunctionDecl *FD, std::optional<ArrayRef<TemplateArgument>> TemplateArgs, 7463 LocalInstantiationScope &Scope); 7464 7465 private: 7466 // The current stack of constraint satisfactions, so we can exit-early. 7467 using SatisfactionStackEntryTy = 7468 std::pair<const NamedDecl *, llvm::FoldingSetNodeID>; 7469 llvm::SmallVector<SatisfactionStackEntryTy, 10> 7470 SatisfactionStack; 7471 7472 public: PushSatisfactionStackEntry(const NamedDecl * D,const llvm::FoldingSetNodeID & ID)7473 void PushSatisfactionStackEntry(const NamedDecl *D, 7474 const llvm::FoldingSetNodeID &ID) { 7475 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl()); 7476 SatisfactionStack.emplace_back(Can, ID); 7477 } 7478 PopSatisfactionStackEntry()7479 void PopSatisfactionStackEntry() { SatisfactionStack.pop_back(); } 7480 SatisfactionStackContains(const NamedDecl * D,const llvm::FoldingSetNodeID & ID)7481 bool SatisfactionStackContains(const NamedDecl *D, 7482 const llvm::FoldingSetNodeID &ID) const { 7483 const NamedDecl *Can = cast<NamedDecl>(D->getCanonicalDecl()); 7484 return llvm::find(SatisfactionStack, 7485 SatisfactionStackEntryTy{Can, ID}) != 7486 SatisfactionStack.end(); 7487 } 7488 7489 // Resets the current SatisfactionStack for cases where we are instantiating 7490 // constraints as a 'side effect' of normal instantiation in a way that is not 7491 // indicative of recursive definition. 7492 class SatisfactionStackResetRAII { 7493 llvm::SmallVector<SatisfactionStackEntryTy, 10> 7494 BackupSatisfactionStack; 7495 Sema &SemaRef; 7496 7497 public: SatisfactionStackResetRAII(Sema & S)7498 SatisfactionStackResetRAII(Sema &S) : SemaRef(S) { 7499 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack); 7500 } 7501 ~SatisfactionStackResetRAII()7502 ~SatisfactionStackResetRAII() { 7503 SemaRef.SwapSatisfactionStack(BackupSatisfactionStack); 7504 } 7505 }; 7506 SwapSatisfactionStack(llvm::SmallVectorImpl<SatisfactionStackEntryTy> & NewSS)7507 void SwapSatisfactionStack( 7508 llvm::SmallVectorImpl<SatisfactionStackEntryTy> &NewSS) { 7509 SatisfactionStack.swap(NewSS); 7510 } 7511 7512 const NormalizedConstraint * 7513 getNormalizedAssociatedConstraints( 7514 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); 7515 7516 /// \brief Check whether the given declaration's associated constraints are 7517 /// at least as constrained than another declaration's according to the 7518 /// partial ordering of constraints. 7519 /// 7520 /// \param Result If no error occurred, receives the result of true if D1 is 7521 /// at least constrained than D2, and false otherwise. 7522 /// 7523 /// \returns true if an error occurred, false otherwise. 7524 bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef<const Expr *> AC1, 7525 NamedDecl *D2, MutableArrayRef<const Expr *> AC2, 7526 bool &Result); 7527 7528 /// If D1 was not at least as constrained as D2, but would've been if a pair 7529 /// of atomic constraints involved had been declared in a concept and not 7530 /// repeated in two separate places in code. 7531 /// \returns true if such a diagnostic was emitted, false otherwise. 7532 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, 7533 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); 7534 7535 /// \brief Check whether the given list of constraint expressions are 7536 /// satisfied (as if in a 'conjunction') given template arguments. 7537 /// \param Template the template-like entity that triggered the constraints 7538 /// check (either a concept or a constrained entity). 7539 /// \param ConstraintExprs a list of constraint expressions, treated as if 7540 /// they were 'AND'ed together. 7541 /// \param TemplateArgLists the list of template arguments to substitute into 7542 /// the constraint expression. 7543 /// \param TemplateIDRange The source range of the template id that 7544 /// caused the constraints check. 7545 /// \param Satisfaction if true is returned, will contain details of the 7546 /// satisfaction, with enough information to diagnose an unsatisfied 7547 /// expression. 7548 /// \returns true if an error occurred and satisfaction could not be checked, 7549 /// false otherwise. CheckConstraintSatisfaction(const NamedDecl * Template,ArrayRef<const Expr * > ConstraintExprs,const MultiLevelTemplateArgumentList & TemplateArgLists,SourceRange TemplateIDRange,ConstraintSatisfaction & Satisfaction)7550 bool CheckConstraintSatisfaction( 7551 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 7552 const MultiLevelTemplateArgumentList &TemplateArgLists, 7553 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction) { 7554 llvm::SmallVector<Expr *, 4> Converted; 7555 return CheckConstraintSatisfaction(Template, ConstraintExprs, Converted, 7556 TemplateArgLists, TemplateIDRange, 7557 Satisfaction); 7558 } 7559 7560 /// \brief Check whether the given list of constraint expressions are 7561 /// satisfied (as if in a 'conjunction') given template arguments. 7562 /// Additionally, takes an empty list of Expressions which is populated with 7563 /// the instantiated versions of the ConstraintExprs. 7564 /// \param Template the template-like entity that triggered the constraints 7565 /// check (either a concept or a constrained entity). 7566 /// \param ConstraintExprs a list of constraint expressions, treated as if 7567 /// they were 'AND'ed together. 7568 /// \param ConvertedConstraints a out parameter that will get populated with 7569 /// the instantiated version of the ConstraintExprs if we successfully checked 7570 /// satisfaction. 7571 /// \param TemplateArgList the multi-level list of template arguments to 7572 /// substitute into the constraint expression. This should be relative to the 7573 /// top-level (hence multi-level), since we need to instantiate fully at the 7574 /// time of checking. 7575 /// \param TemplateIDRange The source range of the template id that 7576 /// caused the constraints check. 7577 /// \param Satisfaction if true is returned, will contain details of the 7578 /// satisfaction, with enough information to diagnose an unsatisfied 7579 /// expression. 7580 /// \returns true if an error occurred and satisfaction could not be checked, 7581 /// false otherwise. 7582 bool CheckConstraintSatisfaction( 7583 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 7584 llvm::SmallVectorImpl<Expr *> &ConvertedConstraints, 7585 const MultiLevelTemplateArgumentList &TemplateArgList, 7586 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); 7587 7588 /// \brief Check whether the given non-dependent constraint expression is 7589 /// satisfied. Returns false and updates Satisfaction with the satisfaction 7590 /// verdict if successful, emits a diagnostic and returns true if an error 7591 /// occurred and satisfaction could not be determined. 7592 /// 7593 /// \returns true if an error occurred, false otherwise. 7594 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, 7595 ConstraintSatisfaction &Satisfaction); 7596 7597 /// Check whether the given function decl's trailing requires clause is 7598 /// satisfied, if any. Returns false and updates Satisfaction with the 7599 /// satisfaction verdict if successful, emits a diagnostic and returns true if 7600 /// an error occurred and satisfaction could not be determined. 7601 /// 7602 /// \returns true if an error occurred, false otherwise. 7603 bool CheckFunctionConstraints(const FunctionDecl *FD, 7604 ConstraintSatisfaction &Satisfaction, 7605 SourceLocation UsageLoc = SourceLocation(), 7606 bool ForOverloadResolution = false); 7607 7608 /// \brief Ensure that the given template arguments satisfy the constraints 7609 /// associated with the given template, emitting a diagnostic if they do not. 7610 /// 7611 /// \param Template The template to which the template arguments are being 7612 /// provided. 7613 /// 7614 /// \param TemplateArgs The converted, canonicalized template arguments. 7615 /// 7616 /// \param TemplateIDRange The source range of the template id that 7617 /// caused the constraints check. 7618 /// 7619 /// \returns true if the constrains are not satisfied or could not be checked 7620 /// for satisfaction, false if the constraints are satisfied. 7621 bool EnsureTemplateArgumentListConstraints( 7622 TemplateDecl *Template, 7623 const MultiLevelTemplateArgumentList &TemplateArgs, 7624 SourceRange TemplateIDRange); 7625 7626 /// \brief Emit diagnostics explaining why a constraint expression was deemed 7627 /// unsatisfied. 7628 /// \param First whether this is the first time an unsatisfied constraint is 7629 /// diagnosed for this error. 7630 void 7631 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, 7632 bool First = true); 7633 7634 /// \brief Emit diagnostics explaining why a constraint expression was deemed 7635 /// unsatisfied. 7636 void 7637 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, 7638 bool First = true); 7639 7640 // ParseObjCStringLiteral - Parse Objective-C string literals. 7641 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 7642 ArrayRef<Expr *> Strings); 7643 7644 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 7645 7646 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 7647 /// numeric literal expression. Type of the expression will be "NSNumber *" 7648 /// or "id" if NSNumber is unavailable. 7649 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 7650 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 7651 bool Value); 7652 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 7653 7654 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 7655 /// '@' prefixed parenthesized expression. The type of the expression will 7656 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type 7657 /// of ValueType, which is allowed to be a built-in numeric type, "char *", 7658 /// "const char *" or C structure with attribute 'objc_boxable'. 7659 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 7660 7661 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 7662 Expr *IndexExpr, 7663 ObjCMethodDecl *getterMethod, 7664 ObjCMethodDecl *setterMethod); 7665 7666 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 7667 MutableArrayRef<ObjCDictionaryElement> Elements); 7668 7669 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 7670 TypeSourceInfo *EncodedTypeInfo, 7671 SourceLocation RParenLoc); 7672 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 7673 CXXConversionDecl *Method, 7674 bool HadMultipleCandidates); 7675 7676 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 7677 SourceLocation EncodeLoc, 7678 SourceLocation LParenLoc, 7679 ParsedType Ty, 7680 SourceLocation RParenLoc); 7681 7682 /// ParseObjCSelectorExpression - Build selector expression for \@selector 7683 ExprResult ParseObjCSelectorExpression(Selector Sel, 7684 SourceLocation AtLoc, 7685 SourceLocation SelLoc, 7686 SourceLocation LParenLoc, 7687 SourceLocation RParenLoc, 7688 bool WarnMultipleSelectors); 7689 7690 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 7691 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 7692 SourceLocation AtLoc, 7693 SourceLocation ProtoLoc, 7694 SourceLocation LParenLoc, 7695 SourceLocation ProtoIdLoc, 7696 SourceLocation RParenLoc); 7697 7698 //===--------------------------------------------------------------------===// 7699 // C++ Declarations 7700 // 7701 Decl *ActOnStartLinkageSpecification(Scope *S, 7702 SourceLocation ExternLoc, 7703 Expr *LangStr, 7704 SourceLocation LBraceLoc); 7705 Decl *ActOnFinishLinkageSpecification(Scope *S, 7706 Decl *LinkageSpec, 7707 SourceLocation RBraceLoc); 7708 7709 7710 //===--------------------------------------------------------------------===// 7711 // C++ Classes 7712 // 7713 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); 7714 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 7715 const CXXScopeSpec *SS = nullptr); 7716 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 7717 7718 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 7719 SourceLocation ColonLoc, 7720 const ParsedAttributesView &Attrs); 7721 7722 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 7723 Declarator &D, 7724 MultiTemplateParamsArg TemplateParameterLists, 7725 Expr *BitfieldWidth, const VirtSpecifiers &VS, 7726 InClassInitStyle InitStyle); 7727 7728 void ActOnStartCXXInClassMemberInitializer(); 7729 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 7730 SourceLocation EqualLoc, 7731 Expr *Init); 7732 7733 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 7734 Scope *S, 7735 CXXScopeSpec &SS, 7736 IdentifierInfo *MemberOrBase, 7737 ParsedType TemplateTypeTy, 7738 const DeclSpec &DS, 7739 SourceLocation IdLoc, 7740 SourceLocation LParenLoc, 7741 ArrayRef<Expr *> Args, 7742 SourceLocation RParenLoc, 7743 SourceLocation EllipsisLoc); 7744 7745 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 7746 Scope *S, 7747 CXXScopeSpec &SS, 7748 IdentifierInfo *MemberOrBase, 7749 ParsedType TemplateTypeTy, 7750 const DeclSpec &DS, 7751 SourceLocation IdLoc, 7752 Expr *InitList, 7753 SourceLocation EllipsisLoc); 7754 7755 MemInitResult BuildMemInitializer(Decl *ConstructorD, 7756 Scope *S, 7757 CXXScopeSpec &SS, 7758 IdentifierInfo *MemberOrBase, 7759 ParsedType TemplateTypeTy, 7760 const DeclSpec &DS, 7761 SourceLocation IdLoc, 7762 Expr *Init, 7763 SourceLocation EllipsisLoc); 7764 7765 MemInitResult BuildMemberInitializer(ValueDecl *Member, 7766 Expr *Init, 7767 SourceLocation IdLoc); 7768 7769 MemInitResult BuildBaseInitializer(QualType BaseType, 7770 TypeSourceInfo *BaseTInfo, 7771 Expr *Init, 7772 CXXRecordDecl *ClassDecl, 7773 SourceLocation EllipsisLoc); 7774 7775 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 7776 Expr *Init, 7777 CXXRecordDecl *ClassDecl); 7778 7779 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 7780 CXXCtorInitializer *Initializer); 7781 7782 bool SetCtorInitializers( 7783 CXXConstructorDecl *Constructor, bool AnyErrors, 7784 ArrayRef<CXXCtorInitializer *> Initializers = std::nullopt); 7785 7786 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 7787 7788 7789 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 7790 /// mark all the non-trivial destructors of its members and bases as 7791 /// referenced. 7792 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 7793 CXXRecordDecl *Record); 7794 7795 /// Mark destructors of virtual bases of this class referenced. In the Itanium 7796 /// C++ ABI, this is done when emitting a destructor for any non-abstract 7797 /// class. In the Microsoft C++ ABI, this is done any time a class's 7798 /// destructor is referenced. 7799 void MarkVirtualBaseDestructorsReferenced( 7800 SourceLocation Location, CXXRecordDecl *ClassDecl, 7801 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); 7802 7803 /// Do semantic checks to allow the complete destructor variant to be emitted 7804 /// when the destructor is defined in another translation unit. In the Itanium 7805 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they 7806 /// can be emitted in separate TUs. To emit the complete variant, run a subset 7807 /// of the checks performed when emitting a regular destructor. 7808 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 7809 CXXDestructorDecl *Dtor); 7810 7811 /// The list of classes whose vtables have been used within 7812 /// this translation unit, and the source locations at which the 7813 /// first use occurred. 7814 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 7815 7816 /// The list of vtables that are required but have not yet been 7817 /// materialized. 7818 SmallVector<VTableUse, 16> VTableUses; 7819 7820 /// The set of classes whose vtables have been used within 7821 /// this translation unit, and a bit that will be true if the vtable is 7822 /// required to be emitted (otherwise, it should be emitted only if needed 7823 /// by code generation). 7824 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 7825 7826 /// Load any externally-stored vtable uses. 7827 void LoadExternalVTableUses(); 7828 7829 /// Note that the vtable for the given class was used at the 7830 /// given location. 7831 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 7832 bool DefinitionRequired = false); 7833 7834 /// Mark the exception specifications of all virtual member functions 7835 /// in the given class as needed. 7836 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 7837 const CXXRecordDecl *RD); 7838 7839 /// MarkVirtualMembersReferenced - Will mark all members of the given 7840 /// CXXRecordDecl referenced. 7841 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, 7842 bool ConstexprOnly = false); 7843 7844 /// Define all of the vtables that have been used in this 7845 /// translation unit and reference any virtual members used by those 7846 /// vtables. 7847 /// 7848 /// \returns true if any work was done, false otherwise. 7849 bool DefineUsedVTables(); 7850 7851 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 7852 7853 void ActOnMemInitializers(Decl *ConstructorDecl, 7854 SourceLocation ColonLoc, 7855 ArrayRef<CXXCtorInitializer*> MemInits, 7856 bool AnyErrors); 7857 7858 /// Check class-level dllimport/dllexport attribute. The caller must 7859 /// ensure that referenceDLLExportedClassMethods is called some point later 7860 /// when all outer classes of Class are complete. 7861 void checkClassLevelDLLAttribute(CXXRecordDecl *Class); 7862 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); 7863 7864 void referenceDLLExportedClassMethods(); 7865 7866 void propagateDLLAttrToBaseClassTemplate( 7867 CXXRecordDecl *Class, Attr *ClassAttr, 7868 ClassTemplateSpecializationDecl *BaseTemplateSpec, 7869 SourceLocation BaseLoc); 7870 7871 /// Add gsl::Pointer attribute to std::container::iterator 7872 /// \param ND The declaration that introduces the name 7873 /// std::container::iterator. \param UnderlyingRecord The record named by ND. 7874 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); 7875 7876 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. 7877 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); 7878 7879 /// Add [[gsl::Pointer]] attributes for std:: types. 7880 void inferGslPointerAttribute(TypedefNameDecl *TD); 7881 7882 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); 7883 7884 /// Check that the C++ class annoated with "trivial_abi" satisfies all the 7885 /// conditions that are needed for the attribute to have an effect. 7886 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); 7887 7888 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, 7889 Decl *TagDecl, SourceLocation LBrac, 7890 SourceLocation RBrac, 7891 const ParsedAttributesView &AttrList); 7892 void ActOnFinishCXXMemberDecls(); 7893 void ActOnFinishCXXNonNestedClass(); 7894 7895 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 7896 unsigned ActOnReenterTemplateScope(Decl *Template, 7897 llvm::function_ref<Scope *()> EnterScope); 7898 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 7899 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 7900 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 7901 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 7902 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 7903 void ActOnFinishDelayedMemberInitializers(Decl *Record); 7904 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 7905 CachedTokens &Toks); 7906 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 7907 bool IsInsideALocalClassWithinATemplateFunction(); 7908 7909 bool EvaluateStaticAssertMessageAsString(Expr *Message, std::string &Result, 7910 ASTContext &Ctx, 7911 bool ErrorOnInvalidMessage); 7912 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 7913 Expr *AssertExpr, 7914 Expr *AssertMessageExpr, 7915 SourceLocation RParenLoc); 7916 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 7917 Expr *AssertExpr, Expr *AssertMessageExpr, 7918 SourceLocation RParenLoc, bool Failed); 7919 void DiagnoseStaticAssertDetails(const Expr *E); 7920 7921 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 7922 SourceLocation FriendLoc, 7923 TypeSourceInfo *TSInfo); 7924 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 7925 MultiTemplateParamsArg TemplateParams); 7926 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 7927 MultiTemplateParamsArg TemplateParams); 7928 7929 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 7930 StorageClass& SC); 7931 void CheckConstructor(CXXConstructorDecl *Constructor); 7932 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 7933 StorageClass& SC); 7934 bool CheckDestructor(CXXDestructorDecl *Destructor); 7935 void CheckConversionDeclarator(Declarator &D, QualType &R, 7936 StorageClass& SC); 7937 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 7938 bool CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 7939 StorageClass &SC); 7940 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); 7941 7942 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); 7943 7944 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7945 CXXSpecialMember CSM, 7946 SourceLocation DefaultLoc); 7947 void CheckDelayedMemberExceptionSpecs(); 7948 7949 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, 7950 DefaultedComparisonKind DCK); 7951 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 7952 FunctionDecl *Spaceship); 7953 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, 7954 DefaultedComparisonKind DCK); 7955 7956 void CheckExplicitObjectMemberFunction(Declarator &D, DeclarationName Name, 7957 QualType R, bool IsLambda, 7958 DeclContext *DC = nullptr); 7959 void CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D, 7960 DeclarationName Name, QualType R); 7961 void CheckExplicitObjectLambda(Declarator &D); 7962 7963 //===--------------------------------------------------------------------===// 7964 // C++ Derived Classes 7965 // 7966 7967 /// ActOnBaseSpecifier - Parsed a base specifier 7968 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 7969 SourceRange SpecifierRange, 7970 bool Virtual, AccessSpecifier Access, 7971 TypeSourceInfo *TInfo, 7972 SourceLocation EllipsisLoc); 7973 7974 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 7975 const ParsedAttributesView &Attrs, bool Virtual, 7976 AccessSpecifier Access, ParsedType basetype, 7977 SourceLocation BaseLoc, 7978 SourceLocation EllipsisLoc); 7979 7980 bool AttachBaseSpecifiers(CXXRecordDecl *Class, 7981 MutableArrayRef<CXXBaseSpecifier *> Bases); 7982 void ActOnBaseSpecifiers(Decl *ClassDecl, 7983 MutableArrayRef<CXXBaseSpecifier *> Bases); 7984 7985 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); 7986 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 7987 CXXBasePaths &Paths); 7988 7989 // FIXME: I don't like this name. 7990 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 7991 7992 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 7993 SourceLocation Loc, SourceRange Range, 7994 CXXCastPath *BasePath = nullptr, 7995 bool IgnoreAccess = false); 7996 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 7997 unsigned InaccessibleBaseID, 7998 unsigned AmbiguousBaseConvID, 7999 SourceLocation Loc, SourceRange Range, 8000 DeclarationName Name, 8001 CXXCastPath *BasePath, 8002 bool IgnoreAccess = false); 8003 8004 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 8005 8006 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 8007 const CXXMethodDecl *Old); 8008 8009 /// CheckOverridingFunctionReturnType - Checks whether the return types are 8010 /// covariant, according to C++ [class.virtual]p5. 8011 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 8012 const CXXMethodDecl *Old); 8013 8014 // Check that the overriding method has no explicit object parameter. 8015 bool CheckExplicitObjectOverride(CXXMethodDecl *New, 8016 const CXXMethodDecl *Old); 8017 8018 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 8019 /// spec is a subset of base spec. 8020 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 8021 const CXXMethodDecl *Old); 8022 8023 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 8024 8025 /// CheckOverrideControl - Check C++11 override control semantics. 8026 void CheckOverrideControl(NamedDecl *D); 8027 8028 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 8029 /// not used in the declaration of an overriding method. 8030 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); 8031 8032 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 8033 /// overrides a virtual member function marked 'final', according to 8034 /// C++11 [class.virtual]p4. 8035 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 8036 const CXXMethodDecl *Old); 8037 8038 8039 //===--------------------------------------------------------------------===// 8040 // C++ Access Control 8041 // 8042 8043 enum AccessResult { 8044 AR_accessible, 8045 AR_inaccessible, 8046 AR_dependent, 8047 AR_delayed 8048 }; 8049 8050 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 8051 NamedDecl *PrevMemberDecl, 8052 AccessSpecifier LexicalAS); 8053 8054 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 8055 DeclAccessPair FoundDecl); 8056 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 8057 DeclAccessPair FoundDecl); 8058 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 8059 SourceRange PlacementRange, 8060 CXXRecordDecl *NamingClass, 8061 DeclAccessPair FoundDecl, 8062 bool Diagnose = true); 8063 AccessResult CheckConstructorAccess(SourceLocation Loc, 8064 CXXConstructorDecl *D, 8065 DeclAccessPair FoundDecl, 8066 const InitializedEntity &Entity, 8067 bool IsCopyBindingRefToTemp = false); 8068 AccessResult CheckConstructorAccess(SourceLocation Loc, 8069 CXXConstructorDecl *D, 8070 DeclAccessPair FoundDecl, 8071 const InitializedEntity &Entity, 8072 const PartialDiagnostic &PDiag); 8073 AccessResult CheckDestructorAccess(SourceLocation Loc, 8074 CXXDestructorDecl *Dtor, 8075 const PartialDiagnostic &PDiag, 8076 QualType objectType = QualType()); 8077 AccessResult CheckFriendAccess(NamedDecl *D); 8078 AccessResult CheckMemberAccess(SourceLocation UseLoc, 8079 CXXRecordDecl *NamingClass, 8080 DeclAccessPair Found); 8081 AccessResult 8082 CheckStructuredBindingMemberAccess(SourceLocation UseLoc, 8083 CXXRecordDecl *DecomposedClass, 8084 DeclAccessPair Field); 8085 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, 8086 const SourceRange &, 8087 DeclAccessPair FoundDecl); 8088 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 8089 Expr *ObjectExpr, 8090 Expr *ArgExpr, 8091 DeclAccessPair FoundDecl); 8092 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, 8093 ArrayRef<Expr *> ArgExprs, 8094 DeclAccessPair FoundDecl); 8095 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 8096 DeclAccessPair FoundDecl); 8097 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 8098 QualType Base, QualType Derived, 8099 const CXXBasePath &Path, 8100 unsigned DiagID, 8101 bool ForceCheck = false, 8102 bool ForceUnprivileged = false); 8103 void CheckLookupAccess(const LookupResult &R); 8104 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, 8105 QualType BaseType); 8106 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 8107 DeclAccessPair Found, QualType ObjectType, 8108 SourceLocation Loc, 8109 const PartialDiagnostic &Diag); isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)8110 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 8111 DeclAccessPair Found, 8112 QualType ObjectType) { 8113 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, 8114 SourceLocation(), PDiag()); 8115 } 8116 8117 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 8118 const MultiLevelTemplateArgumentList &TemplateArgs); 8119 void PerformDependentDiagnostics(const DeclContext *Pattern, 8120 const MultiLevelTemplateArgumentList &TemplateArgs); 8121 8122 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 8123 8124 /// When true, access checking violations are treated as SFINAE 8125 /// failures rather than hard errors. 8126 bool AccessCheckingSFINAE; 8127 8128 enum AbstractDiagSelID { 8129 AbstractNone = -1, 8130 AbstractReturnType, 8131 AbstractParamType, 8132 AbstractVariableType, 8133 AbstractFieldType, 8134 AbstractIvarType, 8135 AbstractSynthesizedIvarType, 8136 AbstractArrayType 8137 }; 8138 8139 bool isAbstractType(SourceLocation Loc, QualType T); 8140 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 8141 TypeDiagnoser &Diagnoser); 8142 template <typename... Ts> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)8143 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 8144 const Ts &...Args) { 8145 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 8146 return RequireNonAbstractType(Loc, T, Diagnoser); 8147 } 8148 8149 void DiagnoseAbstractType(const CXXRecordDecl *RD); 8150 8151 //===--------------------------------------------------------------------===// 8152 // C++ Overloaded Operators [C++ 13.5] 8153 // 8154 8155 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 8156 8157 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 8158 8159 //===--------------------------------------------------------------------===// 8160 // C++ Templates [C++ 14] 8161 // 8162 void FilterAcceptableTemplateNames(LookupResult &R, 8163 bool AllowFunctionTemplates = true, 8164 bool AllowDependent = true); 8165 bool hasAnyAcceptableTemplateNames(LookupResult &R, 8166 bool AllowFunctionTemplates = true, 8167 bool AllowDependent = true, 8168 bool AllowNonTemplateFunctions = false); 8169 /// Try to interpret the lookup result D as a template-name. 8170 /// 8171 /// \param D A declaration found by name lookup. 8172 /// \param AllowFunctionTemplates Whether function templates should be 8173 /// considered valid results. 8174 /// \param AllowDependent Whether unresolved using declarations (that might 8175 /// name templates) should be considered valid results. 8176 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, 8177 bool AllowFunctionTemplates = true, 8178 bool AllowDependent = true); 8179 8180 enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; 8181 /// Whether and why a template name is required in this lookup. 8182 class RequiredTemplateKind { 8183 public: 8184 /// Template name is required if TemplateKWLoc is valid. 8185 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) TemplateKW(TemplateKWLoc)8186 : TemplateKW(TemplateKWLoc) {} 8187 /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag)8188 RequiredTemplateKind(TemplateNameIsRequiredTag) {} 8189 getTemplateKeywordLoc()8190 SourceLocation getTemplateKeywordLoc() const { 8191 return TemplateKW.value_or(SourceLocation()); 8192 } hasTemplateKeyword()8193 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } isRequired()8194 bool isRequired() const { return TemplateKW != SourceLocation(); } 8195 explicit operator bool() const { return isRequired(); } 8196 8197 private: 8198 std::optional<SourceLocation> TemplateKW; 8199 }; 8200 8201 enum class AssumedTemplateKind { 8202 /// This is not assumed to be a template name. 8203 None, 8204 /// This is assumed to be a template name because lookup found nothing. 8205 FoundNothing, 8206 /// This is assumed to be a template name because lookup found one or more 8207 /// functions (but no function templates). 8208 FoundFunctions, 8209 }; 8210 bool LookupTemplateName( 8211 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, 8212 bool EnteringContext, bool &MemberOfUnknownSpecialization, 8213 RequiredTemplateKind RequiredTemplate = SourceLocation(), 8214 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); 8215 8216 TemplateNameKind isTemplateName(Scope *S, 8217 CXXScopeSpec &SS, 8218 bool hasTemplateKeyword, 8219 const UnqualifiedId &Name, 8220 ParsedType ObjectType, 8221 bool EnteringContext, 8222 TemplateTy &Template, 8223 bool &MemberOfUnknownSpecialization, 8224 bool Disambiguation = false); 8225 8226 /// Try to resolve an undeclared template name as a type template. 8227 /// 8228 /// Sets II to the identifier corresponding to the template name, and updates 8229 /// Name to a corresponding (typo-corrected) type template name and TNK to 8230 /// the corresponding kind, if possible. 8231 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, 8232 TemplateNameKind &TNK, 8233 SourceLocation NameLoc, 8234 IdentifierInfo *&II); 8235 8236 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 8237 SourceLocation NameLoc, 8238 bool Diagnose = true); 8239 8240 /// Determine whether a particular identifier might be the name in a C++1z 8241 /// deduction-guide declaration. 8242 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 8243 SourceLocation NameLoc, CXXScopeSpec &SS, 8244 ParsedTemplateTy *Template = nullptr); 8245 8246 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 8247 SourceLocation IILoc, 8248 Scope *S, 8249 const CXXScopeSpec *SS, 8250 TemplateTy &SuggestedTemplate, 8251 TemplateNameKind &SuggestedKind); 8252 8253 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 8254 NamedDecl *Instantiation, 8255 bool InstantiatedFromMember, 8256 const NamedDecl *Pattern, 8257 const NamedDecl *PatternDef, 8258 TemplateSpecializationKind TSK, 8259 bool Complain = true); 8260 8261 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 8262 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 8263 8264 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, 8265 SourceLocation EllipsisLoc, 8266 SourceLocation KeyLoc, 8267 IdentifierInfo *ParamName, 8268 SourceLocation ParamNameLoc, 8269 unsigned Depth, unsigned Position, 8270 SourceLocation EqualLoc, 8271 ParsedType DefaultArg, bool HasTypeConstraint); 8272 8273 bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint); 8274 8275 bool ActOnTypeConstraint(const CXXScopeSpec &SS, 8276 TemplateIdAnnotation *TypeConstraint, 8277 TemplateTypeParmDecl *ConstrainedParameter, 8278 SourceLocation EllipsisLoc); 8279 bool BuildTypeConstraint(const CXXScopeSpec &SS, 8280 TemplateIdAnnotation *TypeConstraint, 8281 TemplateTypeParmDecl *ConstrainedParameter, 8282 SourceLocation EllipsisLoc, 8283 bool AllowUnexpandedPack); 8284 8285 bool AttachTypeConstraint(NestedNameSpecifierLoc NS, 8286 DeclarationNameInfo NameInfo, 8287 ConceptDecl *NamedConcept, 8288 const TemplateArgumentListInfo *TemplateArgs, 8289 TemplateTypeParmDecl *ConstrainedParameter, 8290 SourceLocation EllipsisLoc); 8291 8292 bool AttachTypeConstraint(AutoTypeLoc TL, 8293 NonTypeTemplateParmDecl *NewConstrainedParm, 8294 NonTypeTemplateParmDecl *OrigConstrainedParm, 8295 SourceLocation EllipsisLoc); 8296 8297 bool RequireStructuralType(QualType T, SourceLocation Loc); 8298 8299 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 8300 SourceLocation Loc); 8301 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 8302 8303 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 8304 unsigned Depth, 8305 unsigned Position, 8306 SourceLocation EqualLoc, 8307 Expr *DefaultArg); 8308 NamedDecl *ActOnTemplateTemplateParameter(Scope *S, 8309 SourceLocation TmpLoc, 8310 TemplateParameterList *Params, 8311 SourceLocation EllipsisLoc, 8312 IdentifierInfo *ParamName, 8313 SourceLocation ParamNameLoc, 8314 unsigned Depth, 8315 unsigned Position, 8316 SourceLocation EqualLoc, 8317 ParsedTemplateArgument DefaultArg); 8318 8319 TemplateParameterList * 8320 ActOnTemplateParameterList(unsigned Depth, 8321 SourceLocation ExportLoc, 8322 SourceLocation TemplateLoc, 8323 SourceLocation LAngleLoc, 8324 ArrayRef<NamedDecl *> Params, 8325 SourceLocation RAngleLoc, 8326 Expr *RequiresClause); 8327 8328 /// The context in which we are checking a template parameter list. 8329 enum TemplateParamListContext { 8330 TPC_ClassTemplate, 8331 TPC_VarTemplate, 8332 TPC_FunctionTemplate, 8333 TPC_ClassTemplateMember, 8334 TPC_FriendClassTemplate, 8335 TPC_FriendFunctionTemplate, 8336 TPC_FriendFunctionTemplateDefinition, 8337 TPC_TypeAliasTemplate 8338 }; 8339 8340 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 8341 TemplateParameterList *OldParams, 8342 TemplateParamListContext TPC, 8343 SkipBodyInfo *SkipBody = nullptr); 8344 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 8345 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 8346 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 8347 ArrayRef<TemplateParameterList *> ParamLists, 8348 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, 8349 bool SuppressDiagnostic = false); 8350 8351 DeclResult CheckClassTemplate( 8352 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 8353 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 8354 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 8355 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 8356 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 8357 TemplateParameterList **OuterTemplateParamLists, 8358 SkipBodyInfo *SkipBody = nullptr); 8359 8360 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, 8361 QualType NTTPType, 8362 SourceLocation Loc); 8363 8364 /// Get a template argument mapping the given template parameter to itself, 8365 /// e.g. for X in \c template<int X>, this would return an expression template 8366 /// argument referencing X. 8367 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, 8368 SourceLocation Location); 8369 8370 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 8371 TemplateArgumentListInfo &Out); 8372 8373 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); 8374 8375 void NoteAllFoundTemplates(TemplateName Name); 8376 8377 QualType CheckTemplateIdType(TemplateName Template, 8378 SourceLocation TemplateLoc, 8379 TemplateArgumentListInfo &TemplateArgs); 8380 8381 TypeResult 8382 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 8383 TemplateTy Template, IdentifierInfo *TemplateII, 8384 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 8385 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, 8386 bool IsCtorOrDtorName = false, bool IsClassName = false, 8387 ImplicitTypenameContext AllowImplicitTypename = 8388 ImplicitTypenameContext::No); 8389 8390 /// Parsed an elaborated-type-specifier that refers to a template-id, 8391 /// such as \c class T::template apply<U>. 8392 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 8393 TypeSpecifierType TagSpec, 8394 SourceLocation TagLoc, 8395 CXXScopeSpec &SS, 8396 SourceLocation TemplateKWLoc, 8397 TemplateTy TemplateD, 8398 SourceLocation TemplateLoc, 8399 SourceLocation LAngleLoc, 8400 ASTTemplateArgsPtr TemplateArgsIn, 8401 SourceLocation RAngleLoc); 8402 8403 DeclResult ActOnVarTemplateSpecialization( 8404 Scope *S, Declarator &D, TypeSourceInfo *DI, 8405 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 8406 StorageClass SC, bool IsPartialSpecialization); 8407 8408 /// Get the specialization of the given variable template corresponding to 8409 /// the specified argument list, or a null-but-valid result if the arguments 8410 /// are dependent. 8411 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 8412 SourceLocation TemplateLoc, 8413 SourceLocation TemplateNameLoc, 8414 const TemplateArgumentListInfo &TemplateArgs); 8415 8416 /// Form a reference to the specialization of the given variable template 8417 /// corresponding to the specified argument list, or a null-but-valid result 8418 /// if the arguments are dependent. 8419 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 8420 const DeclarationNameInfo &NameInfo, 8421 VarTemplateDecl *Template, 8422 SourceLocation TemplateLoc, 8423 const TemplateArgumentListInfo *TemplateArgs); 8424 8425 ExprResult 8426 CheckConceptTemplateId(const CXXScopeSpec &SS, 8427 SourceLocation TemplateKWLoc, 8428 const DeclarationNameInfo &ConceptNameInfo, 8429 NamedDecl *FoundDecl, ConceptDecl *NamedConcept, 8430 const TemplateArgumentListInfo *TemplateArgs); 8431 8432 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); 8433 8434 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 8435 SourceLocation TemplateKWLoc, 8436 LookupResult &R, 8437 bool RequiresADL, 8438 const TemplateArgumentListInfo *TemplateArgs); 8439 8440 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 8441 SourceLocation TemplateKWLoc, 8442 const DeclarationNameInfo &NameInfo, 8443 const TemplateArgumentListInfo *TemplateArgs); 8444 8445 TemplateNameKind ActOnTemplateName( 8446 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 8447 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, 8448 TemplateTy &Template, bool AllowInjectedClassName = false); 8449 8450 DeclResult ActOnClassTemplateSpecialization( 8451 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 8452 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 8453 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 8454 MultiTemplateParamsArg TemplateParameterLists, 8455 SkipBodyInfo *SkipBody = nullptr); 8456 8457 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, 8458 TemplateDecl *PrimaryTemplate, 8459 unsigned NumExplicitArgs, 8460 ArrayRef<TemplateArgument> Args); 8461 void CheckTemplatePartialSpecialization( 8462 ClassTemplatePartialSpecializationDecl *Partial); 8463 void CheckTemplatePartialSpecialization( 8464 VarTemplatePartialSpecializationDecl *Partial); 8465 8466 Decl *ActOnTemplateDeclarator(Scope *S, 8467 MultiTemplateParamsArg TemplateParameterLists, 8468 Declarator &D); 8469 8470 bool 8471 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 8472 TemplateSpecializationKind NewTSK, 8473 NamedDecl *PrevDecl, 8474 TemplateSpecializationKind PrevTSK, 8475 SourceLocation PrevPtOfInstantiation, 8476 bool &SuppressNew); 8477 8478 bool CheckDependentFunctionTemplateSpecialization( 8479 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, 8480 LookupResult &Previous); 8481 8482 bool CheckFunctionTemplateSpecialization( 8483 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 8484 LookupResult &Previous, bool QualifiedFriend = false); 8485 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 8486 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 8487 8488 DeclResult ActOnExplicitInstantiation( 8489 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 8490 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 8491 TemplateTy Template, SourceLocation TemplateNameLoc, 8492 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, 8493 SourceLocation RAngleLoc, const ParsedAttributesView &Attr); 8494 8495 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 8496 SourceLocation TemplateLoc, 8497 unsigned TagSpec, SourceLocation KWLoc, 8498 CXXScopeSpec &SS, IdentifierInfo *Name, 8499 SourceLocation NameLoc, 8500 const ParsedAttributesView &Attr); 8501 8502 DeclResult ActOnExplicitInstantiation(Scope *S, 8503 SourceLocation ExternLoc, 8504 SourceLocation TemplateLoc, 8505 Declarator &D); 8506 8507 TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable( 8508 TemplateDecl *Template, SourceLocation TemplateLoc, 8509 SourceLocation RAngleLoc, Decl *Param, 8510 ArrayRef<TemplateArgument> SugaredConverted, 8511 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg); 8512 8513 SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const; 8514 8515 /// Specifies the context in which a particular template 8516 /// argument is being checked. 8517 enum CheckTemplateArgumentKind { 8518 /// The template argument was specified in the code or was 8519 /// instantiated with some deduced template arguments. 8520 CTAK_Specified, 8521 8522 /// The template argument was deduced via template argument 8523 /// deduction. 8524 CTAK_Deduced, 8525 8526 /// The template argument was deduced from an array bound 8527 /// via template argument deduction. 8528 CTAK_DeducedFromArrayBound 8529 }; 8530 8531 bool 8532 CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, 8533 NamedDecl *Template, SourceLocation TemplateLoc, 8534 SourceLocation RAngleLoc, unsigned ArgumentPackIndex, 8535 SmallVectorImpl<TemplateArgument> &SugaredConverted, 8536 SmallVectorImpl<TemplateArgument> &CanonicalConverted, 8537 CheckTemplateArgumentKind CTAK); 8538 8539 /// Check that the given template arguments can be provided to 8540 /// the given template, converting the arguments along the way. 8541 /// 8542 /// \param Template The template to which the template arguments are being 8543 /// provided. 8544 /// 8545 /// \param TemplateLoc The location of the template name in the source. 8546 /// 8547 /// \param TemplateArgs The list of template arguments. If the template is 8548 /// a template template parameter, this function may extend the set of 8549 /// template arguments to also include substituted, defaulted template 8550 /// arguments. 8551 /// 8552 /// \param PartialTemplateArgs True if the list of template arguments is 8553 /// intentionally partial, e.g., because we're checking just the initial 8554 /// set of template arguments. 8555 /// 8556 /// \param Converted Will receive the converted, canonicalized template 8557 /// arguments. 8558 /// 8559 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to 8560 /// contain the converted forms of the template arguments as written. 8561 /// Otherwise, \p TemplateArgs will not be modified. 8562 /// 8563 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will 8564 /// receive true if the cause for the error is the associated constraints of 8565 /// the template not being satisfied by the template arguments. 8566 /// 8567 /// \returns true if an error occurred, false otherwise. 8568 bool CheckTemplateArgumentList( 8569 TemplateDecl *Template, SourceLocation TemplateLoc, 8570 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, 8571 SmallVectorImpl<TemplateArgument> &SugaredConverted, 8572 SmallVectorImpl<TemplateArgument> &CanonicalConverted, 8573 bool UpdateArgsWithConversions = true, 8574 bool *ConstraintsNotSatisfied = nullptr); 8575 8576 bool CheckTemplateTypeArgument( 8577 TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, 8578 SmallVectorImpl<TemplateArgument> &SugaredConverted, 8579 SmallVectorImpl<TemplateArgument> &CanonicalConverted); 8580 8581 bool CheckTemplateArgument(TypeSourceInfo *Arg); 8582 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 8583 QualType InstantiatedParamType, Expr *Arg, 8584 TemplateArgument &SugaredConverted, 8585 TemplateArgument &CanonicalConverted, 8586 CheckTemplateArgumentKind CTAK); 8587 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 8588 TemplateParameterList *Params, 8589 TemplateArgumentLoc &Arg); 8590 8591 void NoteTemplateLocation(const NamedDecl &Decl, 8592 std::optional<SourceRange> ParamRange = {}); 8593 void NoteTemplateParameterLocation(const NamedDecl &Decl); 8594 8595 ExprResult 8596 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 8597 QualType ParamType, 8598 SourceLocation Loc); 8599 ExprResult 8600 BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, 8601 SourceLocation Loc); 8602 8603 /// Enumeration describing how template parameter lists are compared 8604 /// for equality. 8605 enum TemplateParameterListEqualKind { 8606 /// We are matching the template parameter lists of two templates 8607 /// that might be redeclarations. 8608 /// 8609 /// \code 8610 /// template<typename T> struct X; 8611 /// template<typename T> struct X; 8612 /// \endcode 8613 TPL_TemplateMatch, 8614 8615 /// We are matching the template parameter lists of two template 8616 /// template parameters as part of matching the template parameter lists 8617 /// of two templates that might be redeclarations. 8618 /// 8619 /// \code 8620 /// template<template<int I> class TT> struct X; 8621 /// template<template<int Value> class Other> struct X; 8622 /// \endcode 8623 TPL_TemplateTemplateParmMatch, 8624 8625 /// We are matching the template parameter lists of a template 8626 /// template argument against the template parameter lists of a template 8627 /// template parameter. 8628 /// 8629 /// \code 8630 /// template<template<int Value> class Metafun> struct X; 8631 /// template<int Value> struct integer_c; 8632 /// X<integer_c> xic; 8633 /// \endcode 8634 TPL_TemplateTemplateArgumentMatch, 8635 8636 /// We are determining whether the template-parameters are equivalent 8637 /// according to C++ [temp.over.link]/6. This comparison does not consider 8638 /// constraints. 8639 /// 8640 /// \code 8641 /// template<C1 T> void f(T); 8642 /// template<C2 T> void f(T); 8643 /// \endcode 8644 TPL_TemplateParamsEquivalent, 8645 }; 8646 8647 // A struct to represent the 'new' declaration, which is either itself just 8648 // the named decl, or the important information we need about it in order to 8649 // do constraint comparisons. 8650 class TemplateCompareNewDeclInfo { 8651 const NamedDecl *ND = nullptr; 8652 const DeclContext *DC = nullptr; 8653 const DeclContext *LexicalDC = nullptr; 8654 SourceLocation Loc; 8655 8656 public: TemplateCompareNewDeclInfo(const NamedDecl * ND)8657 TemplateCompareNewDeclInfo(const NamedDecl *ND) : ND(ND) {} TemplateCompareNewDeclInfo(const DeclContext * DeclCtx,const DeclContext * LexicalDeclCtx,SourceLocation Loc)8658 TemplateCompareNewDeclInfo(const DeclContext *DeclCtx, 8659 const DeclContext *LexicalDeclCtx, 8660 SourceLocation Loc) 8661 8662 : DC(DeclCtx), LexicalDC(LexicalDeclCtx), Loc(Loc) { 8663 assert(DC && LexicalDC && 8664 "Constructor only for cases where we have the information to put " 8665 "in here"); 8666 } 8667 8668 // If this was constructed with no information, we cannot do substitution 8669 // for constraint comparison, so make sure we can check that. isInvalid()8670 bool isInvalid() const { return !ND && !DC; } 8671 getDecl()8672 const NamedDecl *getDecl() const { return ND; } 8673 ContainsDecl(const NamedDecl * ND)8674 bool ContainsDecl(const NamedDecl *ND) const { return this->ND == ND; } 8675 getLexicalDeclContext()8676 const DeclContext *getLexicalDeclContext() const { 8677 return ND ? ND->getLexicalDeclContext() : LexicalDC; 8678 } 8679 getDeclContext()8680 const DeclContext *getDeclContext() const { 8681 return ND ? ND->getDeclContext() : DC; 8682 } 8683 getLocation()8684 SourceLocation getLocation() const { return ND ? ND->getLocation() : Loc; } 8685 }; 8686 8687 bool TemplateParameterListsAreEqual( 8688 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, 8689 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, 8690 TemplateParameterListEqualKind Kind, 8691 SourceLocation TemplateArgLoc = SourceLocation()); 8692 8693 bool TemplateParameterListsAreEqual( 8694 TemplateParameterList *New, TemplateParameterList *Old, bool Complain, 8695 TemplateParameterListEqualKind Kind, 8696 SourceLocation TemplateArgLoc = SourceLocation()) { 8697 return TemplateParameterListsAreEqual(nullptr, New, nullptr, Old, Complain, 8698 Kind, TemplateArgLoc); 8699 } 8700 8701 // Calculates whether two constraint expressions are equal irrespective of a 8702 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and 8703 // 'New', which are the "source" of the constraint, since this is necessary 8704 // for figuring out the relative 'depth' of the constraint. The depth of the 8705 // 'primary template' and the 'instantiated from' templates aren't necessarily 8706 // the same, such as a case when one is a 'friend' defined in a class. 8707 bool AreConstraintExpressionsEqual(const NamedDecl *Old, 8708 const Expr *OldConstr, 8709 const TemplateCompareNewDeclInfo &New, 8710 const Expr *NewConstr); 8711 8712 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 8713 8714 /// Called when the parser has parsed a C++ typename 8715 /// specifier, e.g., "typename T::type". 8716 /// 8717 /// \param S The scope in which this typename type occurs. 8718 /// \param TypenameLoc the location of the 'typename' keyword 8719 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 8720 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 8721 /// \param IdLoc the location of the identifier. 8722 /// \param IsImplicitTypename context where T::type refers to a type. 8723 TypeResult ActOnTypenameType( 8724 Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, 8725 const IdentifierInfo &II, SourceLocation IdLoc, 8726 ImplicitTypenameContext IsImplicitTypename = ImplicitTypenameContext::No); 8727 8728 /// Called when the parser has parsed a C++ typename 8729 /// specifier that ends in a template-id, e.g., 8730 /// "typename MetaFun::template apply<T1, T2>". 8731 /// 8732 /// \param S The scope in which this typename type occurs. 8733 /// \param TypenameLoc the location of the 'typename' keyword 8734 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 8735 /// \param TemplateLoc the location of the 'template' keyword, if any. 8736 /// \param TemplateName The template name. 8737 /// \param TemplateII The identifier used to name the template. 8738 /// \param TemplateIILoc The location of the template name. 8739 /// \param LAngleLoc The location of the opening angle bracket ('<'). 8740 /// \param TemplateArgs The template arguments. 8741 /// \param RAngleLoc The location of the closing angle bracket ('>'). 8742 TypeResult 8743 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 8744 const CXXScopeSpec &SS, 8745 SourceLocation TemplateLoc, 8746 TemplateTy TemplateName, 8747 IdentifierInfo *TemplateII, 8748 SourceLocation TemplateIILoc, 8749 SourceLocation LAngleLoc, 8750 ASTTemplateArgsPtr TemplateArgs, 8751 SourceLocation RAngleLoc); 8752 8753 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 8754 SourceLocation KeywordLoc, 8755 NestedNameSpecifierLoc QualifierLoc, 8756 const IdentifierInfo &II, 8757 SourceLocation IILoc, 8758 TypeSourceInfo **TSI, 8759 bool DeducedTSTContext); 8760 8761 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 8762 SourceLocation KeywordLoc, 8763 NestedNameSpecifierLoc QualifierLoc, 8764 const IdentifierInfo &II, 8765 SourceLocation IILoc, 8766 bool DeducedTSTContext = true); 8767 8768 8769 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 8770 SourceLocation Loc, 8771 DeclarationName Name); 8772 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 8773 8774 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 8775 bool RebuildTemplateParamsInCurrentInstantiation( 8776 TemplateParameterList *Params); 8777 8778 std::string 8779 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 8780 const TemplateArgumentList &Args); 8781 8782 std::string 8783 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 8784 const TemplateArgument *Args, 8785 unsigned NumArgs); 8786 8787 //===--------------------------------------------------------------------===// 8788 // C++ Concepts 8789 //===--------------------------------------------------------------------===// 8790 Decl *ActOnConceptDefinition( 8791 Scope *S, MultiTemplateParamsArg TemplateParameterLists, 8792 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); 8793 8794 void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, 8795 bool &AddToScope); 8796 8797 RequiresExprBodyDecl * 8798 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 8799 ArrayRef<ParmVarDecl *> LocalParameters, 8800 Scope *BodyScope); 8801 void ActOnFinishRequiresExpr(); 8802 concepts::Requirement *ActOnSimpleRequirement(Expr *E); 8803 concepts::Requirement *ActOnTypeRequirement( 8804 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, 8805 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); 8806 concepts::Requirement *ActOnCompoundRequirement(Expr *E, 8807 SourceLocation NoexceptLoc); 8808 concepts::Requirement * 8809 ActOnCompoundRequirement( 8810 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 8811 TemplateIdAnnotation *TypeConstraint, unsigned Depth); 8812 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); 8813 concepts::ExprRequirement * 8814 BuildExprRequirement( 8815 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, 8816 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 8817 concepts::ExprRequirement * 8818 BuildExprRequirement( 8819 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, 8820 bool IsSatisfied, SourceLocation NoexceptLoc, 8821 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 8822 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); 8823 concepts::TypeRequirement * 8824 BuildTypeRequirement( 8825 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 8826 concepts::NestedRequirement *BuildNestedRequirement(Expr *E); 8827 concepts::NestedRequirement * 8828 BuildNestedRequirement(StringRef InvalidConstraintEntity, 8829 const ASTConstraintSatisfaction &Satisfaction); 8830 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, 8831 RequiresExprBodyDecl *Body, 8832 SourceLocation LParenLoc, 8833 ArrayRef<ParmVarDecl *> LocalParameters, 8834 SourceLocation RParenLoc, 8835 ArrayRef<concepts::Requirement *> Requirements, 8836 SourceLocation ClosingBraceLoc); 8837 8838 //===--------------------------------------------------------------------===// 8839 // C++ Variadic Templates (C++0x [temp.variadic]) 8840 //===--------------------------------------------------------------------===// 8841 8842 /// Determine whether an unexpanded parameter pack might be permitted in this 8843 /// location. Useful for error recovery. 8844 bool isUnexpandedParameterPackPermitted(); 8845 8846 /// The context in which an unexpanded parameter pack is 8847 /// being diagnosed. 8848 /// 8849 /// Note that the values of this enumeration line up with the first 8850 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 8851 enum UnexpandedParameterPackContext { 8852 /// An arbitrary expression. 8853 UPPC_Expression = 0, 8854 8855 /// The base type of a class type. 8856 UPPC_BaseType, 8857 8858 /// The type of an arbitrary declaration. 8859 UPPC_DeclarationType, 8860 8861 /// The type of a data member. 8862 UPPC_DataMemberType, 8863 8864 /// The size of a bit-field. 8865 UPPC_BitFieldWidth, 8866 8867 /// The expression in a static assertion. 8868 UPPC_StaticAssertExpression, 8869 8870 /// The fixed underlying type of an enumeration. 8871 UPPC_FixedUnderlyingType, 8872 8873 /// The enumerator value. 8874 UPPC_EnumeratorValue, 8875 8876 /// A using declaration. 8877 UPPC_UsingDeclaration, 8878 8879 /// A friend declaration. 8880 UPPC_FriendDeclaration, 8881 8882 /// A declaration qualifier. 8883 UPPC_DeclarationQualifier, 8884 8885 /// An initializer. 8886 UPPC_Initializer, 8887 8888 /// A default argument. 8889 UPPC_DefaultArgument, 8890 8891 /// The type of a non-type template parameter. 8892 UPPC_NonTypeTemplateParameterType, 8893 8894 /// The type of an exception. 8895 UPPC_ExceptionType, 8896 8897 /// Explicit specialization. 8898 UPPC_ExplicitSpecialization, 8899 8900 /// Partial specialization. 8901 UPPC_PartialSpecialization, 8902 8903 /// Microsoft __if_exists. 8904 UPPC_IfExists, 8905 8906 /// Microsoft __if_not_exists. 8907 UPPC_IfNotExists, 8908 8909 /// Lambda expression. 8910 UPPC_Lambda, 8911 8912 /// Block expression. 8913 UPPC_Block, 8914 8915 /// A type constraint. 8916 UPPC_TypeConstraint, 8917 8918 // A requirement in a requires-expression. 8919 UPPC_Requirement, 8920 8921 // A requires-clause. 8922 UPPC_RequiresClause, 8923 }; 8924 8925 /// Diagnose unexpanded parameter packs. 8926 /// 8927 /// \param Loc The location at which we should emit the diagnostic. 8928 /// 8929 /// \param UPPC The context in which we are diagnosing unexpanded 8930 /// parameter packs. 8931 /// 8932 /// \param Unexpanded the set of unexpanded parameter packs. 8933 /// 8934 /// \returns true if an error occurred, false otherwise. 8935 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 8936 UnexpandedParameterPackContext UPPC, 8937 ArrayRef<UnexpandedParameterPack> Unexpanded); 8938 8939 /// If the given type contains an unexpanded parameter pack, 8940 /// diagnose the error. 8941 /// 8942 /// \param Loc The source location where a diagnostc should be emitted. 8943 /// 8944 /// \param T The type that is being checked for unexpanded parameter 8945 /// packs. 8946 /// 8947 /// \returns true if an error occurred, false otherwise. 8948 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 8949 UnexpandedParameterPackContext UPPC); 8950 8951 /// If the given expression contains an unexpanded parameter 8952 /// pack, diagnose the error. 8953 /// 8954 /// \param E The expression that is being checked for unexpanded 8955 /// parameter packs. 8956 /// 8957 /// \returns true if an error occurred, false otherwise. 8958 bool DiagnoseUnexpandedParameterPack(Expr *E, 8959 UnexpandedParameterPackContext UPPC = UPPC_Expression); 8960 8961 /// If the given requirees-expression contains an unexpanded reference to one 8962 /// of its own parameter packs, diagnose the error. 8963 /// 8964 /// \param RE The requiress-expression that is being checked for unexpanded 8965 /// parameter packs. 8966 /// 8967 /// \returns true if an error occurred, false otherwise. 8968 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); 8969 8970 /// If the given nested-name-specifier contains an unexpanded 8971 /// parameter pack, diagnose the error. 8972 /// 8973 /// \param SS The nested-name-specifier that is being checked for 8974 /// unexpanded parameter packs. 8975 /// 8976 /// \returns true if an error occurred, false otherwise. 8977 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 8978 UnexpandedParameterPackContext UPPC); 8979 8980 /// If the given name contains an unexpanded parameter pack, 8981 /// diagnose the error. 8982 /// 8983 /// \param NameInfo The name (with source location information) that 8984 /// is being checked for unexpanded parameter packs. 8985 /// 8986 /// \returns true if an error occurred, false otherwise. 8987 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 8988 UnexpandedParameterPackContext UPPC); 8989 8990 /// If the given template name contains an unexpanded parameter pack, 8991 /// diagnose the error. 8992 /// 8993 /// \param Loc The location of the template name. 8994 /// 8995 /// \param Template The template name that is being checked for unexpanded 8996 /// parameter packs. 8997 /// 8998 /// \returns true if an error occurred, false otherwise. 8999 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 9000 TemplateName Template, 9001 UnexpandedParameterPackContext UPPC); 9002 9003 /// If the given template argument contains an unexpanded parameter 9004 /// pack, diagnose the error. 9005 /// 9006 /// \param Arg The template argument that is being checked for unexpanded 9007 /// parameter packs. 9008 /// 9009 /// \returns true if an error occurred, false otherwise. 9010 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 9011 UnexpandedParameterPackContext UPPC); 9012 9013 /// Collect the set of unexpanded parameter packs within the given 9014 /// template argument. 9015 /// 9016 /// \param Arg The template argument that will be traversed to find 9017 /// unexpanded parameter packs. 9018 void collectUnexpandedParameterPacks(TemplateArgument Arg, 9019 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 9020 9021 /// Collect the set of unexpanded parameter packs within the given 9022 /// template argument. 9023 /// 9024 /// \param Arg The template argument that will be traversed to find 9025 /// unexpanded parameter packs. 9026 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 9027 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 9028 9029 /// Collect the set of unexpanded parameter packs within the given 9030 /// type. 9031 /// 9032 /// \param T The type that will be traversed to find 9033 /// unexpanded parameter packs. 9034 void collectUnexpandedParameterPacks(QualType T, 9035 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 9036 9037 /// Collect the set of unexpanded parameter packs within the given 9038 /// type. 9039 /// 9040 /// \param TL The type that will be traversed to find 9041 /// unexpanded parameter packs. 9042 void collectUnexpandedParameterPacks(TypeLoc TL, 9043 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 9044 9045 /// Collect the set of unexpanded parameter packs within the given 9046 /// nested-name-specifier. 9047 /// 9048 /// \param NNS The nested-name-specifier that will be traversed to find 9049 /// unexpanded parameter packs. 9050 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, 9051 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 9052 9053 /// Collect the set of unexpanded parameter packs within the given 9054 /// name. 9055 /// 9056 /// \param NameInfo The name that will be traversed to find 9057 /// unexpanded parameter packs. 9058 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 9059 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 9060 9061 /// Invoked when parsing a template argument followed by an 9062 /// ellipsis, which creates a pack expansion. 9063 /// 9064 /// \param Arg The template argument preceding the ellipsis, which 9065 /// may already be invalid. 9066 /// 9067 /// \param EllipsisLoc The location of the ellipsis. 9068 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 9069 SourceLocation EllipsisLoc); 9070 9071 /// Invoked when parsing a type followed by an ellipsis, which 9072 /// creates a pack expansion. 9073 /// 9074 /// \param Type The type preceding the ellipsis, which will become 9075 /// the pattern of the pack expansion. 9076 /// 9077 /// \param EllipsisLoc The location of the ellipsis. 9078 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 9079 9080 /// Construct a pack expansion type from the pattern of the pack 9081 /// expansion. 9082 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 9083 SourceLocation EllipsisLoc, 9084 std::optional<unsigned> NumExpansions); 9085 9086 /// Construct a pack expansion type from the pattern of the pack 9087 /// expansion. 9088 QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, 9089 SourceLocation EllipsisLoc, 9090 std::optional<unsigned> NumExpansions); 9091 9092 /// Invoked when parsing an expression followed by an ellipsis, which 9093 /// creates a pack expansion. 9094 /// 9095 /// \param Pattern The expression preceding the ellipsis, which will become 9096 /// the pattern of the pack expansion. 9097 /// 9098 /// \param EllipsisLoc The location of the ellipsis. 9099 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 9100 9101 /// Invoked when parsing an expression followed by an ellipsis, which 9102 /// creates a pack expansion. 9103 /// 9104 /// \param Pattern The expression preceding the ellipsis, which will become 9105 /// the pattern of the pack expansion. 9106 /// 9107 /// \param EllipsisLoc The location of the ellipsis. 9108 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 9109 std::optional<unsigned> NumExpansions); 9110 9111 /// Determine whether we could expand a pack expansion with the 9112 /// given set of parameter packs into separate arguments by repeatedly 9113 /// transforming the pattern. 9114 /// 9115 /// \param EllipsisLoc The location of the ellipsis that identifies the 9116 /// pack expansion. 9117 /// 9118 /// \param PatternRange The source range that covers the entire pattern of 9119 /// the pack expansion. 9120 /// 9121 /// \param Unexpanded The set of unexpanded parameter packs within the 9122 /// pattern. 9123 /// 9124 /// \param ShouldExpand Will be set to \c true if the transformer should 9125 /// expand the corresponding pack expansions into separate arguments. When 9126 /// set, \c NumExpansions must also be set. 9127 /// 9128 /// \param RetainExpansion Whether the caller should add an unexpanded 9129 /// pack expansion after all of the expanded arguments. This is used 9130 /// when extending explicitly-specified template argument packs per 9131 /// C++0x [temp.arg.explicit]p9. 9132 /// 9133 /// \param NumExpansions The number of separate arguments that will be in 9134 /// the expanded form of the corresponding pack expansion. This is both an 9135 /// input and an output parameter, which can be set by the caller if the 9136 /// number of expansions is known a priori (e.g., due to a prior substitution) 9137 /// and will be set by the callee when the number of expansions is known. 9138 /// The callee must set this value when \c ShouldExpand is \c true; it may 9139 /// set this value in other cases. 9140 /// 9141 /// \returns true if an error occurred (e.g., because the parameter packs 9142 /// are to be instantiated with arguments of different lengths), false 9143 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 9144 /// must be set. 9145 bool CheckParameterPacksForExpansion( 9146 SourceLocation EllipsisLoc, SourceRange PatternRange, 9147 ArrayRef<UnexpandedParameterPack> Unexpanded, 9148 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, 9149 bool &RetainExpansion, std::optional<unsigned> &NumExpansions); 9150 9151 /// Determine the number of arguments in the given pack expansion 9152 /// type. 9153 /// 9154 /// This routine assumes that the number of arguments in the expansion is 9155 /// consistent across all of the unexpanded parameter packs in its pattern. 9156 /// 9157 /// Returns an empty Optional if the type can't be expanded. 9158 std::optional<unsigned> getNumArgumentsInExpansion( 9159 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); 9160 9161 /// Determine whether the given declarator contains any unexpanded 9162 /// parameter packs. 9163 /// 9164 /// This routine is used by the parser to disambiguate function declarators 9165 /// with an ellipsis prior to the ')', e.g., 9166 /// 9167 /// \code 9168 /// void f(T...); 9169 /// \endcode 9170 /// 9171 /// To determine whether we have an (unnamed) function parameter pack or 9172 /// a variadic function. 9173 /// 9174 /// \returns true if the declarator contains any unexpanded parameter packs, 9175 /// false otherwise. 9176 bool containsUnexpandedParameterPacks(Declarator &D); 9177 9178 /// Returns the pattern of the pack expansion for a template argument. 9179 /// 9180 /// \param OrigLoc The template argument to expand. 9181 /// 9182 /// \param Ellipsis Will be set to the location of the ellipsis. 9183 /// 9184 /// \param NumExpansions Will be set to the number of expansions that will 9185 /// be generated from this pack expansion, if known a priori. 9186 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 9187 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, 9188 std::optional<unsigned> &NumExpansions) const; 9189 9190 /// Given a template argument that contains an unexpanded parameter pack, but 9191 /// which has already been substituted, attempt to determine the number of 9192 /// elements that will be produced once this argument is fully-expanded. 9193 /// 9194 /// This is intended for use when transforming 'sizeof...(Arg)' in order to 9195 /// avoid actually expanding the pack where possible. 9196 std::optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); 9197 9198 //===--------------------------------------------------------------------===// 9199 // C++ Template Argument Deduction (C++ [temp.deduct]) 9200 //===--------------------------------------------------------------------===// 9201 9202 /// Adjust the type \p ArgFunctionType to match the calling convention, 9203 /// noreturn, and optionally the exception specification of \p FunctionType. 9204 /// Deduction often wants to ignore these properties when matching function 9205 /// types. 9206 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, 9207 bool AdjustExceptionSpec = false); 9208 9209 /// Describes the result of template argument deduction. 9210 /// 9211 /// The TemplateDeductionResult enumeration describes the result of 9212 /// template argument deduction, as returned from 9213 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 9214 /// structure provides additional information about the results of 9215 /// template argument deduction, e.g., the deduced template argument 9216 /// list (if successful) or the specific template parameters or 9217 /// deduced arguments that were involved in the failure. 9218 enum TemplateDeductionResult { 9219 /// Template argument deduction was successful. 9220 TDK_Success = 0, 9221 /// The declaration was invalid; do nothing. 9222 TDK_Invalid, 9223 /// Template argument deduction exceeded the maximum template 9224 /// instantiation depth (which has already been diagnosed). 9225 TDK_InstantiationDepth, 9226 /// Template argument deduction did not deduce a value 9227 /// for every template parameter. 9228 TDK_Incomplete, 9229 /// Template argument deduction did not deduce a value for every 9230 /// expansion of an expanded template parameter pack. 9231 TDK_IncompletePack, 9232 /// Template argument deduction produced inconsistent 9233 /// deduced values for the given template parameter. 9234 TDK_Inconsistent, 9235 /// Template argument deduction failed due to inconsistent 9236 /// cv-qualifiers on a template parameter type that would 9237 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 9238 /// but were given a non-const "X". 9239 TDK_Underqualified, 9240 /// Substitution of the deduced template argument values 9241 /// resulted in an error. 9242 TDK_SubstitutionFailure, 9243 /// After substituting deduced template arguments, a dependent 9244 /// parameter type did not match the corresponding argument. 9245 TDK_DeducedMismatch, 9246 /// After substituting deduced template arguments, an element of 9247 /// a dependent parameter type did not match the corresponding element 9248 /// of the corresponding argument (when deducing from an initializer list). 9249 TDK_DeducedMismatchNested, 9250 /// A non-depnedent component of the parameter did not match the 9251 /// corresponding component of the argument. 9252 TDK_NonDeducedMismatch, 9253 /// When performing template argument deduction for a function 9254 /// template, there were too many call arguments. 9255 TDK_TooManyArguments, 9256 /// When performing template argument deduction for a function 9257 /// template, there were too few call arguments. 9258 TDK_TooFewArguments, 9259 /// The explicitly-specified template arguments were not valid 9260 /// template arguments for the given template. 9261 TDK_InvalidExplicitArguments, 9262 /// Checking non-dependent argument conversions failed. 9263 TDK_NonDependentConversionFailure, 9264 /// The deduced arguments did not satisfy the constraints associated 9265 /// with the template. 9266 TDK_ConstraintsNotSatisfied, 9267 /// Deduction failed; that's all we know. 9268 TDK_MiscellaneousDeductionFailure, 9269 /// CUDA Target attributes do not match. 9270 TDK_CUDATargetMismatch, 9271 /// Some error which was already diagnosed. 9272 TDK_AlreadyDiagnosed 9273 }; 9274 9275 TemplateDeductionResult 9276 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 9277 const TemplateArgumentList &TemplateArgs, 9278 sema::TemplateDeductionInfo &Info); 9279 9280 TemplateDeductionResult 9281 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 9282 const TemplateArgumentList &TemplateArgs, 9283 sema::TemplateDeductionInfo &Info); 9284 9285 TemplateDeductionResult SubstituteExplicitTemplateArguments( 9286 FunctionTemplateDecl *FunctionTemplate, 9287 TemplateArgumentListInfo &ExplicitTemplateArgs, 9288 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 9289 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 9290 sema::TemplateDeductionInfo &Info); 9291 9292 /// brief A function argument from which we performed template argument 9293 // deduction for a call. 9294 struct OriginalCallArg { OriginalCallArgOriginalCallArg9295 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, 9296 unsigned ArgIdx, QualType OriginalArgType) 9297 : OriginalParamType(OriginalParamType), 9298 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), 9299 OriginalArgType(OriginalArgType) {} 9300 9301 QualType OriginalParamType; 9302 bool DecomposedParam; 9303 unsigned ArgIdx; 9304 QualType OriginalArgType; 9305 }; 9306 9307 TemplateDeductionResult FinishTemplateArgumentDeduction( 9308 FunctionTemplateDecl *FunctionTemplate, 9309 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 9310 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 9311 sema::TemplateDeductionInfo &Info, 9312 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, 9313 bool PartialOverloading = false, 9314 llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); 9315 9316 TemplateDeductionResult DeduceTemplateArguments( 9317 FunctionTemplateDecl *FunctionTemplate, 9318 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 9319 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, 9320 bool PartialOverloading, bool AggregateDeductionCandidate, 9321 QualType ObjectType, Expr::Classification ObjectClassification, 9322 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); 9323 9324 TemplateDeductionResult 9325 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 9326 TemplateArgumentListInfo *ExplicitTemplateArgs, 9327 QualType ArgFunctionType, 9328 FunctionDecl *&Specialization, 9329 sema::TemplateDeductionInfo &Info, 9330 bool IsAddressOfFunction = false); 9331 9332 TemplateDeductionResult DeduceTemplateArguments( 9333 FunctionTemplateDecl *FunctionTemplate, QualType ObjectType, 9334 Expr::Classification ObjectClassification, QualType ToType, 9335 CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); 9336 9337 TemplateDeductionResult 9338 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 9339 TemplateArgumentListInfo *ExplicitTemplateArgs, 9340 FunctionDecl *&Specialization, 9341 sema::TemplateDeductionInfo &Info, 9342 bool IsAddressOfFunction = false); 9343 9344 /// Substitute Replacement for \p auto in \p TypeWithAuto 9345 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 9346 /// Substitute Replacement for auto in TypeWithAuto 9347 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 9348 QualType Replacement); 9349 9350 // Substitute auto in TypeWithAuto for a Dependent auto type 9351 QualType SubstAutoTypeDependent(QualType TypeWithAuto); 9352 9353 // Substitute auto in TypeWithAuto for a Dependent auto type 9354 TypeSourceInfo * 9355 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto); 9356 9357 /// Completely replace the \c auto in \p TypeWithAuto by 9358 /// \p Replacement. This does not retain any \c auto type sugar. 9359 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); 9360 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 9361 QualType Replacement); 9362 9363 TemplateDeductionResult 9364 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, 9365 sema::TemplateDeductionInfo &Info, 9366 bool DependentDeduction = false, 9367 bool IgnoreConstraints = false, 9368 TemplateSpecCandidateSet *FailedTSC = nullptr); 9369 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 9370 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 9371 bool Diagnose = true); 9372 9373 bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, 9374 SourceLocation Loc); 9375 9376 /// Declare implicit deduction guides for a class template if we've 9377 /// not already done so. 9378 void DeclareImplicitDeductionGuides(TemplateDecl *Template, 9379 SourceLocation Loc); 9380 FunctionTemplateDecl *DeclareImplicitDeductionGuideFromInitList( 9381 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes, 9382 SourceLocation Loc); 9383 llvm::DenseMap<unsigned, CXXDeductionGuideDecl *> 9384 AggregateDeductionCandidates; 9385 9386 QualType DeduceTemplateSpecializationFromInitializer( 9387 TypeSourceInfo *TInfo, const InitializedEntity &Entity, 9388 const InitializationKind &Kind, MultiExprArg Init); 9389 9390 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, 9391 QualType Type, TypeSourceInfo *TSI, 9392 SourceRange Range, bool DirectInit, 9393 Expr *Init); 9394 9395 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 9396 9397 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 9398 SourceLocation ReturnLoc, Expr *RetExpr, 9399 const AutoType *AT); 9400 9401 FunctionTemplateDecl *getMoreSpecializedTemplate( 9402 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, 9403 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, 9404 unsigned NumCallArguments2, bool Reversed = false); 9405 UnresolvedSetIterator 9406 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 9407 TemplateSpecCandidateSet &FailedCandidates, 9408 SourceLocation Loc, 9409 const PartialDiagnostic &NoneDiag, 9410 const PartialDiagnostic &AmbigDiag, 9411 const PartialDiagnostic &CandidateDiag, 9412 bool Complain = true, QualType TargetType = QualType()); 9413 9414 ClassTemplatePartialSpecializationDecl * 9415 getMoreSpecializedPartialSpecialization( 9416 ClassTemplatePartialSpecializationDecl *PS1, 9417 ClassTemplatePartialSpecializationDecl *PS2, 9418 SourceLocation Loc); 9419 9420 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, 9421 sema::TemplateDeductionInfo &Info); 9422 9423 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 9424 VarTemplatePartialSpecializationDecl *PS1, 9425 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 9426 9427 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, 9428 sema::TemplateDeductionInfo &Info); 9429 9430 bool isTemplateTemplateParameterAtLeastAsSpecializedAs( 9431 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); 9432 9433 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 9434 unsigned Depth, llvm::SmallBitVector &Used); 9435 9436 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 9437 bool OnlyDeduced, 9438 unsigned Depth, 9439 llvm::SmallBitVector &Used); MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)9440 void MarkDeducedTemplateParameters( 9441 const FunctionTemplateDecl *FunctionTemplate, 9442 llvm::SmallBitVector &Deduced) { 9443 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 9444 } 9445 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 9446 const FunctionTemplateDecl *FunctionTemplate, 9447 llvm::SmallBitVector &Deduced); 9448 9449 //===--------------------------------------------------------------------===// 9450 // C++ Template Instantiation 9451 // 9452 9453 MultiLevelTemplateArgumentList getTemplateInstantiationArgs( 9454 const NamedDecl *D, const DeclContext *DC = nullptr, bool Final = false, 9455 const TemplateArgumentList *Innermost = nullptr, 9456 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr, 9457 bool ForConstraintInstantiation = false, 9458 bool SkipForSpecialization = false); 9459 9460 /// A context in which code is being synthesized (where a source location 9461 /// alone is not sufficient to identify the context). This covers template 9462 /// instantiation and various forms of implicitly-generated functions. 9463 struct CodeSynthesisContext { 9464 /// The kind of template instantiation we are performing 9465 enum SynthesisKind { 9466 /// We are instantiating a template declaration. The entity is 9467 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 9468 TemplateInstantiation, 9469 9470 /// We are instantiating a default argument for a template 9471 /// parameter. The Entity is the template parameter whose argument is 9472 /// being instantiated, the Template is the template, and the 9473 /// TemplateArgs/NumTemplateArguments provide the template arguments as 9474 /// specified. 9475 DefaultTemplateArgumentInstantiation, 9476 9477 /// We are instantiating a default argument for a function. 9478 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 9479 /// provides the template arguments as specified. 9480 DefaultFunctionArgumentInstantiation, 9481 9482 /// We are substituting explicit template arguments provided for 9483 /// a function template. The entity is a FunctionTemplateDecl. 9484 ExplicitTemplateArgumentSubstitution, 9485 9486 /// We are substituting template argument determined as part of 9487 /// template argument deduction for either a class template 9488 /// partial specialization or a function template. The 9489 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or 9490 /// a TemplateDecl. 9491 DeducedTemplateArgumentSubstitution, 9492 9493 /// We are substituting into a lambda expression. 9494 LambdaExpressionSubstitution, 9495 9496 /// We are substituting prior template arguments into a new 9497 /// template parameter. The template parameter itself is either a 9498 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 9499 PriorTemplateArgumentSubstitution, 9500 9501 /// We are checking the validity of a default template argument that 9502 /// has been used when naming a template-id. 9503 DefaultTemplateArgumentChecking, 9504 9505 /// We are computing the exception specification for a defaulted special 9506 /// member function. 9507 ExceptionSpecEvaluation, 9508 9509 /// We are instantiating the exception specification for a function 9510 /// template which was deferred until it was needed. 9511 ExceptionSpecInstantiation, 9512 9513 /// We are instantiating a requirement of a requires expression. 9514 RequirementInstantiation, 9515 9516 /// We are checking the satisfaction of a nested requirement of a requires 9517 /// expression. 9518 NestedRequirementConstraintsCheck, 9519 9520 /// We are declaring an implicit special member function. 9521 DeclaringSpecialMember, 9522 9523 /// We are declaring an implicit 'operator==' for a defaulted 9524 /// 'operator<=>'. 9525 DeclaringImplicitEqualityComparison, 9526 9527 /// We are defining a synthesized function (such as a defaulted special 9528 /// member). 9529 DefiningSynthesizedFunction, 9530 9531 // We are checking the constraints associated with a constrained entity or 9532 // the constraint expression of a concept. This includes the checks that 9533 // atomic constraints have the type 'bool' and that they can be constant 9534 // evaluated. 9535 ConstraintsCheck, 9536 9537 // We are substituting template arguments into a constraint expression. 9538 ConstraintSubstitution, 9539 9540 // We are normalizing a constraint expression. 9541 ConstraintNormalization, 9542 9543 // Instantiating a Requires Expression parameter clause. 9544 RequirementParameterInstantiation, 9545 9546 // We are substituting into the parameter mapping of an atomic constraint 9547 // during normalization. 9548 ParameterMappingSubstitution, 9549 9550 /// We are rewriting a comparison operator in terms of an operator<=>. 9551 RewritingOperatorAsSpaceship, 9552 9553 /// We are initializing a structured binding. 9554 InitializingStructuredBinding, 9555 9556 /// We are marking a class as __dllexport. 9557 MarkingClassDllexported, 9558 9559 /// We are building an implied call from __builtin_dump_struct. The 9560 /// arguments are in CallArgs. 9561 BuildingBuiltinDumpStructCall, 9562 9563 /// Added for Template instantiation observation. 9564 /// Memoization means we are _not_ instantiating a template because 9565 /// it is already instantiated (but we entered a context where we 9566 /// would have had to if it was not already instantiated). 9567 Memoization, 9568 9569 /// We are building deduction guides for a class. 9570 BuildingDeductionGuides, 9571 } Kind; 9572 9573 /// Was the enclosing context a non-instantiation SFINAE context? 9574 bool SavedInNonInstantiationSFINAEContext; 9575 9576 /// The point of instantiation or synthesis within the source code. 9577 SourceLocation PointOfInstantiation; 9578 9579 /// The entity that is being synthesized. 9580 Decl *Entity; 9581 9582 /// The template (or partial specialization) in which we are 9583 /// performing the instantiation, for substitutions of prior template 9584 /// arguments. 9585 NamedDecl *Template; 9586 9587 union { 9588 /// The list of template arguments we are substituting, if they 9589 /// are not part of the entity. 9590 const TemplateArgument *TemplateArgs; 9591 9592 /// The list of argument expressions in a synthesized call. 9593 const Expr *const *CallArgs; 9594 }; 9595 9596 // FIXME: Wrap this union around more members, or perhaps store the 9597 // kind-specific members in the RAII object owning the context. 9598 union { 9599 /// The number of template arguments in TemplateArgs. 9600 unsigned NumTemplateArgs; 9601 9602 /// The number of expressions in CallArgs. 9603 unsigned NumCallArgs; 9604 9605 /// The special member being declared or defined. 9606 CXXSpecialMember SpecialMember; 9607 }; 9608 template_argumentsCodeSynthesisContext9609 ArrayRef<TemplateArgument> template_arguments() const { 9610 assert(Kind != DeclaringSpecialMember); 9611 return {TemplateArgs, NumTemplateArgs}; 9612 } 9613 9614 /// The template deduction info object associated with the 9615 /// substitution or checking of explicit or deduced template arguments. 9616 sema::TemplateDeductionInfo *DeductionInfo; 9617 9618 /// The source range that covers the construct that cause 9619 /// the instantiation, e.g., the template-id that causes a class 9620 /// template instantiation. 9621 SourceRange InstantiationRange; 9622 CodeSynthesisContextCodeSynthesisContext9623 CodeSynthesisContext() 9624 : Kind(TemplateInstantiation), 9625 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), 9626 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), 9627 DeductionInfo(nullptr) {} 9628 9629 /// Determines whether this template is an actual instantiation 9630 /// that should be counted toward the maximum instantiation depth. 9631 bool isInstantiationRecord() const; 9632 }; 9633 9634 /// List of active code synthesis contexts. 9635 /// 9636 /// This vector is treated as a stack. As synthesis of one entity requires 9637 /// synthesis of another, additional contexts are pushed onto the stack. 9638 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; 9639 9640 /// Specializations whose definitions are currently being instantiated. 9641 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; 9642 9643 /// Non-dependent types used in templates that have already been instantiated 9644 /// by some template instantiation. 9645 llvm::DenseSet<QualType> InstantiatedNonDependentTypes; 9646 9647 /// Extra modules inspected when performing a lookup during a template 9648 /// instantiation. Computed lazily. 9649 SmallVector<Module*, 16> CodeSynthesisContextLookupModules; 9650 9651 /// Cache of additional modules that should be used for name lookup 9652 /// within the current template instantiation. Computed lazily; use 9653 /// getLookupModules() to get a complete set. 9654 llvm::DenseSet<Module*> LookupModulesCache; 9655 9656 /// Get the set of additional modules that should be checked during 9657 /// name lookup. A module and its imports become visible when instanting a 9658 /// template defined within it. 9659 llvm::DenseSet<Module*> &getLookupModules(); 9660 9661 /// Map from the most recent declaration of a namespace to the most 9662 /// recent visible declaration of that namespace. 9663 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; 9664 9665 /// Whether we are in a SFINAE context that is not associated with 9666 /// template instantiation. 9667 /// 9668 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 9669 /// of a template instantiation or template argument deduction. 9670 bool InNonInstantiationSFINAEContext; 9671 9672 /// The number of \p CodeSynthesisContexts that are not template 9673 /// instantiations and, therefore, should not be counted as part of the 9674 /// instantiation depth. 9675 /// 9676 /// When the instantiation depth reaches the user-configurable limit 9677 /// \p LangOptions::InstantiationDepth we will abort instantiation. 9678 // FIXME: Should we have a similar limit for other forms of synthesis? 9679 unsigned NonInstantiationEntries; 9680 9681 /// The depth of the context stack at the point when the most recent 9682 /// error or warning was produced. 9683 /// 9684 /// This value is used to suppress printing of redundant context stacks 9685 /// when there are multiple errors or warnings in the same instantiation. 9686 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. 9687 unsigned LastEmittedCodeSynthesisContextDepth = 0; 9688 9689 /// The template instantiation callbacks to trace or track 9690 /// instantiations (objects can be chained). 9691 /// 9692 /// This callbacks is used to print, trace or track template 9693 /// instantiations as they are being constructed. 9694 std::vector<std::unique_ptr<TemplateInstantiationCallback>> 9695 TemplateInstCallbacks; 9696 9697 /// The current index into pack expansion arguments that will be 9698 /// used for substitution of parameter packs. 9699 /// 9700 /// The pack expansion index will be -1 to indicate that parameter packs 9701 /// should be instantiated as themselves. Otherwise, the index specifies 9702 /// which argument within the parameter pack will be used for substitution. 9703 int ArgumentPackSubstitutionIndex; 9704 9705 /// RAII object used to change the argument pack substitution index 9706 /// within a \c Sema object. 9707 /// 9708 /// See \c ArgumentPackSubstitutionIndex for more information. 9709 class ArgumentPackSubstitutionIndexRAII { 9710 Sema &Self; 9711 int OldSubstitutionIndex; 9712 9713 public: ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)9714 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 9715 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 9716 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 9717 } 9718 ~ArgumentPackSubstitutionIndexRAII()9719 ~ArgumentPackSubstitutionIndexRAII() { 9720 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 9721 } 9722 }; 9723 9724 friend class ArgumentPackSubstitutionRAII; 9725 9726 /// For each declaration that involved template argument deduction, the 9727 /// set of diagnostics that were suppressed during that template argument 9728 /// deduction. 9729 /// 9730 /// FIXME: Serialize this structure to the AST file. 9731 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 9732 SuppressedDiagnosticsMap; 9733 SuppressedDiagnosticsMap SuppressedDiagnostics; 9734 9735 /// A stack object to be created when performing template 9736 /// instantiation. 9737 /// 9738 /// Construction of an object of type \c InstantiatingTemplate 9739 /// pushes the current instantiation onto the stack of active 9740 /// instantiations. If the size of this stack exceeds the maximum 9741 /// number of recursive template instantiations, construction 9742 /// produces an error and evaluates true. 9743 /// 9744 /// Destruction of this object will pop the named instantiation off 9745 /// the stack. 9746 struct InstantiatingTemplate { 9747 /// Note that we are instantiating a class template, 9748 /// function template, variable template, alias template, 9749 /// or a member thereof. 9750 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9751 Decl *Entity, 9752 SourceRange InstantiationRange = SourceRange()); 9753 9754 struct ExceptionSpecification {}; 9755 /// Note that we are instantiating an exception specification 9756 /// of a function template. 9757 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9758 FunctionDecl *Entity, ExceptionSpecification, 9759 SourceRange InstantiationRange = SourceRange()); 9760 9761 /// Note that we are instantiating a default argument in a 9762 /// template-id. 9763 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9764 TemplateParameter Param, TemplateDecl *Template, 9765 ArrayRef<TemplateArgument> TemplateArgs, 9766 SourceRange InstantiationRange = SourceRange()); 9767 9768 /// Note that we are substituting either explicitly-specified or 9769 /// deduced template arguments during function template argument deduction. 9770 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9771 FunctionTemplateDecl *FunctionTemplate, 9772 ArrayRef<TemplateArgument> TemplateArgs, 9773 CodeSynthesisContext::SynthesisKind Kind, 9774 sema::TemplateDeductionInfo &DeductionInfo, 9775 SourceRange InstantiationRange = SourceRange()); 9776 9777 /// Note that we are instantiating as part of template 9778 /// argument deduction for a class template declaration. 9779 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9780 TemplateDecl *Template, 9781 ArrayRef<TemplateArgument> TemplateArgs, 9782 sema::TemplateDeductionInfo &DeductionInfo, 9783 SourceRange InstantiationRange = SourceRange()); 9784 9785 /// Note that we are instantiating as part of template 9786 /// argument deduction for a class template partial 9787 /// specialization. 9788 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9789 ClassTemplatePartialSpecializationDecl *PartialSpec, 9790 ArrayRef<TemplateArgument> TemplateArgs, 9791 sema::TemplateDeductionInfo &DeductionInfo, 9792 SourceRange InstantiationRange = SourceRange()); 9793 9794 /// Note that we are instantiating as part of template 9795 /// argument deduction for a variable template partial 9796 /// specialization. 9797 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9798 VarTemplatePartialSpecializationDecl *PartialSpec, 9799 ArrayRef<TemplateArgument> TemplateArgs, 9800 sema::TemplateDeductionInfo &DeductionInfo, 9801 SourceRange InstantiationRange = SourceRange()); 9802 9803 /// Note that we are instantiating a default argument for a function 9804 /// parameter. 9805 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9806 ParmVarDecl *Param, 9807 ArrayRef<TemplateArgument> TemplateArgs, 9808 SourceRange InstantiationRange = SourceRange()); 9809 9810 /// Note that we are substituting prior template arguments into a 9811 /// non-type parameter. 9812 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9813 NamedDecl *Template, 9814 NonTypeTemplateParmDecl *Param, 9815 ArrayRef<TemplateArgument> TemplateArgs, 9816 SourceRange InstantiationRange); 9817 9818 /// Note that we are substituting prior template arguments into a 9819 /// template template parameter. 9820 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9821 NamedDecl *Template, 9822 TemplateTemplateParmDecl *Param, 9823 ArrayRef<TemplateArgument> TemplateArgs, 9824 SourceRange InstantiationRange); 9825 9826 /// Note that we are checking the default template argument 9827 /// against the template parameter for a given template-id. 9828 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9829 TemplateDecl *Template, 9830 NamedDecl *Param, 9831 ArrayRef<TemplateArgument> TemplateArgs, 9832 SourceRange InstantiationRange); 9833 9834 struct ConstraintsCheck {}; 9835 /// \brief Note that we are checking the constraints associated with some 9836 /// constrained entity (a concept declaration or a template with associated 9837 /// constraints). 9838 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9839 ConstraintsCheck, NamedDecl *Template, 9840 ArrayRef<TemplateArgument> TemplateArgs, 9841 SourceRange InstantiationRange); 9842 9843 struct ConstraintSubstitution {}; 9844 /// \brief Note that we are checking a constraint expression associated 9845 /// with a template declaration or as part of the satisfaction check of a 9846 /// concept. 9847 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9848 ConstraintSubstitution, NamedDecl *Template, 9849 sema::TemplateDeductionInfo &DeductionInfo, 9850 SourceRange InstantiationRange); 9851 9852 struct ConstraintNormalization {}; 9853 /// \brief Note that we are normalizing a constraint expression. 9854 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9855 ConstraintNormalization, NamedDecl *Template, 9856 SourceRange InstantiationRange); 9857 9858 struct ParameterMappingSubstitution {}; 9859 /// \brief Note that we are subtituting into the parameter mapping of an 9860 /// atomic constraint during constraint normalization. 9861 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9862 ParameterMappingSubstitution, NamedDecl *Template, 9863 SourceRange InstantiationRange); 9864 9865 /// \brief Note that we are substituting template arguments into a part of 9866 /// a requirement of a requires expression. 9867 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9868 concepts::Requirement *Req, 9869 sema::TemplateDeductionInfo &DeductionInfo, 9870 SourceRange InstantiationRange = SourceRange()); 9871 9872 /// \brief Note that we are checking the satisfaction of the constraint 9873 /// expression inside of a nested requirement. 9874 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9875 concepts::NestedRequirement *Req, ConstraintsCheck, 9876 SourceRange InstantiationRange = SourceRange()); 9877 9878 /// \brief Note that we are checking a requires clause. 9879 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9880 const RequiresExpr *E, 9881 sema::TemplateDeductionInfo &DeductionInfo, 9882 SourceRange InstantiationRange); 9883 9884 struct BuildingDeductionGuidesTag {}; 9885 /// \brief Note that we are building deduction guides. 9886 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 9887 TemplateDecl *Entity, BuildingDeductionGuidesTag, 9888 SourceRange InstantiationRange = SourceRange()); 9889 9890 /// Note that we have finished instantiating this template. 9891 void Clear(); 9892 ~InstantiatingTemplateInstantiatingTemplate9893 ~InstantiatingTemplate() { Clear(); } 9894 9895 /// Determines whether we have exceeded the maximum 9896 /// recursive template instantiations. isInvalidInstantiatingTemplate9897 bool isInvalid() const { return Invalid; } 9898 9899 /// Determine whether we are already instantiating this 9900 /// specialization in some surrounding active instantiation. isAlreadyInstantiatingInstantiatingTemplate9901 bool isAlreadyInstantiating() const { return AlreadyInstantiating; } 9902 9903 private: 9904 Sema &SemaRef; 9905 bool Invalid; 9906 bool AlreadyInstantiating; 9907 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 9908 SourceRange InstantiationRange); 9909 9910 InstantiatingTemplate( 9911 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, 9912 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 9913 Decl *Entity, NamedDecl *Template = nullptr, 9914 ArrayRef<TemplateArgument> TemplateArgs = std::nullopt, 9915 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 9916 9917 InstantiatingTemplate(const InstantiatingTemplate&) = delete; 9918 9919 InstantiatingTemplate& 9920 operator=(const InstantiatingTemplate&) = delete; 9921 }; 9922 9923 void pushCodeSynthesisContext(CodeSynthesisContext Ctx); 9924 void popCodeSynthesisContext(); 9925 9926 /// Determine whether we are currently performing template instantiation. inTemplateInstantiation()9927 bool inTemplateInstantiation() const { 9928 return CodeSynthesisContexts.size() > NonInstantiationEntries; 9929 } 9930 PrintContextStack()9931 void PrintContextStack() { 9932 if (!CodeSynthesisContexts.empty() && 9933 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { 9934 PrintInstantiationStack(); 9935 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); 9936 } 9937 if (PragmaAttributeCurrentTargetDecl) 9938 PrintPragmaAttributeInstantiationPoint(); 9939 } 9940 void PrintInstantiationStack(); 9941 9942 void PrintPragmaAttributeInstantiationPoint(); 9943 9944 /// Determines whether we are currently in a context where 9945 /// template argument substitution failures are not considered 9946 /// errors. 9947 /// 9948 /// \returns An empty \c Optional if we're not in a SFINAE context. 9949 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 9950 /// template-deduction context object, which can be used to capture 9951 /// diagnostics that will be suppressed. 9952 std::optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 9953 9954 /// Whether the AST is currently being rebuilt to correct immediate 9955 /// invocations. Immediate invocation candidates and references to consteval 9956 /// functions aren't tracked when this is set. 9957 bool RebuildingImmediateInvocation = false; 9958 9959 /// Used to change context to isConstantEvaluated without pushing a heavy 9960 /// ExpressionEvaluationContextRecord object. 9961 bool isConstantEvaluatedOverride = false; 9962 currentEvaluationContext()9963 const ExpressionEvaluationContextRecord ¤tEvaluationContext() const { 9964 assert(!ExprEvalContexts.empty() && 9965 "Must be in an expression evaluation context"); 9966 return ExprEvalContexts.back(); 9967 }; 9968 isConstantEvaluatedContext()9969 bool isConstantEvaluatedContext() const { 9970 return currentEvaluationContext().isConstantEvaluated() || 9971 isConstantEvaluatedOverride; 9972 } 9973 isAlwaysConstantEvaluatedContext()9974 bool isAlwaysConstantEvaluatedContext() const { 9975 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext(); 9976 return (Ctx.isConstantEvaluated() || isConstantEvaluatedOverride) && 9977 !Ctx.InConditionallyConstantEvaluateContext; 9978 } 9979 9980 /// Determines whether we are currently in a context that 9981 /// is not evaluated as per C++ [expr] p5. isUnevaluatedContext()9982 bool isUnevaluatedContext() const { 9983 return currentEvaluationContext().isUnevaluated(); 9984 } 9985 isImmediateFunctionContext()9986 bool isImmediateFunctionContext() const { 9987 return currentEvaluationContext().isImmediateFunctionContext(); 9988 } 9989 isCheckingDefaultArgumentOrInitializer()9990 bool isCheckingDefaultArgumentOrInitializer() const { 9991 const ExpressionEvaluationContextRecord &Ctx = currentEvaluationContext(); 9992 return (Ctx.Context == 9993 ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed) || 9994 Ctx.IsCurrentlyCheckingDefaultArgumentOrInitializer; 9995 } 9996 9997 std::optional<ExpressionEvaluationContextRecord::InitializationContext> InnermostDeclarationWithDelayedImmediateInvocations()9998 InnermostDeclarationWithDelayedImmediateInvocations() const { 9999 assert(!ExprEvalContexts.empty() && 10000 "Must be in an expression evaluation context"); 10001 for (const auto &Ctx : llvm::reverse(ExprEvalContexts)) { 10002 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && 10003 Ctx.DelayedDefaultInitializationContext) 10004 return Ctx.DelayedDefaultInitializationContext; 10005 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() || 10006 Ctx.isUnevaluated()) 10007 break; 10008 } 10009 return std::nullopt; 10010 } 10011 10012 std::optional<ExpressionEvaluationContextRecord::InitializationContext> OutermostDeclarationWithDelayedImmediateInvocations()10013 OutermostDeclarationWithDelayedImmediateInvocations() const { 10014 assert(!ExprEvalContexts.empty() && 10015 "Must be in an expression evaluation context"); 10016 std::optional<ExpressionEvaluationContextRecord::InitializationContext> Res; 10017 for (auto &Ctx : llvm::reverse(ExprEvalContexts)) { 10018 if (Ctx.Context == ExpressionEvaluationContext::PotentiallyEvaluated && 10019 !Ctx.DelayedDefaultInitializationContext && Res) 10020 break; 10021 if (Ctx.isConstantEvaluated() || Ctx.isImmediateFunctionContext() || 10022 Ctx.isUnevaluated()) 10023 break; 10024 Res = Ctx.DelayedDefaultInitializationContext; 10025 } 10026 return Res; 10027 } 10028 10029 /// RAII class used to determine whether SFINAE has 10030 /// trapped any errors that occur during template argument 10031 /// deduction. 10032 class SFINAETrap { 10033 Sema &SemaRef; 10034 unsigned PrevSFINAEErrors; 10035 bool PrevInNonInstantiationSFINAEContext; 10036 bool PrevAccessCheckingSFINAE; 10037 bool PrevLastDiagnosticIgnored; 10038 10039 public: 10040 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) SemaRef(SemaRef)10041 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 10042 PrevInNonInstantiationSFINAEContext( 10043 SemaRef.InNonInstantiationSFINAEContext), 10044 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), 10045 PrevLastDiagnosticIgnored( 10046 SemaRef.getDiagnostics().isLastDiagnosticIgnored()) 10047 { 10048 if (!SemaRef.isSFINAEContext()) 10049 SemaRef.InNonInstantiationSFINAEContext = true; 10050 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 10051 } 10052 ~SFINAETrap()10053 ~SFINAETrap() { 10054 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 10055 SemaRef.InNonInstantiationSFINAEContext 10056 = PrevInNonInstantiationSFINAEContext; 10057 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 10058 SemaRef.getDiagnostics().setLastDiagnosticIgnored( 10059 PrevLastDiagnosticIgnored); 10060 } 10061 10062 /// Determine whether any SFINAE errors have been trapped. hasErrorOccurred()10063 bool hasErrorOccurred() const { 10064 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 10065 } 10066 }; 10067 10068 /// RAII class used to indicate that we are performing provisional 10069 /// semantic analysis to determine the validity of a construct, so 10070 /// typo-correction and diagnostics in the immediate context (not within 10071 /// implicitly-instantiated templates) should be suppressed. 10072 class TentativeAnalysisScope { 10073 Sema &SemaRef; 10074 // FIXME: Using a SFINAETrap for this is a hack. 10075 SFINAETrap Trap; 10076 bool PrevDisableTypoCorrection; 10077 public: TentativeAnalysisScope(Sema & SemaRef)10078 explicit TentativeAnalysisScope(Sema &SemaRef) 10079 : SemaRef(SemaRef), Trap(SemaRef, true), 10080 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 10081 SemaRef.DisableTypoCorrection = true; 10082 } ~TentativeAnalysisScope()10083 ~TentativeAnalysisScope() { 10084 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 10085 } 10086 }; 10087 10088 /// The current instantiation scope used to store local 10089 /// variables. 10090 LocalInstantiationScope *CurrentInstantiationScope; 10091 10092 /// Tracks whether we are in a context where typo correction is 10093 /// disabled. 10094 bool DisableTypoCorrection; 10095 10096 /// The number of typos corrected by CorrectTypo. 10097 unsigned TyposCorrected; 10098 10099 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 10100 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 10101 10102 /// A cache containing identifiers for which typo correction failed and 10103 /// their locations, so that repeated attempts to correct an identifier in a 10104 /// given location are ignored if typo correction already failed for it. 10105 IdentifierSourceLocations TypoCorrectionFailures; 10106 10107 /// Worker object for performing CFG-based warnings. 10108 sema::AnalysisBasedWarnings AnalysisWarnings; 10109 threadSafety::BeforeSet *ThreadSafetyDeclCache; 10110 10111 /// An entity for which implicit template instantiation is required. 10112 /// 10113 /// The source location associated with the declaration is the first place in 10114 /// the source code where the declaration was "used". It is not necessarily 10115 /// the point of instantiation (which will be either before or after the 10116 /// namespace-scope declaration that triggered this implicit instantiation), 10117 /// However, it is the location that diagnostics should generally refer to, 10118 /// because users will need to know what code triggered the instantiation. 10119 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 10120 10121 /// The queue of implicit template instantiations that are required 10122 /// but have not yet been performed. 10123 std::deque<PendingImplicitInstantiation> PendingInstantiations; 10124 10125 /// Queue of implicit template instantiations that cannot be performed 10126 /// eagerly. 10127 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; 10128 10129 SmallVector<SmallVector<VTableUse, 16>, 8> SavedVTableUses; 10130 SmallVector<std::deque<PendingImplicitInstantiation>, 8> 10131 SavedPendingInstantiations; 10132 10133 class GlobalEagerInstantiationScope { 10134 public: GlobalEagerInstantiationScope(Sema & S,bool Enabled)10135 GlobalEagerInstantiationScope(Sema &S, bool Enabled) 10136 : S(S), Enabled(Enabled) { 10137 if (!Enabled) return; 10138 10139 S.SavedPendingInstantiations.emplace_back(); 10140 S.SavedPendingInstantiations.back().swap(S.PendingInstantiations); 10141 10142 S.SavedVTableUses.emplace_back(); 10143 S.SavedVTableUses.back().swap(S.VTableUses); 10144 } 10145 perform()10146 void perform() { 10147 if (Enabled) { 10148 S.DefineUsedVTables(); 10149 S.PerformPendingInstantiations(); 10150 } 10151 } 10152 ~GlobalEagerInstantiationScope()10153 ~GlobalEagerInstantiationScope() { 10154 if (!Enabled) return; 10155 10156 // Restore the set of pending vtables. 10157 assert(S.VTableUses.empty() && 10158 "VTableUses should be empty before it is discarded."); 10159 S.VTableUses.swap(S.SavedVTableUses.back()); 10160 S.SavedVTableUses.pop_back(); 10161 10162 // Restore the set of pending implicit instantiations. 10163 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { 10164 assert(S.PendingInstantiations.empty() && 10165 "PendingInstantiations should be empty before it is discarded."); 10166 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back()); 10167 S.SavedPendingInstantiations.pop_back(); 10168 } else { 10169 // Template instantiations in the PCH may be delayed until the TU. 10170 S.PendingInstantiations.swap(S.SavedPendingInstantiations.back()); 10171 S.PendingInstantiations.insert( 10172 S.PendingInstantiations.end(), 10173 S.SavedPendingInstantiations.back().begin(), 10174 S.SavedPendingInstantiations.back().end()); 10175 S.SavedPendingInstantiations.pop_back(); 10176 } 10177 } 10178 10179 private: 10180 Sema &S; 10181 bool Enabled; 10182 }; 10183 10184 /// The queue of implicit template instantiations that are required 10185 /// and must be performed within the current local scope. 10186 /// 10187 /// This queue is only used for member functions of local classes in 10188 /// templates, which must be instantiated in the same scope as their 10189 /// enclosing function, so that they can reference function-local 10190 /// types, static variables, enumerators, etc. 10191 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 10192 10193 class LocalEagerInstantiationScope { 10194 public: LocalEagerInstantiationScope(Sema & S)10195 LocalEagerInstantiationScope(Sema &S) : S(S) { 10196 SavedPendingLocalImplicitInstantiations.swap( 10197 S.PendingLocalImplicitInstantiations); 10198 } 10199 perform()10200 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } 10201 ~LocalEagerInstantiationScope()10202 ~LocalEagerInstantiationScope() { 10203 assert(S.PendingLocalImplicitInstantiations.empty() && 10204 "there shouldn't be any pending local implicit instantiations"); 10205 SavedPendingLocalImplicitInstantiations.swap( 10206 S.PendingLocalImplicitInstantiations); 10207 } 10208 10209 private: 10210 Sema &S; 10211 std::deque<PendingImplicitInstantiation> 10212 SavedPendingLocalImplicitInstantiations; 10213 }; 10214 10215 /// A helper class for building up ExtParameterInfos. 10216 class ExtParameterInfoBuilder { 10217 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; 10218 bool HasInteresting = false; 10219 10220 public: 10221 /// Set the ExtParameterInfo for the parameter at the given index, 10222 /// set(unsigned index,FunctionProtoType::ExtParameterInfo info)10223 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { 10224 assert(Infos.size() <= index); 10225 Infos.resize(index); 10226 Infos.push_back(info); 10227 10228 if (!HasInteresting) 10229 HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); 10230 } 10231 10232 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the 10233 /// ExtParameterInfo array we've built up. 10234 const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)10235 getPointerOrNull(unsigned numParams) { 10236 if (!HasInteresting) return nullptr; 10237 Infos.resize(numParams); 10238 return Infos.data(); 10239 } 10240 }; 10241 10242 void PerformPendingInstantiations(bool LocalOnly = false); 10243 10244 TypeSourceInfo *SubstType(TypeSourceInfo *T, 10245 const MultiLevelTemplateArgumentList &TemplateArgs, 10246 SourceLocation Loc, DeclarationName Entity, 10247 bool AllowDeducedTST = false); 10248 10249 QualType SubstType(QualType T, 10250 const MultiLevelTemplateArgumentList &TemplateArgs, 10251 SourceLocation Loc, DeclarationName Entity); 10252 10253 TypeSourceInfo *SubstType(TypeLoc TL, 10254 const MultiLevelTemplateArgumentList &TemplateArgs, 10255 SourceLocation Loc, DeclarationName Entity); 10256 10257 TypeSourceInfo *SubstFunctionDeclType( 10258 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, 10259 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, 10260 Qualifiers ThisTypeQuals, bool EvaluateConstraints = true); 10261 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 10262 const MultiLevelTemplateArgumentList &Args); 10263 bool SubstExceptionSpec(SourceLocation Loc, 10264 FunctionProtoType::ExceptionSpecInfo &ESI, 10265 SmallVectorImpl<QualType> &ExceptionStorage, 10266 const MultiLevelTemplateArgumentList &Args); 10267 ParmVarDecl * 10268 SubstParmVarDecl(ParmVarDecl *D, 10269 const MultiLevelTemplateArgumentList &TemplateArgs, 10270 int indexAdjustment, std::optional<unsigned> NumExpansions, 10271 bool ExpectParameterPack, bool EvaluateConstraints = true); 10272 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, 10273 const FunctionProtoType::ExtParameterInfo *ExtParamInfos, 10274 const MultiLevelTemplateArgumentList &TemplateArgs, 10275 SmallVectorImpl<QualType> &ParamTypes, 10276 SmallVectorImpl<ParmVarDecl *> *OutParams, 10277 ExtParameterInfoBuilder &ParamInfos); 10278 bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, 10279 const MultiLevelTemplateArgumentList &TemplateArgs, 10280 bool ForCallExpr = false); 10281 ExprResult SubstExpr(Expr *E, 10282 const MultiLevelTemplateArgumentList &TemplateArgs); 10283 10284 // A RAII type used by the TemplateDeclInstantiator and TemplateInstantiator 10285 // to disable constraint evaluation, then restore the state. 10286 template <typename InstTy> struct ConstraintEvalRAII { 10287 InstTy &TI; 10288 bool OldValue; 10289 ConstraintEvalRAIIConstraintEvalRAII10290 ConstraintEvalRAII(InstTy &TI) 10291 : TI(TI), OldValue(TI.getEvaluateConstraints()) { 10292 TI.setEvaluateConstraints(false); 10293 } ~ConstraintEvalRAIIConstraintEvalRAII10294 ~ConstraintEvalRAII() { TI.setEvaluateConstraints(OldValue); } 10295 }; 10296 10297 // Must be used instead of SubstExpr at 'constraint checking' time. 10298 ExprResult 10299 SubstConstraintExpr(Expr *E, 10300 const MultiLevelTemplateArgumentList &TemplateArgs); 10301 // Unlike the above, this does not evaluates constraints. 10302 ExprResult SubstConstraintExprWithoutSatisfaction( 10303 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); 10304 10305 /// Substitute the given template arguments into a list of 10306 /// expressions, expanding pack expansions if required. 10307 /// 10308 /// \param Exprs The list of expressions to substitute into. 10309 /// 10310 /// \param IsCall Whether this is some form of call, in which case 10311 /// default arguments will be dropped. 10312 /// 10313 /// \param TemplateArgs The set of template arguments to substitute. 10314 /// 10315 /// \param Outputs Will receive all of the substituted arguments. 10316 /// 10317 /// \returns true if an error occurred, false otherwise. 10318 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 10319 const MultiLevelTemplateArgumentList &TemplateArgs, 10320 SmallVectorImpl<Expr *> &Outputs); 10321 10322 StmtResult SubstStmt(Stmt *S, 10323 const MultiLevelTemplateArgumentList &TemplateArgs); 10324 10325 TemplateParameterList * 10326 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 10327 const MultiLevelTemplateArgumentList &TemplateArgs, 10328 bool EvaluateConstraints = true); 10329 10330 bool 10331 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 10332 const MultiLevelTemplateArgumentList &TemplateArgs, 10333 TemplateArgumentListInfo &Outputs); 10334 10335 Decl *SubstDecl(Decl *D, DeclContext *Owner, 10336 const MultiLevelTemplateArgumentList &TemplateArgs); 10337 10338 /// Substitute the name and return type of a defaulted 'operator<=>' to form 10339 /// an implicit 'operator=='. 10340 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 10341 FunctionDecl *Spaceship); 10342 10343 ExprResult SubstInitializer(Expr *E, 10344 const MultiLevelTemplateArgumentList &TemplateArgs, 10345 bool CXXDirectInit); 10346 10347 bool 10348 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 10349 CXXRecordDecl *Pattern, 10350 const MultiLevelTemplateArgumentList &TemplateArgs); 10351 10352 bool 10353 InstantiateClass(SourceLocation PointOfInstantiation, 10354 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 10355 const MultiLevelTemplateArgumentList &TemplateArgs, 10356 TemplateSpecializationKind TSK, 10357 bool Complain = true); 10358 10359 bool InstantiateEnum(SourceLocation PointOfInstantiation, 10360 EnumDecl *Instantiation, EnumDecl *Pattern, 10361 const MultiLevelTemplateArgumentList &TemplateArgs, 10362 TemplateSpecializationKind TSK); 10363 10364 bool InstantiateInClassInitializer( 10365 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 10366 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 10367 10368 struct LateInstantiatedAttribute { 10369 const Attr *TmplAttr; 10370 LocalInstantiationScope *Scope; 10371 Decl *NewDecl; 10372 LateInstantiatedAttributeLateInstantiatedAttribute10373 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 10374 Decl *D) 10375 : TmplAttr(A), Scope(S), NewDecl(D) 10376 { } 10377 }; 10378 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 10379 10380 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 10381 const Decl *Pattern, Decl *Inst, 10382 LateInstantiatedAttrVec *LateAttrs = nullptr, 10383 LocalInstantiationScope *OuterMostScope = nullptr); 10384 void updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst); 10385 10386 void 10387 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, 10388 const Decl *Pattern, Decl *Inst, 10389 LateInstantiatedAttrVec *LateAttrs = nullptr, 10390 LocalInstantiationScope *OuterMostScope = nullptr); 10391 10392 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); 10393 10394 bool usesPartialOrExplicitSpecialization( 10395 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); 10396 10397 bool 10398 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 10399 ClassTemplateSpecializationDecl *ClassTemplateSpec, 10400 TemplateSpecializationKind TSK, 10401 bool Complain = true); 10402 10403 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 10404 CXXRecordDecl *Instantiation, 10405 const MultiLevelTemplateArgumentList &TemplateArgs, 10406 TemplateSpecializationKind TSK); 10407 10408 void InstantiateClassTemplateSpecializationMembers( 10409 SourceLocation PointOfInstantiation, 10410 ClassTemplateSpecializationDecl *ClassTemplateSpec, 10411 TemplateSpecializationKind TSK); 10412 10413 NestedNameSpecifierLoc 10414 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 10415 const MultiLevelTemplateArgumentList &TemplateArgs); 10416 10417 DeclarationNameInfo 10418 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 10419 const MultiLevelTemplateArgumentList &TemplateArgs); 10420 TemplateName 10421 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 10422 SourceLocation Loc, 10423 const MultiLevelTemplateArgumentList &TemplateArgs); 10424 10425 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, 10426 const MultiLevelTemplateArgumentList &TemplateArgs, 10427 bool EvaluateConstraint); 10428 10429 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 10430 ParmVarDecl *Param); 10431 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 10432 FunctionDecl *Function); 10433 bool CheckInstantiatedFunctionTemplateConstraints( 10434 SourceLocation PointOfInstantiation, FunctionDecl *Decl, 10435 ArrayRef<TemplateArgument> TemplateArgs, 10436 ConstraintSatisfaction &Satisfaction); 10437 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 10438 const TemplateArgumentList *Args, 10439 SourceLocation Loc); 10440 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 10441 FunctionDecl *Function, 10442 bool Recursive = false, 10443 bool DefinitionRequired = false, 10444 bool AtEndOfTU = false); 10445 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 10446 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 10447 const TemplateArgumentList &TemplateArgList, 10448 const TemplateArgumentListInfo &TemplateArgsInfo, 10449 SmallVectorImpl<TemplateArgument> &Converted, 10450 SourceLocation PointOfInstantiation, 10451 LateInstantiatedAttrVec *LateAttrs = nullptr, 10452 LocalInstantiationScope *StartingScope = nullptr); 10453 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 10454 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 10455 const MultiLevelTemplateArgumentList &TemplateArgs); 10456 void 10457 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 10458 const MultiLevelTemplateArgumentList &TemplateArgs, 10459 LateInstantiatedAttrVec *LateAttrs, 10460 DeclContext *Owner, 10461 LocalInstantiationScope *StartingScope, 10462 bool InstantiatingVarTemplate = false, 10463 VarTemplateSpecializationDecl *PrevVTSD = nullptr); 10464 10465 void InstantiateVariableInitializer( 10466 VarDecl *Var, VarDecl *OldVar, 10467 const MultiLevelTemplateArgumentList &TemplateArgs); 10468 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 10469 VarDecl *Var, bool Recursive = false, 10470 bool DefinitionRequired = false, 10471 bool AtEndOfTU = false); 10472 10473 void InstantiateMemInitializers(CXXConstructorDecl *New, 10474 const CXXConstructorDecl *Tmpl, 10475 const MultiLevelTemplateArgumentList &TemplateArgs); 10476 10477 ExplicitSpecifier instantiateExplicitSpecifier( 10478 const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES); 10479 10480 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 10481 const MultiLevelTemplateArgumentList &TemplateArgs, 10482 bool FindingInstantiatedContext = false); 10483 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 10484 const MultiLevelTemplateArgumentList &TemplateArgs); 10485 10486 // Objective-C declarations. 10487 enum ObjCContainerKind { 10488 OCK_None = -1, 10489 OCK_Interface = 0, 10490 OCK_Protocol, 10491 OCK_Category, 10492 OCK_ClassExtension, 10493 OCK_Implementation, 10494 OCK_CategoryImplementation 10495 }; 10496 ObjCContainerKind getObjCContainerKind() const; 10497 10498 DeclResult actOnObjCTypeParam(Scope *S, 10499 ObjCTypeParamVariance variance, 10500 SourceLocation varianceLoc, 10501 unsigned index, 10502 IdentifierInfo *paramName, 10503 SourceLocation paramLoc, 10504 SourceLocation colonLoc, 10505 ParsedType typeBound); 10506 10507 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, 10508 ArrayRef<Decl *> typeParams, 10509 SourceLocation rAngleLoc); 10510 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); 10511 10512 ObjCInterfaceDecl *ActOnStartClassInterface( 10513 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 10514 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 10515 IdentifierInfo *SuperName, SourceLocation SuperLoc, 10516 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, 10517 Decl *const *ProtoRefs, unsigned NumProtoRefs, 10518 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 10519 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody); 10520 10521 void ActOnSuperClassOfClassInterface(Scope *S, 10522 SourceLocation AtInterfaceLoc, 10523 ObjCInterfaceDecl *IDecl, 10524 IdentifierInfo *ClassName, 10525 SourceLocation ClassLoc, 10526 IdentifierInfo *SuperName, 10527 SourceLocation SuperLoc, 10528 ArrayRef<ParsedType> SuperTypeArgs, 10529 SourceRange SuperTypeArgsRange); 10530 10531 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 10532 SmallVectorImpl<SourceLocation> &ProtocolLocs, 10533 IdentifierInfo *SuperName, 10534 SourceLocation SuperLoc); 10535 10536 Decl *ActOnCompatibilityAlias( 10537 SourceLocation AtCompatibilityAliasLoc, 10538 IdentifierInfo *AliasName, SourceLocation AliasLocation, 10539 IdentifierInfo *ClassName, SourceLocation ClassLocation); 10540 10541 bool CheckForwardProtocolDeclarationForCircularDependency( 10542 IdentifierInfo *PName, 10543 SourceLocation &PLoc, SourceLocation PrevLoc, 10544 const ObjCList<ObjCProtocolDecl> &PList); 10545 10546 ObjCProtocolDecl *ActOnStartProtocolInterface( 10547 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, 10548 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, 10549 unsigned NumProtoRefs, const SourceLocation *ProtoLocs, 10550 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList, 10551 SkipBodyInfo *SkipBody); 10552 10553 ObjCCategoryDecl *ActOnStartCategoryInterface( 10554 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 10555 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 10556 IdentifierInfo *CategoryName, SourceLocation CategoryLoc, 10557 Decl *const *ProtoRefs, unsigned NumProtoRefs, 10558 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 10559 const ParsedAttributesView &AttrList); 10560 10561 ObjCImplementationDecl *ActOnStartClassImplementation( 10562 SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, 10563 SourceLocation ClassLoc, IdentifierInfo *SuperClassname, 10564 SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); 10565 10566 ObjCCategoryImplDecl *ActOnStartCategoryImplementation( 10567 SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, 10568 SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, 10569 const ParsedAttributesView &AttrList); 10570 10571 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 10572 ArrayRef<Decl *> Decls); 10573 10574 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 10575 IdentifierInfo **IdentList, 10576 SourceLocation *IdentLocs, 10577 ArrayRef<ObjCTypeParamList *> TypeParamLists, 10578 unsigned NumElts); 10579 10580 DeclGroupPtrTy 10581 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 10582 ArrayRef<IdentifierLocPair> IdentList, 10583 const ParsedAttributesView &attrList); 10584 10585 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 10586 ArrayRef<IdentifierLocPair> ProtocolId, 10587 SmallVectorImpl<Decl *> &Protocols); 10588 10589 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, 10590 SourceLocation ProtocolLoc, 10591 IdentifierInfo *TypeArgId, 10592 SourceLocation TypeArgLoc, 10593 bool SelectProtocolFirst = false); 10594 10595 /// Given a list of identifiers (and their locations), resolve the 10596 /// names to either Objective-C protocol qualifiers or type 10597 /// arguments, as appropriate. 10598 void actOnObjCTypeArgsOrProtocolQualifiers( 10599 Scope *S, 10600 ParsedType baseType, 10601 SourceLocation lAngleLoc, 10602 ArrayRef<IdentifierInfo *> identifiers, 10603 ArrayRef<SourceLocation> identifierLocs, 10604 SourceLocation rAngleLoc, 10605 SourceLocation &typeArgsLAngleLoc, 10606 SmallVectorImpl<ParsedType> &typeArgs, 10607 SourceLocation &typeArgsRAngleLoc, 10608 SourceLocation &protocolLAngleLoc, 10609 SmallVectorImpl<Decl *> &protocols, 10610 SourceLocation &protocolRAngleLoc, 10611 bool warnOnIncompleteProtocols); 10612 10613 /// Build a an Objective-C protocol-qualified 'id' type where no 10614 /// base type was specified. 10615 TypeResult actOnObjCProtocolQualifierType( 10616 SourceLocation lAngleLoc, 10617 ArrayRef<Decl *> protocols, 10618 ArrayRef<SourceLocation> protocolLocs, 10619 SourceLocation rAngleLoc); 10620 10621 /// Build a specialized and/or protocol-qualified Objective-C type. 10622 TypeResult actOnObjCTypeArgsAndProtocolQualifiers( 10623 Scope *S, 10624 SourceLocation Loc, 10625 ParsedType BaseType, 10626 SourceLocation TypeArgsLAngleLoc, 10627 ArrayRef<ParsedType> TypeArgs, 10628 SourceLocation TypeArgsRAngleLoc, 10629 SourceLocation ProtocolLAngleLoc, 10630 ArrayRef<Decl *> Protocols, 10631 ArrayRef<SourceLocation> ProtocolLocs, 10632 SourceLocation ProtocolRAngleLoc); 10633 10634 /// Build an Objective-C type parameter type. 10635 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, 10636 SourceLocation ProtocolLAngleLoc, 10637 ArrayRef<ObjCProtocolDecl *> Protocols, 10638 ArrayRef<SourceLocation> ProtocolLocs, 10639 SourceLocation ProtocolRAngleLoc, 10640 bool FailOnError = false); 10641 10642 /// Build an Objective-C object pointer type. 10643 QualType BuildObjCObjectType( 10644 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, 10645 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, 10646 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, 10647 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, 10648 bool FailOnError, bool Rebuilding); 10649 10650 /// Ensure attributes are consistent with type. 10651 /// \param [in, out] Attributes The attributes to check; they will 10652 /// be modified to be consistent with \p PropertyTy. 10653 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 10654 SourceLocation Loc, 10655 unsigned &Attributes, 10656 bool propertyInPrimaryClass); 10657 10658 /// Process the specified property declaration and create decls for the 10659 /// setters and getters as needed. 10660 /// \param property The property declaration being processed 10661 void ProcessPropertyDecl(ObjCPropertyDecl *property); 10662 10663 10664 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 10665 ObjCPropertyDecl *SuperProperty, 10666 const IdentifierInfo *Name, 10667 bool OverridingProtocolProperty); 10668 10669 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 10670 ObjCInterfaceDecl *ID); 10671 10672 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 10673 ArrayRef<Decl *> allMethods = std::nullopt, 10674 ArrayRef<DeclGroupPtrTy> allTUVars = std::nullopt); 10675 10676 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 10677 SourceLocation LParenLoc, 10678 FieldDeclarator &FD, ObjCDeclSpec &ODS, 10679 Selector GetterSel, Selector SetterSel, 10680 tok::ObjCKeywordKind MethodImplKind, 10681 DeclContext *lexicalDC = nullptr); 10682 10683 Decl *ActOnPropertyImplDecl(Scope *S, 10684 SourceLocation AtLoc, 10685 SourceLocation PropertyLoc, 10686 bool ImplKind, 10687 IdentifierInfo *PropertyId, 10688 IdentifierInfo *PropertyIvar, 10689 SourceLocation PropertyIvarLoc, 10690 ObjCPropertyQueryKind QueryKind); 10691 10692 enum ObjCSpecialMethodKind { 10693 OSMK_None, 10694 OSMK_Alloc, 10695 OSMK_New, 10696 OSMK_Copy, 10697 OSMK_RetainingInit, 10698 OSMK_NonRetainingInit 10699 }; 10700 10701 struct ObjCArgInfo { 10702 IdentifierInfo *Name; 10703 SourceLocation NameLoc; 10704 // The Type is null if no type was specified, and the DeclSpec is invalid 10705 // in this case. 10706 ParsedType Type; 10707 ObjCDeclSpec DeclSpec; 10708 10709 /// ArgAttrs - Attribute list for this argument. 10710 ParsedAttributesView ArgAttrs; 10711 }; 10712 10713 Decl *ActOnMethodDeclaration( 10714 Scope *S, 10715 SourceLocation BeginLoc, // location of the + or -. 10716 SourceLocation EndLoc, // location of the ; or {. 10717 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 10718 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 10719 // optional arguments. The number of types/arguments is obtained 10720 // from the Sel.getNumArgs(). 10721 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, 10722 unsigned CNumArgs, // c-style args 10723 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, 10724 bool isVariadic, bool MethodDefinition); 10725 10726 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 10727 const ObjCObjectPointerType *OPT, 10728 bool IsInstance); 10729 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 10730 bool IsInstance); 10731 10732 bool CheckARCMethodDecl(ObjCMethodDecl *method); 10733 bool inferObjCARCLifetime(ValueDecl *decl); 10734 10735 void deduceOpenCLAddressSpace(ValueDecl *decl); 10736 10737 ExprResult 10738 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 10739 Expr *BaseExpr, 10740 SourceLocation OpLoc, 10741 DeclarationName MemberName, 10742 SourceLocation MemberLoc, 10743 SourceLocation SuperLoc, QualType SuperType, 10744 bool Super); 10745 10746 ExprResult 10747 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 10748 IdentifierInfo &propertyName, 10749 SourceLocation receiverNameLoc, 10750 SourceLocation propertyNameLoc); 10751 10752 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 10753 10754 /// Describes the kind of message expression indicated by a message 10755 /// send that starts with an identifier. 10756 enum ObjCMessageKind { 10757 /// The message is sent to 'super'. 10758 ObjCSuperMessage, 10759 /// The message is an instance message. 10760 ObjCInstanceMessage, 10761 /// The message is a class message, and the identifier is a type 10762 /// name. 10763 ObjCClassMessage 10764 }; 10765 10766 ObjCMessageKind getObjCMessageKind(Scope *S, 10767 IdentifierInfo *Name, 10768 SourceLocation NameLoc, 10769 bool IsSuper, 10770 bool HasTrailingDot, 10771 ParsedType &ReceiverType); 10772 10773 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 10774 Selector Sel, 10775 SourceLocation LBracLoc, 10776 ArrayRef<SourceLocation> SelectorLocs, 10777 SourceLocation RBracLoc, 10778 MultiExprArg Args); 10779 10780 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 10781 QualType ReceiverType, 10782 SourceLocation SuperLoc, 10783 Selector Sel, 10784 ObjCMethodDecl *Method, 10785 SourceLocation LBracLoc, 10786 ArrayRef<SourceLocation> SelectorLocs, 10787 SourceLocation RBracLoc, 10788 MultiExprArg Args, 10789 bool isImplicit = false); 10790 10791 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 10792 bool isSuperReceiver, 10793 SourceLocation Loc, 10794 Selector Sel, 10795 ObjCMethodDecl *Method, 10796 MultiExprArg Args); 10797 10798 ExprResult ActOnClassMessage(Scope *S, 10799 ParsedType Receiver, 10800 Selector Sel, 10801 SourceLocation LBracLoc, 10802 ArrayRef<SourceLocation> SelectorLocs, 10803 SourceLocation RBracLoc, 10804 MultiExprArg Args); 10805 10806 ExprResult BuildInstanceMessage(Expr *Receiver, 10807 QualType ReceiverType, 10808 SourceLocation SuperLoc, 10809 Selector Sel, 10810 ObjCMethodDecl *Method, 10811 SourceLocation LBracLoc, 10812 ArrayRef<SourceLocation> SelectorLocs, 10813 SourceLocation RBracLoc, 10814 MultiExprArg Args, 10815 bool isImplicit = false); 10816 10817 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 10818 QualType ReceiverType, 10819 SourceLocation Loc, 10820 Selector Sel, 10821 ObjCMethodDecl *Method, 10822 MultiExprArg Args); 10823 10824 ExprResult ActOnInstanceMessage(Scope *S, 10825 Expr *Receiver, 10826 Selector Sel, 10827 SourceLocation LBracLoc, 10828 ArrayRef<SourceLocation> SelectorLocs, 10829 SourceLocation RBracLoc, 10830 MultiExprArg Args); 10831 10832 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 10833 ObjCBridgeCastKind Kind, 10834 SourceLocation BridgeKeywordLoc, 10835 TypeSourceInfo *TSInfo, 10836 Expr *SubExpr); 10837 10838 ExprResult ActOnObjCBridgedCast(Scope *S, 10839 SourceLocation LParenLoc, 10840 ObjCBridgeCastKind Kind, 10841 SourceLocation BridgeKeywordLoc, 10842 ParsedType Type, 10843 SourceLocation RParenLoc, 10844 Expr *SubExpr); 10845 10846 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); 10847 10848 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); 10849 10850 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 10851 CastKind &Kind); 10852 10853 bool checkObjCBridgeRelatedComponents(SourceLocation Loc, 10854 QualType DestType, QualType SrcType, 10855 ObjCInterfaceDecl *&RelatedClass, 10856 ObjCMethodDecl *&ClassMethod, 10857 ObjCMethodDecl *&InstanceMethod, 10858 TypedefNameDecl *&TDNDecl, 10859 bool CfToNs, bool Diagnose = true); 10860 10861 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, 10862 QualType DestType, QualType SrcType, 10863 Expr *&SrcExpr, bool Diagnose = true); 10864 10865 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, 10866 bool Diagnose = true); 10867 10868 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 10869 10870 /// Check whether the given new method is a valid override of the 10871 /// given overridden method, and set any properties that should be inherited. 10872 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 10873 const ObjCMethodDecl *Overridden); 10874 10875 /// Describes the compatibility of a result type with its method. 10876 enum ResultTypeCompatibilityKind { 10877 RTC_Compatible, 10878 RTC_Incompatible, 10879 RTC_Unknown 10880 }; 10881 10882 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, 10883 ObjCMethodDecl *overridden); 10884 10885 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 10886 ObjCInterfaceDecl *CurrentClass, 10887 ResultTypeCompatibilityKind RTC); 10888 10889 enum PragmaOptionsAlignKind { 10890 POAK_Native, // #pragma options align=native 10891 POAK_Natural, // #pragma options align=natural 10892 POAK_Packed, // #pragma options align=packed 10893 POAK_Power, // #pragma options align=power 10894 POAK_Mac68k, // #pragma options align=mac68k 10895 POAK_Reset // #pragma options align=reset 10896 }; 10897 10898 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section 10899 void ActOnPragmaClangSection(SourceLocation PragmaLoc, 10900 PragmaClangSectionAction Action, 10901 PragmaClangSectionKind SecKind, StringRef SecName); 10902 10903 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 10904 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 10905 SourceLocation PragmaLoc); 10906 10907 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 10908 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, 10909 StringRef SlotLabel, Expr *Alignment); 10910 10911 enum class PragmaAlignPackDiagnoseKind { 10912 NonDefaultStateAtInclude, 10913 ChangedStateAtExit 10914 }; 10915 10916 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, 10917 SourceLocation IncludeLoc); 10918 void DiagnoseUnterminatedPragmaAlignPack(); 10919 10920 /// ActOnPragmaMSStrictGuardStackCheck - Called on well formed \#pragma 10921 /// strict_gs_check. 10922 void ActOnPragmaMSStrictGuardStackCheck(SourceLocation PragmaLocation, 10923 PragmaMsStackAction Action, 10924 bool Value); 10925 10926 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 10927 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 10928 10929 /// ActOnPragmaMSComment - Called on well formed 10930 /// \#pragma comment(kind, "arg"). 10931 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, 10932 StringRef Arg); 10933 10934 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 10935 /// pointers_to_members(representation method[, general purpose 10936 /// representation]). 10937 void ActOnPragmaMSPointersToMembers( 10938 LangOptions::PragmaMSPointersToMembersKind Kind, 10939 SourceLocation PragmaLoc); 10940 10941 /// Called on well formed \#pragma vtordisp(). 10942 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, 10943 SourceLocation PragmaLoc, 10944 MSVtorDispMode Value); 10945 10946 enum PragmaSectionKind { 10947 PSK_DataSeg, 10948 PSK_BSSSeg, 10949 PSK_ConstSeg, 10950 PSK_CodeSeg, 10951 }; 10952 10953 bool UnifySection(StringRef SectionName, int SectionFlags, 10954 NamedDecl *TheDecl); 10955 bool UnifySection(StringRef SectionName, 10956 int SectionFlags, 10957 SourceLocation PragmaSectionLocation); 10958 10959 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 10960 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 10961 PragmaMsStackAction Action, 10962 llvm::StringRef StackSlotLabel, 10963 StringLiteral *SegmentName, 10964 llvm::StringRef PragmaName); 10965 10966 /// Called on well formed \#pragma section(). 10967 void ActOnPragmaMSSection(SourceLocation PragmaLocation, 10968 int SectionFlags, StringLiteral *SegmentName); 10969 10970 /// Called on well-formed \#pragma init_seg(). 10971 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 10972 StringLiteral *SegmentName); 10973 10974 /// Called on well-formed \#pragma alloc_text(). 10975 void ActOnPragmaMSAllocText( 10976 SourceLocation PragmaLocation, StringRef Section, 10977 const SmallVector<std::tuple<IdentifierInfo *, SourceLocation>> 10978 &Functions); 10979 10980 /// Called on #pragma clang __debug dump II 10981 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); 10982 10983 /// Called on #pragma clang __debug dump E 10984 void ActOnPragmaDump(Expr *E); 10985 10986 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 10987 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, 10988 StringRef Value); 10989 10990 /// Are precise floating point semantics currently enabled? isPreciseFPEnabled()10991 bool isPreciseFPEnabled() { 10992 return !CurFPFeatures.getAllowFPReassociate() && 10993 !CurFPFeatures.getNoSignedZero() && 10994 !CurFPFeatures.getAllowReciprocal() && 10995 !CurFPFeatures.getAllowApproxFunc(); 10996 } 10997 10998 void ActOnPragmaFPEvalMethod(SourceLocation Loc, 10999 LangOptions::FPEvalMethodKind Value); 11000 11001 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control 11002 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, 11003 PragmaFloatControlKind Value); 11004 11005 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 11006 void ActOnPragmaUnused(const Token &Identifier, 11007 Scope *curScope, 11008 SourceLocation PragmaLoc); 11009 11010 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 11011 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 11012 SourceLocation PragmaLoc); 11013 11014 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II, 11015 SourceLocation Loc); 11016 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W); 11017 11018 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 11019 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 11020 SourceLocation PragmaLoc, 11021 SourceLocation WeakNameLoc); 11022 11023 /// ActOnPragmaRedefineExtname - Called on well formed 11024 /// \#pragma redefine_extname oldname newname. 11025 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 11026 IdentifierInfo* AliasName, 11027 SourceLocation PragmaLoc, 11028 SourceLocation WeakNameLoc, 11029 SourceLocation AliasNameLoc); 11030 11031 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 11032 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 11033 IdentifierInfo* AliasName, 11034 SourceLocation PragmaLoc, 11035 SourceLocation WeakNameLoc, 11036 SourceLocation AliasNameLoc); 11037 11038 /// ActOnPragmaFPContract - Called on well formed 11039 /// \#pragma {STDC,OPENCL} FP_CONTRACT and 11040 /// \#pragma clang fp contract 11041 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); 11042 11043 /// Called on well formed 11044 /// \#pragma clang fp reassociate 11045 /// or 11046 /// \#pragma clang fp reciprocal 11047 void ActOnPragmaFPValueChangingOption(SourceLocation Loc, PragmaFPKind Kind, 11048 bool IsEnabled); 11049 11050 /// ActOnPragmaFenvAccess - Called on well formed 11051 /// \#pragma STDC FENV_ACCESS 11052 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); 11053 11054 /// ActOnPragmaCXLimitedRange - Called on well formed 11055 /// \#pragma STDC CX_LIMITED_RANGE 11056 void ActOnPragmaCXLimitedRange(SourceLocation Loc, 11057 LangOptions::ComplexRangeKind Range); 11058 11059 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. 11060 void ActOnPragmaFPExceptions(SourceLocation Loc, 11061 LangOptions::FPExceptionModeKind); 11062 11063 /// Called to set constant rounding mode for floating point operations. 11064 void ActOnPragmaFEnvRound(SourceLocation Loc, llvm::RoundingMode); 11065 11066 /// Called to set exception behavior for floating point operations. 11067 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); 11068 11069 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 11070 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 11071 void AddAlignmentAttributesForRecord(RecordDecl *RD); 11072 11073 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 11074 void AddMsStructLayoutForRecord(RecordDecl *RD); 11075 11076 /// PushNamespaceVisibilityAttr - Note that we've entered a 11077 /// namespace with a visibility attribute. 11078 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 11079 SourceLocation Loc); 11080 11081 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 11082 /// add an appropriate visibility attribute. 11083 void AddPushedVisibilityAttribute(Decl *RD); 11084 11085 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 11086 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 11087 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 11088 11089 /// FreeVisContext - Deallocate and null out VisContext. 11090 void FreeVisContext(); 11091 11092 /// AddCFAuditedAttribute - Check whether we're currently within 11093 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 11094 /// the appropriate attribute. 11095 void AddCFAuditedAttribute(Decl *D); 11096 11097 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, 11098 SourceLocation PragmaLoc, 11099 attr::ParsedSubjectMatchRuleSet Rules); 11100 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, 11101 const IdentifierInfo *Namespace); 11102 11103 /// Called on well-formed '\#pragma clang attribute pop'. 11104 void ActOnPragmaAttributePop(SourceLocation PragmaLoc, 11105 const IdentifierInfo *Namespace); 11106 11107 /// Adds the attributes that have been specified using the 11108 /// '\#pragma clang attribute push' directives to the given declaration. 11109 void AddPragmaAttributes(Scope *S, Decl *D); 11110 11111 void DiagnoseUnterminatedPragmaAttribute(); 11112 11113 /// Called on well formed \#pragma clang optimize. 11114 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 11115 11116 /// #pragma optimize("[optimization-list]", on | off). 11117 void ActOnPragmaMSOptimize(SourceLocation Loc, bool IsOn); 11118 11119 /// Call on well formed \#pragma function. 11120 void 11121 ActOnPragmaMSFunction(SourceLocation Loc, 11122 const llvm::SmallVectorImpl<StringRef> &NoBuiltins); 11123 11124 /// Get the location for the currently active "\#pragma clang optimize 11125 /// off". If this location is invalid, then the state of the pragma is "on". getOptimizeOffPragmaLocation()11126 SourceLocation getOptimizeOffPragmaLocation() const { 11127 return OptimizeOffPragmaLocation; 11128 } 11129 11130 /// Only called on function definitions; if there is a pragma in scope 11131 /// with the effect of a range-based optnone, consider marking the function 11132 /// with attribute optnone. 11133 void AddRangeBasedOptnone(FunctionDecl *FD); 11134 11135 /// Only called on function definitions; if there is a `#pragma alloc_text` 11136 /// that decides which code section the function should be in, add 11137 /// attribute section to the function. 11138 void AddSectionMSAllocText(FunctionDecl *FD); 11139 11140 /// Adds the 'optnone' attribute to the function declaration if there 11141 /// are no conflicts; Loc represents the location causing the 'optnone' 11142 /// attribute to be added (usually because of a pragma). 11143 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 11144 11145 /// Only called on function definitions; if there is a MSVC #pragma optimize 11146 /// in scope, consider changing the function's attributes based on the 11147 /// optimization list passed to the pragma. 11148 void ModifyFnAttributesMSPragmaOptimize(FunctionDecl *FD); 11149 11150 /// Only called on function definitions; if there is a pragma in scope 11151 /// with the effect of a range-based no_builtin, consider marking the function 11152 /// with attribute no_builtin. 11153 void AddImplicitMSFunctionNoBuiltinAttr(FunctionDecl *FD); 11154 11155 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 11156 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 11157 bool IsPackExpansion); 11158 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, 11159 bool IsPackExpansion); 11160 11161 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 11162 /// declaration. 11163 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 11164 Expr *OE); 11165 11166 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular 11167 /// declaration. 11168 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, 11169 Expr *ParamExpr); 11170 11171 /// AddAlignValueAttr - Adds an align_value attribute to a particular 11172 /// declaration. 11173 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); 11174 11175 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. 11176 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, 11177 StringRef Annot, MutableArrayRef<Expr *> Args); 11178 11179 /// ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs 11180 /// (unless they are value dependent or type dependent). Returns false 11181 /// and emits a diagnostic if one or more of the arguments could not be 11182 /// folded into a constant. 11183 bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, 11184 MutableArrayRef<Expr *> Args); 11185 11186 /// Create an CUDALaunchBoundsAttr attribute. 11187 CUDALaunchBoundsAttr *CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, 11188 Expr *MaxThreads, 11189 Expr *MinBlocks, 11190 Expr *MaxBlocks); 11191 11192 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular 11193 /// declaration. 11194 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 11195 Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks); 11196 11197 /// AddModeAttr - Adds a mode attribute to a particular declaration. 11198 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, 11199 bool InInstantiation = false); 11200 11201 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 11202 ParameterABI ABI); 11203 11204 enum class RetainOwnershipKind {NS, CF, OS}; 11205 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 11206 RetainOwnershipKind K, bool IsTemplateInstantiation); 11207 11208 /// Create an AMDGPUWavesPerEUAttr attribute. 11209 AMDGPUFlatWorkGroupSizeAttr * 11210 CreateAMDGPUFlatWorkGroupSizeAttr(const AttributeCommonInfo &CI, Expr *Min, 11211 Expr *Max); 11212 11213 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size 11214 /// attribute to a particular declaration. 11215 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, 11216 Expr *Min, Expr *Max); 11217 11218 /// Create an AMDGPUWavesPerEUAttr attribute. 11219 AMDGPUWavesPerEUAttr * 11220 CreateAMDGPUWavesPerEUAttr(const AttributeCommonInfo &CI, Expr *Min, 11221 Expr *Max); 11222 11223 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a 11224 /// particular declaration. 11225 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 11226 Expr *Min, Expr *Max); 11227 11228 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); 11229 11230 //===--------------------------------------------------------------------===// 11231 // C++ Coroutines 11232 // 11233 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, 11234 StringRef Keyword); 11235 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); 11236 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); 11237 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); 11238 11239 ExprResult BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc); 11240 ExprResult BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E, 11241 UnresolvedLookupExpr *Lookup); 11242 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, 11243 Expr *Awaiter, bool IsImplicit = false); 11244 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *Operand, 11245 UnresolvedLookupExpr *Lookup); 11246 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); 11247 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, 11248 bool IsImplicit = false); 11249 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); 11250 bool buildCoroutineParameterMoves(SourceLocation Loc); 11251 VarDecl *buildCoroutinePromise(SourceLocation Loc); 11252 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); 11253 11254 // Heuristically tells if the function is `get_return_object` member of a 11255 // coroutine promise_type by matching the function name. 11256 static bool CanBeGetReturnObject(const FunctionDecl *FD); 11257 static bool CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD); 11258 11259 // As a clang extension, enforces that a non-coroutine function must be marked 11260 // with [[clang::coro_wrapper]] if it returns a type marked with 11261 // [[clang::coro_return_type]]. 11262 // Expects that FD is not a coroutine. 11263 void CheckCoroutineWrapper(FunctionDecl *FD); 11264 /// Lookup 'coroutine_traits' in std namespace and std::experimental 11265 /// namespace. The namespace found is recorded in Namespace. 11266 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, 11267 SourceLocation FuncLoc); 11268 /// Check that the expression co_await promise.final_suspend() shall not be 11269 /// potentially-throwing. 11270 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); 11271 11272 //===--------------------------------------------------------------------===// 11273 // OpenMP directives and clauses. 11274 // 11275 private: 11276 void *VarDataSharingAttributesStack; 11277 11278 struct DeclareTargetContextInfo { 11279 struct MapInfo { 11280 OMPDeclareTargetDeclAttr::MapTypeTy MT; 11281 SourceLocation Loc; 11282 }; 11283 /// Explicitly listed variables and functions in a 'to' or 'link' clause. 11284 llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped; 11285 11286 /// The 'device_type' as parsed from the clause. 11287 OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; 11288 11289 /// The directive kind, `begin declare target` or `declare target`. 11290 OpenMPDirectiveKind Kind; 11291 11292 /// The directive with indirect clause. 11293 std::optional<Expr *> Indirect; 11294 11295 /// The directive location. 11296 SourceLocation Loc; 11297 DeclareTargetContextInfoDeclareTargetContextInfo11298 DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc) 11299 : Kind(Kind), Loc(Loc) {} 11300 }; 11301 11302 /// Number of nested '#pragma omp declare target' directives. 11303 SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting; 11304 11305 /// Initialization of data-sharing attributes stack. 11306 void InitDataSharingAttributesStack(); 11307 void DestroyDataSharingAttributesStack(); 11308 11309 /// Returns OpenMP nesting level for current directive. 11310 unsigned getOpenMPNestingLevel() const; 11311 11312 /// Adjusts the function scopes index for the target-based regions. 11313 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 11314 unsigned Level) const; 11315 11316 /// Returns the number of scopes associated with the construct on the given 11317 /// OpenMP level. 11318 int getNumberOfConstructScopes(unsigned Level) const; 11319 11320 /// Push new OpenMP function region for non-capturing function. 11321 void pushOpenMPFunctionRegion(); 11322 11323 /// Pop OpenMP function region for non-capturing function. 11324 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); 11325 11326 /// Analyzes and checks a loop nest for use by a loop transformation. 11327 /// 11328 /// \param Kind The loop transformation directive kind. 11329 /// \param NumLoops How many nested loops the directive is expecting. 11330 /// \param AStmt Associated statement of the transformation directive. 11331 /// \param LoopHelpers [out] The loop analysis result. 11332 /// \param Body [out] The body code nested in \p NumLoops loop. 11333 /// \param OriginalInits [out] Collection of statements and declarations that 11334 /// must have been executed/declared before entering the 11335 /// loop. 11336 /// 11337 /// \return Whether there was any error. 11338 bool checkTransformableLoopNest( 11339 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, 11340 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, 11341 Stmt *&Body, 11342 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> 11343 &OriginalInits); 11344 11345 /// Helper to keep information about the current `omp begin/end declare 11346 /// variant` nesting. 11347 struct OMPDeclareVariantScope { 11348 /// The associated OpenMP context selector. 11349 OMPTraitInfo *TI; 11350 11351 /// The associated OpenMP context selector mangling. 11352 std::string NameSuffix; 11353 11354 OMPDeclareVariantScope(OMPTraitInfo &TI); 11355 }; 11356 11357 /// Return the OMPTraitInfo for the surrounding scope, if any. getOMPTraitInfoForSurroundingScope()11358 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { 11359 return OMPDeclareVariantScopes.empty() ? nullptr 11360 : OMPDeclareVariantScopes.back().TI; 11361 } 11362 11363 /// The current `omp begin/end declare variant` scopes. 11364 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; 11365 11366 /// The current `omp begin/end assumes` scopes. 11367 SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; 11368 11369 /// All `omp assumes` we encountered so far. 11370 SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; 11371 11372 /// OMPD_loop is mapped to OMPD_for, OMPD_distribute or OMPD_simd depending 11373 /// on the parameter of the bind clause. In the methods for the 11374 /// mapped directives, check the parameters of the lastprivate clause. 11375 bool checkLastPrivateForMappedDirectives(ArrayRef<OMPClause *> Clauses); 11376 /// Depending on the bind clause of OMPD_loop map the directive to new 11377 /// directives. 11378 /// 1) loop bind(parallel) --> OMPD_for 11379 /// 2) loop bind(teams) --> OMPD_distribute 11380 /// 3) loop bind(thread) --> OMPD_simd 11381 /// This is being handled in Sema instead of Codegen because of the need for 11382 /// rigorous semantic checking in the new mapped directives. 11383 bool mapLoopConstruct(llvm::SmallVector<OMPClause *> &ClausesWithoutBind, 11384 ArrayRef<OMPClause *> Clauses, 11385 OpenMPBindClauseKind &BindKind, 11386 OpenMPDirectiveKind &Kind, 11387 OpenMPDirectiveKind &PrevMappedDirective, 11388 SourceLocation StartLoc, SourceLocation EndLoc, 11389 const DeclarationNameInfo &DirName, 11390 OpenMPDirectiveKind CancelRegion); 11391 11392 public: 11393 /// The declarator \p D defines a function in the scope \p S which is nested 11394 /// in an `omp begin/end declare variant` scope. In this method we create a 11395 /// declaration for \p D and rename \p D according to the OpenMP context 11396 /// selector of the surrounding scope. Return all base functions in \p Bases. 11397 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 11398 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, 11399 SmallVectorImpl<FunctionDecl *> &Bases); 11400 11401 /// Register \p D as specialization of all base functions in \p Bases in the 11402 /// current `omp begin/end declare variant` scope. 11403 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 11404 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); 11405 11406 /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. 11407 void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); 11408 11409 /// Can we exit an OpenMP declare variant scope at the moment. isInOpenMPDeclareVariantScope()11410 bool isInOpenMPDeclareVariantScope() const { 11411 return !OMPDeclareVariantScopes.empty(); 11412 } 11413 11414 ExprResult 11415 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, 11416 bool StrictlyPositive = true, 11417 bool SuppressExprDiags = false); 11418 11419 /// Given the potential call expression \p Call, determine if there is a 11420 /// specialization via the OpenMP declare variant mechanism available. If 11421 /// there is, return the specialized call expression, otherwise return the 11422 /// original \p Call. 11423 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, 11424 SourceLocation LParenLoc, MultiExprArg ArgExprs, 11425 SourceLocation RParenLoc, Expr *ExecConfig); 11426 11427 /// Handle a `omp begin declare variant`. 11428 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); 11429 11430 /// Handle a `omp end declare variant`. 11431 void ActOnOpenMPEndDeclareVariant(); 11432 11433 /// Checks if the variant/multiversion functions are compatible. 11434 bool areMultiversionVariantFunctionsCompatible( 11435 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 11436 const PartialDiagnostic &NoProtoDiagID, 11437 const PartialDiagnosticAt &NoteCausedDiagIDAt, 11438 const PartialDiagnosticAt &NoSupportDiagIDAt, 11439 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 11440 bool ConstexprSupported, bool CLinkageMayDiffer); 11441 11442 /// Function tries to capture lambda's captured variables in the OpenMP region 11443 /// before the original lambda is captured. 11444 void tryCaptureOpenMPLambdas(ValueDecl *V); 11445 11446 /// Return true if the provided declaration \a VD should be captured by 11447 /// reference. 11448 /// \param Level Relative level of nested OpenMP construct for that the check 11449 /// is performed. 11450 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. 11451 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 11452 unsigned OpenMPCaptureLevel) const; 11453 11454 /// Check if the specified variable is used in one of the private 11455 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP 11456 /// constructs. 11457 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, 11458 unsigned StopAt = 0); 11459 11460 /// The member expression(this->fd) needs to be rebuilt in the template 11461 /// instantiation to generate private copy for OpenMP when default 11462 /// clause is used. The function will return true if default 11463 /// cluse is used. 11464 bool isOpenMPRebuildMemberExpr(ValueDecl *D); 11465 11466 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 11467 ExprObjectKind OK, SourceLocation Loc); 11468 11469 /// If the current region is a loop-based region, mark the start of the loop 11470 /// construct. 11471 void startOpenMPLoop(); 11472 11473 /// If the current region is a range loop-based region, mark the start of the 11474 /// loop construct. 11475 void startOpenMPCXXRangeFor(); 11476 11477 /// Check if the specified variable is used in 'private' clause. 11478 /// \param Level Relative level of nested OpenMP construct for that the check 11479 /// is performed. 11480 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 11481 unsigned CapLevel) const; 11482 11483 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) 11484 /// for \p FD based on DSA for the provided corresponding captured declaration 11485 /// \p D. 11486 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); 11487 11488 /// Check if the specified variable is captured by 'target' directive. 11489 /// \param Level Relative level of nested OpenMP construct for that the check 11490 /// is performed. 11491 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 11492 unsigned CaptureLevel) const; 11493 11494 /// Check if the specified global variable must be captured by outer capture 11495 /// regions. 11496 /// \param Level Relative level of nested OpenMP construct for that 11497 /// the check is performed. 11498 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 11499 unsigned CaptureLevel) const; 11500 11501 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, 11502 Expr *Op); 11503 /// Called on start of new data sharing attribute block. 11504 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 11505 const DeclarationNameInfo &DirName, Scope *CurScope, 11506 SourceLocation Loc); 11507 /// Start analysis of clauses. 11508 void StartOpenMPClause(OpenMPClauseKind K); 11509 /// End analysis of clauses. 11510 void EndOpenMPClause(); 11511 /// Called on end of data sharing attribute block. 11512 void EndOpenMPDSABlock(Stmt *CurDirective); 11513 11514 /// Check if the current region is an OpenMP loop region and if it is, 11515 /// mark loop control variable, used in \p Init for loop initialization, as 11516 /// private by default. 11517 /// \param Init First part of the for loop. 11518 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); 11519 11520 /// Called on well-formed '\#pragma omp metadirective' after parsing 11521 /// of the associated statement. 11522 StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses, 11523 Stmt *AStmt, SourceLocation StartLoc, 11524 SourceLocation EndLoc); 11525 11526 // OpenMP directives and clauses. 11527 /// Called on correct id-expression from the '#pragma omp 11528 /// threadprivate'. 11529 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, 11530 const DeclarationNameInfo &Id, 11531 OpenMPDirectiveKind Kind); 11532 /// Called on well-formed '#pragma omp threadprivate'. 11533 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 11534 SourceLocation Loc, 11535 ArrayRef<Expr *> VarList); 11536 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. 11537 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, 11538 ArrayRef<Expr *> VarList); 11539 /// Called on well-formed '#pragma omp allocate'. 11540 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, 11541 ArrayRef<Expr *> VarList, 11542 ArrayRef<OMPClause *> Clauses, 11543 DeclContext *Owner = nullptr); 11544 11545 /// Called on well-formed '#pragma omp [begin] assume[s]'. 11546 void ActOnOpenMPAssumesDirective(SourceLocation Loc, 11547 OpenMPDirectiveKind DKind, 11548 ArrayRef<std::string> Assumptions, 11549 bool SkippedClauses); 11550 11551 /// Check if there is an active global `omp begin assumes` directive. isInOpenMPAssumeScope()11552 bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } 11553 11554 /// Check if there is an active global `omp assumes` directive. hasGlobalOpenMPAssumes()11555 bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } 11556 11557 /// Called on well-formed '#pragma omp end assumes'. 11558 void ActOnOpenMPEndAssumesDirective(); 11559 11560 /// Called on well-formed '#pragma omp requires'. 11561 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, 11562 ArrayRef<OMPClause *> ClauseList); 11563 /// Check restrictions on Requires directive 11564 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, 11565 ArrayRef<OMPClause *> Clauses); 11566 /// Check if the specified type is allowed to be used in 'omp declare 11567 /// reduction' construct. 11568 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 11569 TypeResult ParsedType); 11570 /// Called on start of '#pragma omp declare reduction'. 11571 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( 11572 Scope *S, DeclContext *DC, DeclarationName Name, 11573 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 11574 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); 11575 /// Initialize declare reduction construct initializer. 11576 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); 11577 /// Finish current declare reduction construct initializer. 11578 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); 11579 /// Initialize declare reduction construct initializer. 11580 /// \return omp_priv variable. 11581 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); 11582 /// Finish current declare reduction construct initializer. 11583 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 11584 VarDecl *OmpPrivParm); 11585 /// Called at the end of '#pragma omp declare reduction'. 11586 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( 11587 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); 11588 11589 /// Check variable declaration in 'omp declare mapper' construct. 11590 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); 11591 /// Check if the specified type is allowed to be used in 'omp declare 11592 /// mapper' construct. 11593 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 11594 TypeResult ParsedType); 11595 /// Called on start of '#pragma omp declare mapper'. 11596 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( 11597 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 11598 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 11599 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, 11600 Decl *PrevDeclInScope = nullptr); 11601 /// Build the mapper variable of '#pragma omp declare mapper'. 11602 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, 11603 QualType MapperType, 11604 SourceLocation StartLoc, 11605 DeclarationName VN); 11606 void ActOnOpenMPIteratorVarDecl(VarDecl *VD); 11607 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; 11608 const ValueDecl *getOpenMPDeclareMapperVarName() const; 11609 11610 /// Called on the start of target region i.e. '#pragma omp declare target'. 11611 bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); 11612 11613 /// Called at the end of target region i.e. '#pragma omp end declare target'. 11614 const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective(); 11615 11616 /// Called once a target context is completed, that can be when a 11617 /// '#pragma omp end declare target' was encountered or when a 11618 /// '#pragma omp declare target' without declaration-definition-seq was 11619 /// encountered. 11620 void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); 11621 11622 /// Report unterminated 'omp declare target' or 'omp begin declare target' at 11623 /// the end of a compilation unit. 11624 void DiagnoseUnterminatedOpenMPDeclareTarget(); 11625 11626 /// Searches for the provided declaration name for OpenMP declare target 11627 /// directive. 11628 NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope, 11629 CXXScopeSpec &ScopeSpec, 11630 const DeclarationNameInfo &Id); 11631 11632 /// Called on correct id-expression from the '#pragma omp declare target'. 11633 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 11634 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11635 DeclareTargetContextInfo &DTCI); 11636 11637 /// Check declaration inside target region. 11638 void 11639 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 11640 SourceLocation IdLoc = SourceLocation()); 11641 11642 /// Adds OMPDeclareTargetDeclAttr to referenced variables in declare target 11643 /// directive. 11644 void ActOnOpenMPDeclareTargetInitializer(Decl *D); 11645 11646 /// Finishes analysis of the deferred functions calls that may be declared as 11647 /// host/nohost during device/host compilation. 11648 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 11649 const FunctionDecl *Callee, 11650 SourceLocation Loc); 11651 11652 /// Return true if currently in OpenMP task with untied clause context. 11653 bool isInOpenMPTaskUntiedContext() const; 11654 11655 /// Return true inside OpenMP declare target region. isInOpenMPDeclareTargetContext()11656 bool isInOpenMPDeclareTargetContext() const { 11657 return !DeclareTargetNesting.empty(); 11658 } 11659 /// Return true inside OpenMP target region. 11660 bool isInOpenMPTargetExecutionDirective() const; 11661 11662 /// Return the number of captured regions created for an OpenMP directive. 11663 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); 11664 11665 /// Initialization of captured region for OpenMP region. 11666 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); 11667 11668 /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to 11669 /// an OpenMP loop directive. 11670 StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt); 11671 11672 /// Process a canonical OpenMP loop nest that can either be a canonical 11673 /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an 11674 /// OpenMP loop transformation construct. 11675 StmtResult ActOnOpenMPLoopnest(Stmt *AStmt); 11676 11677 /// End of OpenMP region. 11678 /// 11679 /// \param S Statement associated with the current OpenMP region. 11680 /// \param Clauses List of clauses for the current OpenMP region. 11681 /// 11682 /// \returns Statement for finished OpenMP region. 11683 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); 11684 StmtResult ActOnOpenMPExecutableDirective( 11685 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 11686 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 11687 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, 11688 OpenMPDirectiveKind PrevMappedDirective = llvm::omp::OMPD_unknown); 11689 /// Called on well-formed '\#pragma omp parallel' after parsing 11690 /// of the associated statement. 11691 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 11692 Stmt *AStmt, 11693 SourceLocation StartLoc, 11694 SourceLocation EndLoc); 11695 using VarsWithInheritedDSAType = 11696 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; 11697 /// Called on well-formed '\#pragma omp simd' after parsing 11698 /// of the associated statement. 11699 StmtResult 11700 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 11701 SourceLocation StartLoc, SourceLocation EndLoc, 11702 VarsWithInheritedDSAType &VarsWithImplicitDSA); 11703 /// Called on well-formed '#pragma omp tile' after parsing of its clauses and 11704 /// the associated statement. 11705 StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 11706 Stmt *AStmt, SourceLocation StartLoc, 11707 SourceLocation EndLoc); 11708 /// Called on well-formed '#pragma omp unroll' after parsing of its clauses 11709 /// and the associated statement. 11710 StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, 11711 Stmt *AStmt, SourceLocation StartLoc, 11712 SourceLocation EndLoc); 11713 /// Called on well-formed '\#pragma omp for' after parsing 11714 /// of the associated statement. 11715 StmtResult 11716 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 11717 SourceLocation StartLoc, SourceLocation EndLoc, 11718 VarsWithInheritedDSAType &VarsWithImplicitDSA); 11719 /// Called on well-formed '\#pragma omp for simd' after parsing 11720 /// of the associated statement. 11721 StmtResult 11722 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 11723 SourceLocation StartLoc, SourceLocation EndLoc, 11724 VarsWithInheritedDSAType &VarsWithImplicitDSA); 11725 /// Called on well-formed '\#pragma omp sections' after parsing 11726 /// of the associated statement. 11727 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 11728 Stmt *AStmt, SourceLocation StartLoc, 11729 SourceLocation EndLoc); 11730 /// Called on well-formed '\#pragma omp section' after parsing of the 11731 /// associated statement. 11732 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, 11733 SourceLocation EndLoc); 11734 /// Called on well-formed '\#pragma omp scope' after parsing of the 11735 /// associated statement. 11736 StmtResult ActOnOpenMPScopeDirective(ArrayRef<OMPClause *> Clauses, 11737 Stmt *AStmt, SourceLocation StartLoc, 11738 SourceLocation EndLoc); 11739 /// Called on well-formed '\#pragma omp single' after parsing of the 11740 /// associated statement. 11741 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 11742 Stmt *AStmt, SourceLocation StartLoc, 11743 SourceLocation EndLoc); 11744 /// Called on well-formed '\#pragma omp master' after parsing of the 11745 /// associated statement. 11746 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, 11747 SourceLocation EndLoc); 11748 /// Called on well-formed '\#pragma omp critical' after parsing of the 11749 /// associated statement. 11750 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 11751 ArrayRef<OMPClause *> Clauses, 11752 Stmt *AStmt, SourceLocation StartLoc, 11753 SourceLocation EndLoc); 11754 /// Called on well-formed '\#pragma omp parallel for' after parsing 11755 /// of the associated statement. 11756 StmtResult ActOnOpenMPParallelForDirective( 11757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11758 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11759 /// Called on well-formed '\#pragma omp parallel for simd' after 11760 /// parsing of the associated statement. 11761 StmtResult ActOnOpenMPParallelForSimdDirective( 11762 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11763 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11764 /// Called on well-formed '\#pragma omp parallel master' after 11765 /// parsing of the associated statement. 11766 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 11767 Stmt *AStmt, 11768 SourceLocation StartLoc, 11769 SourceLocation EndLoc); 11770 /// Called on well-formed '\#pragma omp parallel masked' after 11771 /// parsing of the associated statement. 11772 StmtResult ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses, 11773 Stmt *AStmt, 11774 SourceLocation StartLoc, 11775 SourceLocation EndLoc); 11776 /// Called on well-formed '\#pragma omp parallel sections' after 11777 /// parsing of the associated statement. 11778 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 11779 Stmt *AStmt, 11780 SourceLocation StartLoc, 11781 SourceLocation EndLoc); 11782 /// Called on well-formed '\#pragma omp task' after parsing of the 11783 /// associated statement. 11784 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 11785 Stmt *AStmt, SourceLocation StartLoc, 11786 SourceLocation EndLoc); 11787 /// Called on well-formed '\#pragma omp taskyield'. 11788 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 11789 SourceLocation EndLoc); 11790 /// Called on well-formed '\#pragma omp error'. 11791 /// Error direcitive is allowed in both declared and excutable contexts. 11792 /// Adding InExContext to identify which context is called from. 11793 StmtResult ActOnOpenMPErrorDirective(ArrayRef<OMPClause *> Clauses, 11794 SourceLocation StartLoc, 11795 SourceLocation EndLoc, 11796 bool InExContext = true); 11797 /// Called on well-formed '\#pragma omp barrier'. 11798 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 11799 SourceLocation EndLoc); 11800 /// Called on well-formed '\#pragma omp taskwait'. 11801 StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, 11802 SourceLocation StartLoc, 11803 SourceLocation EndLoc); 11804 /// Called on well-formed '\#pragma omp taskgroup'. 11805 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 11806 Stmt *AStmt, SourceLocation StartLoc, 11807 SourceLocation EndLoc); 11808 /// Called on well-formed '\#pragma omp flush'. 11809 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 11810 SourceLocation StartLoc, 11811 SourceLocation EndLoc); 11812 /// Called on well-formed '\#pragma omp depobj'. 11813 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 11814 SourceLocation StartLoc, 11815 SourceLocation EndLoc); 11816 /// Called on well-formed '\#pragma omp scan'. 11817 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 11818 SourceLocation StartLoc, 11819 SourceLocation EndLoc); 11820 /// Called on well-formed '\#pragma omp ordered' after parsing of the 11821 /// associated statement. 11822 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 11823 Stmt *AStmt, SourceLocation StartLoc, 11824 SourceLocation EndLoc); 11825 /// Called on well-formed '\#pragma omp atomic' after parsing of the 11826 /// associated statement. 11827 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 11828 Stmt *AStmt, SourceLocation StartLoc, 11829 SourceLocation EndLoc); 11830 /// Called on well-formed '\#pragma omp target' after parsing of the 11831 /// associated statement. 11832 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 11833 Stmt *AStmt, SourceLocation StartLoc, 11834 SourceLocation EndLoc); 11835 /// Called on well-formed '\#pragma omp target data' after parsing of 11836 /// the associated statement. 11837 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 11838 Stmt *AStmt, SourceLocation StartLoc, 11839 SourceLocation EndLoc); 11840 /// Called on well-formed '\#pragma omp target enter data' after 11841 /// parsing of the associated statement. 11842 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 11843 SourceLocation StartLoc, 11844 SourceLocation EndLoc, 11845 Stmt *AStmt); 11846 /// Called on well-formed '\#pragma omp target exit data' after 11847 /// parsing of the associated statement. 11848 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 11849 SourceLocation StartLoc, 11850 SourceLocation EndLoc, 11851 Stmt *AStmt); 11852 /// Called on well-formed '\#pragma omp target parallel' after 11853 /// parsing of the associated statement. 11854 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 11855 Stmt *AStmt, 11856 SourceLocation StartLoc, 11857 SourceLocation EndLoc); 11858 /// Called on well-formed '\#pragma omp target parallel for' after 11859 /// parsing of the associated statement. 11860 StmtResult ActOnOpenMPTargetParallelForDirective( 11861 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11862 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11863 /// Called on well-formed '\#pragma omp teams' after parsing of the 11864 /// associated statement. 11865 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 11866 Stmt *AStmt, SourceLocation StartLoc, 11867 SourceLocation EndLoc); 11868 /// Called on well-formed '\#pragma omp teams loop' after parsing of the 11869 /// associated statement. 11870 StmtResult ActOnOpenMPTeamsGenericLoopDirective( 11871 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11872 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11873 /// Called on well-formed '\#pragma omp target teams loop' after parsing of 11874 /// the associated statement. 11875 StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective( 11876 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11877 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11878 /// Called on well-formed '\#pragma omp parallel loop' after parsing of the 11879 /// associated statement. 11880 StmtResult ActOnOpenMPParallelGenericLoopDirective( 11881 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11882 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11883 /// Called on well-formed '\#pragma omp target parallel loop' after parsing 11884 /// of the associated statement. 11885 StmtResult ActOnOpenMPTargetParallelGenericLoopDirective( 11886 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11887 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11888 /// Called on well-formed '\#pragma omp cancellation point'. 11889 StmtResult 11890 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 11891 SourceLocation EndLoc, 11892 OpenMPDirectiveKind CancelRegion); 11893 /// Called on well-formed '\#pragma omp cancel'. 11894 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 11895 SourceLocation StartLoc, 11896 SourceLocation EndLoc, 11897 OpenMPDirectiveKind CancelRegion); 11898 /// Called on well-formed '\#pragma omp taskloop' after parsing of the 11899 /// associated statement. 11900 StmtResult 11901 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 11902 SourceLocation StartLoc, SourceLocation EndLoc, 11903 VarsWithInheritedDSAType &VarsWithImplicitDSA); 11904 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of 11905 /// the associated statement. 11906 StmtResult ActOnOpenMPTaskLoopSimdDirective( 11907 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11908 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11909 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the 11910 /// associated statement. 11911 StmtResult ActOnOpenMPMasterTaskLoopDirective( 11912 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11913 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11914 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of 11915 /// the associated statement. 11916 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( 11917 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11918 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11919 /// Called on well-formed '\#pragma omp parallel master taskloop' after 11920 /// parsing of the associated statement. 11921 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( 11922 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11923 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11924 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after 11925 /// parsing of the associated statement. 11926 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( 11927 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11928 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11929 /// Called on well-formed '\#pragma omp masked taskloop' after parsing of the 11930 /// associated statement. 11931 StmtResult ActOnOpenMPMaskedTaskLoopDirective( 11932 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11933 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11934 /// Called on well-formed '\#pragma omp masked taskloop simd' after parsing of 11935 /// the associated statement. 11936 StmtResult ActOnOpenMPMaskedTaskLoopSimdDirective( 11937 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11938 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11939 /// Called on well-formed '\#pragma omp parallel masked taskloop' after 11940 /// parsing of the associated statement. 11941 StmtResult ActOnOpenMPParallelMaskedTaskLoopDirective( 11942 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11943 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11944 /// Called on well-formed '\#pragma omp parallel masked taskloop simd' after 11945 /// parsing of the associated statement. 11946 StmtResult ActOnOpenMPParallelMaskedTaskLoopSimdDirective( 11947 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11948 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11949 /// Called on well-formed '\#pragma omp distribute' after parsing 11950 /// of the associated statement. 11951 StmtResult 11952 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 11953 SourceLocation StartLoc, SourceLocation EndLoc, 11954 VarsWithInheritedDSAType &VarsWithImplicitDSA); 11955 /// Called on well-formed '\#pragma omp target update'. 11956 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 11957 SourceLocation StartLoc, 11958 SourceLocation EndLoc, 11959 Stmt *AStmt); 11960 /// Called on well-formed '\#pragma omp distribute parallel for' after 11961 /// parsing of the associated statement. 11962 StmtResult ActOnOpenMPDistributeParallelForDirective( 11963 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11964 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11965 /// Called on well-formed '\#pragma omp distribute parallel for simd' 11966 /// after parsing of the associated statement. 11967 StmtResult ActOnOpenMPDistributeParallelForSimdDirective( 11968 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11969 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11970 /// Called on well-formed '\#pragma omp distribute simd' after 11971 /// parsing of the associated statement. 11972 StmtResult ActOnOpenMPDistributeSimdDirective( 11973 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11974 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11975 /// Called on well-formed '\#pragma omp target parallel for simd' after 11976 /// parsing of the associated statement. 11977 StmtResult ActOnOpenMPTargetParallelForSimdDirective( 11978 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11979 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11980 /// Called on well-formed '\#pragma omp target simd' after parsing of 11981 /// the associated statement. 11982 StmtResult 11983 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 11984 SourceLocation StartLoc, SourceLocation EndLoc, 11985 VarsWithInheritedDSAType &VarsWithImplicitDSA); 11986 /// Called on well-formed '\#pragma omp teams distribute' after parsing of 11987 /// the associated statement. 11988 StmtResult ActOnOpenMPTeamsDistributeDirective( 11989 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11990 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11991 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing 11992 /// of the associated statement. 11993 StmtResult ActOnOpenMPTeamsDistributeSimdDirective( 11994 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11995 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 11996 /// Called on well-formed '\#pragma omp teams distribute parallel for simd' 11997 /// after parsing of the associated statement. 11998 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( 11999 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12000 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 12001 /// Called on well-formed '\#pragma omp teams distribute parallel for' 12002 /// after parsing of the associated statement. 12003 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( 12004 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12005 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 12006 /// Called on well-formed '\#pragma omp target teams' after parsing of the 12007 /// associated statement. 12008 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 12009 Stmt *AStmt, 12010 SourceLocation StartLoc, 12011 SourceLocation EndLoc); 12012 /// Called on well-formed '\#pragma omp target teams distribute' after parsing 12013 /// of the associated statement. 12014 StmtResult ActOnOpenMPTargetTeamsDistributeDirective( 12015 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12016 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 12017 /// Called on well-formed '\#pragma omp target teams distribute parallel for' 12018 /// after parsing of the associated statement. 12019 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( 12020 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12021 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 12022 /// Called on well-formed '\#pragma omp target teams distribute parallel for 12023 /// simd' after parsing of the associated statement. 12024 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 12025 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12026 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 12027 /// Called on well-formed '\#pragma omp target teams distribute simd' after 12028 /// parsing of the associated statement. 12029 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( 12030 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12031 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 12032 /// Called on well-formed '\#pragma omp interop'. 12033 StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 12034 SourceLocation StartLoc, 12035 SourceLocation EndLoc); 12036 /// Called on well-formed '\#pragma omp dispatch' after parsing of the 12037 // /associated statement. 12038 StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 12039 Stmt *AStmt, SourceLocation StartLoc, 12040 SourceLocation EndLoc); 12041 /// Called on well-formed '\#pragma omp masked' after parsing of the 12042 // /associated statement. 12043 StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 12044 Stmt *AStmt, SourceLocation StartLoc, 12045 SourceLocation EndLoc); 12046 12047 /// Called on well-formed '\#pragma omp loop' after parsing of the 12048 /// associated statement. 12049 StmtResult ActOnOpenMPGenericLoopDirective( 12050 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12051 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 12052 12053 /// Checks correctness of linear modifiers. 12054 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 12055 SourceLocation LinLoc); 12056 /// Checks that the specified declaration matches requirements for the linear 12057 /// decls. 12058 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 12059 OpenMPLinearClauseKind LinKind, QualType Type, 12060 bool IsDeclareSimd = false); 12061 12062 /// Called on well-formed '\#pragma omp declare simd' after parsing of 12063 /// the associated method/function. 12064 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( 12065 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, 12066 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 12067 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 12068 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); 12069 12070 /// Checks '\#pragma omp declare variant' variant function and original 12071 /// functions after parsing of the associated method/function. 12072 /// \param DG Function declaration to which declare variant directive is 12073 /// applied to. 12074 /// \param VariantRef Expression that references the variant function, which 12075 /// must be used instead of the original one, specified in \p DG. 12076 /// \param TI The trait info object representing the match clause. 12077 /// \param NumAppendArgs The number of omp_interop_t arguments to account for 12078 /// in checking. 12079 /// \returns std::nullopt, if the function/variant function are not compatible 12080 /// with the pragma, pair of original function/variant ref expression 12081 /// otherwise. 12082 std::optional<std::pair<FunctionDecl *, Expr *>> 12083 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, 12084 OMPTraitInfo &TI, unsigned NumAppendArgs, 12085 SourceRange SR); 12086 12087 /// Called on well-formed '\#pragma omp declare variant' after parsing of 12088 /// the associated method/function. 12089 /// \param FD Function declaration to which declare variant directive is 12090 /// applied to. 12091 /// \param VariantRef Expression that references the variant function, which 12092 /// must be used instead of the original one, specified in \p DG. 12093 /// \param TI The context traits associated with the function variant. 12094 /// \param AdjustArgsNothing The list of 'nothing' arguments. 12095 /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments. 12096 /// \param AppendArgs The list of 'append_args' arguments. 12097 /// \param AdjustArgsLoc The Location of an 'adjust_args' clause. 12098 /// \param AppendArgsLoc The Location of an 'append_args' clause. 12099 /// \param SR The SourceRange of the 'declare variant' directive. 12100 void ActOnOpenMPDeclareVariantDirective( 12101 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, 12102 ArrayRef<Expr *> AdjustArgsNothing, 12103 ArrayRef<Expr *> AdjustArgsNeedDevicePtr, 12104 ArrayRef<OMPInteropInfo> AppendArgs, SourceLocation AdjustArgsLoc, 12105 SourceLocation AppendArgsLoc, SourceRange SR); 12106 12107 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, 12108 Expr *Expr, 12109 SourceLocation StartLoc, 12110 SourceLocation LParenLoc, 12111 SourceLocation EndLoc); 12112 /// Called on well-formed 'allocator' clause. 12113 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, 12114 SourceLocation StartLoc, 12115 SourceLocation LParenLoc, 12116 SourceLocation EndLoc); 12117 /// Called on well-formed 'if' clause. 12118 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 12119 Expr *Condition, SourceLocation StartLoc, 12120 SourceLocation LParenLoc, 12121 SourceLocation NameModifierLoc, 12122 SourceLocation ColonLoc, 12123 SourceLocation EndLoc); 12124 /// Called on well-formed 'final' clause. 12125 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, 12126 SourceLocation LParenLoc, 12127 SourceLocation EndLoc); 12128 /// Called on well-formed 'num_threads' clause. 12129 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, 12130 SourceLocation StartLoc, 12131 SourceLocation LParenLoc, 12132 SourceLocation EndLoc); 12133 /// Called on well-formed 'align' clause. 12134 OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc, 12135 SourceLocation LParenLoc, 12136 SourceLocation EndLoc); 12137 /// Called on well-formed 'safelen' clause. 12138 OMPClause *ActOnOpenMPSafelenClause(Expr *Length, 12139 SourceLocation StartLoc, 12140 SourceLocation LParenLoc, 12141 SourceLocation EndLoc); 12142 /// Called on well-formed 'simdlen' clause. 12143 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, 12144 SourceLocation LParenLoc, 12145 SourceLocation EndLoc); 12146 /// Called on well-form 'sizes' clause. 12147 OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 12148 SourceLocation StartLoc, 12149 SourceLocation LParenLoc, 12150 SourceLocation EndLoc); 12151 /// Called on well-form 'full' clauses. 12152 OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc, 12153 SourceLocation EndLoc); 12154 /// Called on well-form 'partial' clauses. 12155 OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc, 12156 SourceLocation LParenLoc, 12157 SourceLocation EndLoc); 12158 /// Called on well-formed 'collapse' clause. 12159 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, 12160 SourceLocation StartLoc, 12161 SourceLocation LParenLoc, 12162 SourceLocation EndLoc); 12163 /// Called on well-formed 'ordered' clause. 12164 OMPClause * 12165 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, 12166 SourceLocation LParenLoc = SourceLocation(), 12167 Expr *NumForLoops = nullptr); 12168 /// Called on well-formed 'grainsize' clause. 12169 OMPClause *ActOnOpenMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier, 12170 Expr *Size, SourceLocation StartLoc, 12171 SourceLocation LParenLoc, 12172 SourceLocation ModifierLoc, 12173 SourceLocation EndLoc); 12174 /// Called on well-formed 'num_tasks' clause. 12175 OMPClause *ActOnOpenMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier, 12176 Expr *NumTasks, SourceLocation StartLoc, 12177 SourceLocation LParenLoc, 12178 SourceLocation ModifierLoc, 12179 SourceLocation EndLoc); 12180 /// Called on well-formed 'hint' clause. 12181 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 12182 SourceLocation LParenLoc, 12183 SourceLocation EndLoc); 12184 /// Called on well-formed 'detach' clause. 12185 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 12186 SourceLocation LParenLoc, 12187 SourceLocation EndLoc); 12188 12189 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 12190 unsigned Argument, 12191 SourceLocation ArgumentLoc, 12192 SourceLocation StartLoc, 12193 SourceLocation LParenLoc, 12194 SourceLocation EndLoc); 12195 /// Called on well-formed 'when' clause. 12196 OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc, 12197 SourceLocation LParenLoc, 12198 SourceLocation EndLoc); 12199 /// Called on well-formed 'default' clause. 12200 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, 12201 SourceLocation KindLoc, 12202 SourceLocation StartLoc, 12203 SourceLocation LParenLoc, 12204 SourceLocation EndLoc); 12205 /// Called on well-formed 'proc_bind' clause. 12206 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, 12207 SourceLocation KindLoc, 12208 SourceLocation StartLoc, 12209 SourceLocation LParenLoc, 12210 SourceLocation EndLoc); 12211 /// Called on well-formed 'order' clause. 12212 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseModifier Modifier, 12213 OpenMPOrderClauseKind Kind, 12214 SourceLocation StartLoc, 12215 SourceLocation LParenLoc, 12216 SourceLocation MLoc, SourceLocation KindLoc, 12217 SourceLocation EndLoc); 12218 /// Called on well-formed 'update' clause. 12219 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 12220 SourceLocation KindLoc, 12221 SourceLocation StartLoc, 12222 SourceLocation LParenLoc, 12223 SourceLocation EndLoc); 12224 12225 OMPClause *ActOnOpenMPSingleExprWithArgClause( 12226 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, 12227 SourceLocation StartLoc, SourceLocation LParenLoc, 12228 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, 12229 SourceLocation EndLoc); 12230 /// Called on well-formed 'schedule' clause. 12231 OMPClause *ActOnOpenMPScheduleClause( 12232 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 12233 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 12234 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 12235 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); 12236 12237 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, 12238 SourceLocation EndLoc); 12239 /// Called on well-formed 'nowait' clause. 12240 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, 12241 SourceLocation EndLoc); 12242 /// Called on well-formed 'untied' clause. 12243 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, 12244 SourceLocation EndLoc); 12245 /// Called on well-formed 'mergeable' clause. 12246 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, 12247 SourceLocation EndLoc); 12248 /// Called on well-formed 'read' clause. 12249 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, 12250 SourceLocation EndLoc); 12251 /// Called on well-formed 'write' clause. 12252 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, 12253 SourceLocation EndLoc); 12254 /// Called on well-formed 'update' clause. 12255 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, 12256 SourceLocation EndLoc); 12257 /// Called on well-formed 'capture' clause. 12258 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, 12259 SourceLocation EndLoc); 12260 /// Called on well-formed 'compare' clause. 12261 OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc, 12262 SourceLocation EndLoc); 12263 /// Called on well-formed 'fail' clause. 12264 OMPClause *ActOnOpenMPFailClause(SourceLocation StartLoc, 12265 SourceLocation EndLoc); 12266 OMPClause *ActOnOpenMPFailClause( 12267 OpenMPClauseKind Kind, SourceLocation KindLoc, 12268 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 12269 12270 /// Called on well-formed 'seq_cst' clause. 12271 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 12272 SourceLocation EndLoc); 12273 /// Called on well-formed 'acq_rel' clause. 12274 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 12275 SourceLocation EndLoc); 12276 /// Called on well-formed 'acquire' clause. 12277 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, 12278 SourceLocation EndLoc); 12279 /// Called on well-formed 'release' clause. 12280 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, 12281 SourceLocation EndLoc); 12282 /// Called on well-formed 'relaxed' clause. 12283 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 12284 SourceLocation EndLoc); 12285 12286 /// Called on well-formed 'init' clause. 12287 OMPClause * 12288 ActOnOpenMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo, 12289 SourceLocation StartLoc, SourceLocation LParenLoc, 12290 SourceLocation VarLoc, SourceLocation EndLoc); 12291 12292 /// Called on well-formed 'use' clause. 12293 OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 12294 SourceLocation LParenLoc, 12295 SourceLocation VarLoc, SourceLocation EndLoc); 12296 12297 /// Called on well-formed 'destroy' clause. 12298 OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, 12299 SourceLocation LParenLoc, 12300 SourceLocation VarLoc, 12301 SourceLocation EndLoc); 12302 /// Called on well-formed 'novariants' clause. 12303 OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition, 12304 SourceLocation StartLoc, 12305 SourceLocation LParenLoc, 12306 SourceLocation EndLoc); 12307 /// Called on well-formed 'nocontext' clause. 12308 OMPClause *ActOnOpenMPNocontextClause(Expr *Condition, 12309 SourceLocation StartLoc, 12310 SourceLocation LParenLoc, 12311 SourceLocation EndLoc); 12312 /// Called on well-formed 'filter' clause. 12313 OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc, 12314 SourceLocation LParenLoc, 12315 SourceLocation EndLoc); 12316 /// Called on well-formed 'threads' clause. 12317 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, 12318 SourceLocation EndLoc); 12319 /// Called on well-formed 'simd' clause. 12320 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, 12321 SourceLocation EndLoc); 12322 /// Called on well-formed 'nogroup' clause. 12323 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, 12324 SourceLocation EndLoc); 12325 /// Called on well-formed 'unified_address' clause. 12326 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 12327 SourceLocation EndLoc); 12328 12329 /// Called on well-formed 'unified_address' clause. 12330 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 12331 SourceLocation EndLoc); 12332 12333 /// Called on well-formed 'reverse_offload' clause. 12334 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 12335 SourceLocation EndLoc); 12336 12337 /// Called on well-formed 'dynamic_allocators' clause. 12338 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 12339 SourceLocation EndLoc); 12340 12341 /// Called on well-formed 'atomic_default_mem_order' clause. 12342 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( 12343 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, 12344 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 12345 12346 /// Called on well-formed 'at' clause. 12347 OMPClause *ActOnOpenMPAtClause(OpenMPAtClauseKind Kind, 12348 SourceLocation KindLoc, 12349 SourceLocation StartLoc, 12350 SourceLocation LParenLoc, 12351 SourceLocation EndLoc); 12352 12353 /// Called on well-formed 'severity' clause. 12354 OMPClause *ActOnOpenMPSeverityClause(OpenMPSeverityClauseKind Kind, 12355 SourceLocation KindLoc, 12356 SourceLocation StartLoc, 12357 SourceLocation LParenLoc, 12358 SourceLocation EndLoc); 12359 12360 /// Called on well-formed 'message' clause. 12361 /// passing string for message. 12362 OMPClause *ActOnOpenMPMessageClause(Expr *MS, SourceLocation StartLoc, 12363 SourceLocation LParenLoc, 12364 SourceLocation EndLoc); 12365 12366 /// Data used for processing a list of variables in OpenMP clauses. 12367 struct OpenMPVarListDataTy final { 12368 Expr *DepModOrTailExpr = nullptr; 12369 Expr *IteratorExpr = nullptr; 12370 SourceLocation ColonLoc; 12371 SourceLocation RLoc; 12372 CXXScopeSpec ReductionOrMapperIdScopeSpec; 12373 DeclarationNameInfo ReductionOrMapperId; 12374 int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or 12375 ///< lastprivate clause. 12376 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 12377 MapTypeModifiers; 12378 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 12379 MapTypeModifiersLoc; 12380 SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers> 12381 MotionModifiers; 12382 SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc; 12383 bool IsMapTypeImplicit = false; 12384 SourceLocation ExtraModifierLoc; 12385 SourceLocation OmpAllMemoryLoc; 12386 SourceLocation 12387 StepModifierLoc; /// 'step' modifier location for linear clause 12388 }; 12389 12390 OMPClause *ActOnOpenMPVarListClause(OpenMPClauseKind Kind, 12391 ArrayRef<Expr *> Vars, 12392 const OMPVarListLocTy &Locs, 12393 OpenMPVarListDataTy &Data); 12394 /// Called on well-formed 'inclusive' clause. 12395 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 12396 SourceLocation StartLoc, 12397 SourceLocation LParenLoc, 12398 SourceLocation EndLoc); 12399 /// Called on well-formed 'exclusive' clause. 12400 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 12401 SourceLocation StartLoc, 12402 SourceLocation LParenLoc, 12403 SourceLocation EndLoc); 12404 /// Called on well-formed 'allocate' clause. 12405 OMPClause * 12406 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, 12407 SourceLocation StartLoc, SourceLocation ColonLoc, 12408 SourceLocation LParenLoc, SourceLocation EndLoc); 12409 /// Called on well-formed 'private' clause. 12410 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 12411 SourceLocation StartLoc, 12412 SourceLocation LParenLoc, 12413 SourceLocation EndLoc); 12414 /// Called on well-formed 'firstprivate' clause. 12415 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 12416 SourceLocation StartLoc, 12417 SourceLocation LParenLoc, 12418 SourceLocation EndLoc); 12419 /// Called on well-formed 'lastprivate' clause. 12420 OMPClause *ActOnOpenMPLastprivateClause( 12421 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 12422 SourceLocation LPKindLoc, SourceLocation ColonLoc, 12423 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 12424 /// Called on well-formed 'shared' clause. 12425 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 12426 SourceLocation StartLoc, 12427 SourceLocation LParenLoc, 12428 SourceLocation EndLoc); 12429 /// Called on well-formed 'reduction' clause. 12430 OMPClause *ActOnOpenMPReductionClause( 12431 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 12432 SourceLocation StartLoc, SourceLocation LParenLoc, 12433 SourceLocation ModifierLoc, SourceLocation ColonLoc, 12434 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 12435 const DeclarationNameInfo &ReductionId, 12436 ArrayRef<Expr *> UnresolvedReductions = std::nullopt); 12437 /// Called on well-formed 'task_reduction' clause. 12438 OMPClause *ActOnOpenMPTaskReductionClause( 12439 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12440 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 12441 CXXScopeSpec &ReductionIdScopeSpec, 12442 const DeclarationNameInfo &ReductionId, 12443 ArrayRef<Expr *> UnresolvedReductions = std::nullopt); 12444 /// Called on well-formed 'in_reduction' clause. 12445 OMPClause *ActOnOpenMPInReductionClause( 12446 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12447 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 12448 CXXScopeSpec &ReductionIdScopeSpec, 12449 const DeclarationNameInfo &ReductionId, 12450 ArrayRef<Expr *> UnresolvedReductions = std::nullopt); 12451 /// Called on well-formed 'linear' clause. 12452 OMPClause *ActOnOpenMPLinearClause( 12453 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 12454 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 12455 SourceLocation LinLoc, SourceLocation ColonLoc, 12456 SourceLocation StepModifierLoc, SourceLocation EndLoc); 12457 /// Called on well-formed 'aligned' clause. 12458 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, 12459 Expr *Alignment, 12460 SourceLocation StartLoc, 12461 SourceLocation LParenLoc, 12462 SourceLocation ColonLoc, 12463 SourceLocation EndLoc); 12464 /// Called on well-formed 'copyin' clause. 12465 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 12466 SourceLocation StartLoc, 12467 SourceLocation LParenLoc, 12468 SourceLocation EndLoc); 12469 /// Called on well-formed 'copyprivate' clause. 12470 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 12471 SourceLocation StartLoc, 12472 SourceLocation LParenLoc, 12473 SourceLocation EndLoc); 12474 /// Called on well-formed 'flush' pseudo clause. 12475 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 12476 SourceLocation StartLoc, 12477 SourceLocation LParenLoc, 12478 SourceLocation EndLoc); 12479 /// Called on well-formed 'depobj' pseudo clause. 12480 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 12481 SourceLocation LParenLoc, 12482 SourceLocation EndLoc); 12483 /// Called on well-formed 'depend' clause. 12484 OMPClause *ActOnOpenMPDependClause(const OMPDependClause::DependDataTy &Data, 12485 Expr *DepModifier, 12486 ArrayRef<Expr *> VarList, 12487 SourceLocation StartLoc, 12488 SourceLocation LParenLoc, 12489 SourceLocation EndLoc); 12490 /// Called on well-formed 'device' clause. 12491 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 12492 Expr *Device, SourceLocation StartLoc, 12493 SourceLocation LParenLoc, 12494 SourceLocation ModifierLoc, 12495 SourceLocation EndLoc); 12496 /// Called on well-formed 'map' clause. 12497 OMPClause *ActOnOpenMPMapClause( 12498 Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 12499 ArrayRef<SourceLocation> MapTypeModifiersLoc, 12500 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 12501 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 12502 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 12503 const OMPVarListLocTy &Locs, bool NoDiagnose = false, 12504 ArrayRef<Expr *> UnresolvedMappers = std::nullopt); 12505 /// Called on well-formed 'num_teams' clause. 12506 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, 12507 SourceLocation LParenLoc, 12508 SourceLocation EndLoc); 12509 /// Called on well-formed 'thread_limit' clause. 12510 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 12511 SourceLocation StartLoc, 12512 SourceLocation LParenLoc, 12513 SourceLocation EndLoc); 12514 /// Called on well-formed 'priority' clause. 12515 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, 12516 SourceLocation LParenLoc, 12517 SourceLocation EndLoc); 12518 /// Called on well-formed 'dist_schedule' clause. 12519 OMPClause *ActOnOpenMPDistScheduleClause( 12520 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, 12521 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, 12522 SourceLocation CommaLoc, SourceLocation EndLoc); 12523 /// Called on well-formed 'defaultmap' clause. 12524 OMPClause *ActOnOpenMPDefaultmapClause( 12525 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 12526 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 12527 SourceLocation KindLoc, SourceLocation EndLoc); 12528 /// Called on well-formed 'to' clause. 12529 OMPClause * 12530 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 12531 ArrayRef<SourceLocation> MotionModifiersLoc, 12532 CXXScopeSpec &MapperIdScopeSpec, 12533 DeclarationNameInfo &MapperId, SourceLocation ColonLoc, 12534 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 12535 ArrayRef<Expr *> UnresolvedMappers = std::nullopt); 12536 /// Called on well-formed 'from' clause. 12537 OMPClause * 12538 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 12539 ArrayRef<SourceLocation> MotionModifiersLoc, 12540 CXXScopeSpec &MapperIdScopeSpec, 12541 DeclarationNameInfo &MapperId, SourceLocation ColonLoc, 12542 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 12543 ArrayRef<Expr *> UnresolvedMappers = std::nullopt); 12544 /// Called on well-formed 'use_device_ptr' clause. 12545 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 12546 const OMPVarListLocTy &Locs); 12547 /// Called on well-formed 'use_device_addr' clause. 12548 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 12549 const OMPVarListLocTy &Locs); 12550 /// Called on well-formed 'is_device_ptr' clause. 12551 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 12552 const OMPVarListLocTy &Locs); 12553 /// Called on well-formed 'has_device_addr' clause. 12554 OMPClause *ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList, 12555 const OMPVarListLocTy &Locs); 12556 /// Called on well-formed 'nontemporal' clause. 12557 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 12558 SourceLocation StartLoc, 12559 SourceLocation LParenLoc, 12560 SourceLocation EndLoc); 12561 12562 /// Data for list of allocators. 12563 struct UsesAllocatorsData { 12564 /// Allocator. 12565 Expr *Allocator = nullptr; 12566 /// Allocator traits. 12567 Expr *AllocatorTraits = nullptr; 12568 /// Locations of '(' and ')' symbols. 12569 SourceLocation LParenLoc, RParenLoc; 12570 }; 12571 /// Called on well-formed 'uses_allocators' clause. 12572 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, 12573 SourceLocation LParenLoc, 12574 SourceLocation EndLoc, 12575 ArrayRef<UsesAllocatorsData> Data); 12576 /// Called on well-formed 'affinity' clause. 12577 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, 12578 SourceLocation LParenLoc, 12579 SourceLocation ColonLoc, 12580 SourceLocation EndLoc, Expr *Modifier, 12581 ArrayRef<Expr *> Locators); 12582 /// Called on a well-formed 'bind' clause. 12583 OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, 12584 SourceLocation KindLoc, 12585 SourceLocation StartLoc, 12586 SourceLocation LParenLoc, 12587 SourceLocation EndLoc); 12588 12589 /// Called on a well-formed 'ompx_dyn_cgroup_mem' clause. 12590 OMPClause *ActOnOpenMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc, 12591 SourceLocation LParenLoc, 12592 SourceLocation EndLoc); 12593 12594 /// Called on well-formed 'doacross' clause. 12595 OMPClause * 12596 ActOnOpenMPDoacrossClause(OpenMPDoacrossClauseModifier DepType, 12597 SourceLocation DepLoc, SourceLocation ColonLoc, 12598 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12599 SourceLocation LParenLoc, SourceLocation EndLoc); 12600 12601 /// Called on a well-formed 'ompx_attribute' clause. 12602 OMPClause *ActOnOpenMPXAttributeClause(ArrayRef<const Attr *> Attrs, 12603 SourceLocation StartLoc, 12604 SourceLocation LParenLoc, 12605 SourceLocation EndLoc); 12606 12607 /// Called on a well-formed 'ompx_bare' clause. 12608 OMPClause *ActOnOpenMPXBareClause(SourceLocation StartLoc, 12609 SourceLocation EndLoc); 12610 12611 /// The kind of conversion being performed. 12612 enum CheckedConversionKind { 12613 /// An implicit conversion. 12614 CCK_ImplicitConversion, 12615 /// A C-style cast. 12616 CCK_CStyleCast, 12617 /// A functional-style cast. 12618 CCK_FunctionalCast, 12619 /// A cast other than a C-style cast. 12620 CCK_OtherCast, 12621 /// A conversion for an operand of a builtin overloaded operator. 12622 CCK_ForBuiltinOverloadedOp 12623 }; 12624 isCast(CheckedConversionKind CCK)12625 static bool isCast(CheckedConversionKind CCK) { 12626 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || 12627 CCK == CCK_OtherCast; 12628 } 12629 12630 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 12631 /// cast. If there is already an implicit cast, merge into the existing one. 12632 /// If isLvalue, the result of the cast is an lvalue. 12633 ExprResult 12634 ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 12635 ExprValueKind VK = VK_PRValue, 12636 const CXXCastPath *BasePath = nullptr, 12637 CheckedConversionKind CCK = CCK_ImplicitConversion); 12638 12639 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 12640 /// to the conversion from scalar type ScalarTy to the Boolean type. 12641 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 12642 12643 /// IgnoredValueConversions - Given that an expression's result is 12644 /// syntactically ignored, perform any conversions that are 12645 /// required. 12646 ExprResult IgnoredValueConversions(Expr *E); 12647 12648 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 12649 // functions and arrays to their respective pointers (C99 6.3.2.1). 12650 ExprResult UsualUnaryConversions(Expr *E); 12651 12652 /// CallExprUnaryConversions - a special case of an unary conversion 12653 /// performed on a function designator of a call expression. 12654 ExprResult CallExprUnaryConversions(Expr *E); 12655 12656 // DefaultFunctionArrayConversion - converts functions and arrays 12657 // to their respective pointers (C99 6.3.2.1). 12658 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); 12659 12660 // DefaultFunctionArrayLvalueConversion - converts functions and 12661 // arrays to their respective pointers and performs the 12662 // lvalue-to-rvalue conversion. 12663 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, 12664 bool Diagnose = true); 12665 12666 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 12667 // the operand. This function is a no-op if the operand has a function type 12668 // or an array type. 12669 ExprResult DefaultLvalueConversion(Expr *E); 12670 12671 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 12672 // do not have a prototype. Integer promotions are performed on each 12673 // argument, and arguments that have type float are promoted to double. 12674 ExprResult DefaultArgumentPromotion(Expr *E); 12675 12676 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize 12677 /// it as an xvalue. In C++98, the result will still be a prvalue, because 12678 /// we don't have xvalues there. 12679 ExprResult TemporaryMaterializationConversion(Expr *E); 12680 12681 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 12682 enum VariadicCallType { 12683 VariadicFunction, 12684 VariadicBlock, 12685 VariadicMethod, 12686 VariadicConstructor, 12687 VariadicDoesNotApply 12688 }; 12689 12690 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 12691 const FunctionProtoType *Proto, 12692 Expr *Fn); 12693 12694 // Used for determining in which context a type is allowed to be passed to a 12695 // vararg function. 12696 enum VarArgKind { 12697 VAK_Valid, 12698 VAK_ValidInCXX11, 12699 VAK_Undefined, 12700 VAK_MSVCUndefined, 12701 VAK_Invalid 12702 }; 12703 12704 // Determines which VarArgKind fits an expression. 12705 VarArgKind isValidVarArgType(const QualType &Ty); 12706 12707 /// Check to see if the given expression is a valid argument to a variadic 12708 /// function, issuing a diagnostic if not. 12709 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 12710 12711 /// Check whether the given statement can have musttail applied to it, 12712 /// issuing a diagnostic and returning false if not. In the success case, 12713 /// the statement is rewritten to remove implicit nodes from the return 12714 /// value. 12715 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); 12716 12717 private: 12718 /// Check whether the given statement can have musttail applied to it, 12719 /// issuing a diagnostic and returning false if not. 12720 bool checkMustTailAttr(const Stmt *St, const Attr &MTA); 12721 12722 public: 12723 /// Check to see if a given expression could have '.c_str()' called on it. 12724 bool hasCStrMethod(const Expr *E); 12725 12726 /// GatherArgumentsForCall - Collector argument expressions for various 12727 /// form of call prototypes. 12728 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 12729 const FunctionProtoType *Proto, 12730 unsigned FirstParam, ArrayRef<Expr *> Args, 12731 SmallVectorImpl<Expr *> &AllArgs, 12732 VariadicCallType CallType = VariadicDoesNotApply, 12733 bool AllowExplicit = false, 12734 bool IsListInitialization = false); 12735 12736 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 12737 // will create a runtime trap if the resulting type is not a POD type. 12738 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 12739 FunctionDecl *FDecl); 12740 12741 /// Context in which we're performing a usual arithmetic conversion. 12742 enum ArithConvKind { 12743 /// An arithmetic operation. 12744 ACK_Arithmetic, 12745 /// A bitwise operation. 12746 ACK_BitwiseOp, 12747 /// A comparison. 12748 ACK_Comparison, 12749 /// A conditional (?:) operator. 12750 ACK_Conditional, 12751 /// A compound assignment expression. 12752 ACK_CompAssign, 12753 }; 12754 12755 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 12756 // operands and then handles various conversions that are common to binary 12757 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 12758 // routine returns the first non-arithmetic type found. The client is 12759 // responsible for emitting appropriate error diagnostics. 12760 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 12761 SourceLocation Loc, ArithConvKind ACK); 12762 12763 /// AssignConvertType - All of the 'assignment' semantic checks return this 12764 /// enum to indicate whether the assignment was allowed. These checks are 12765 /// done for simple assignments, as well as initialization, return from 12766 /// function, argument passing, etc. The query is phrased in terms of a 12767 /// source and destination type. 12768 enum AssignConvertType { 12769 /// Compatible - the types are compatible according to the standard. 12770 Compatible, 12771 12772 /// PointerToInt - The assignment converts a pointer to an int, which we 12773 /// accept as an extension. 12774 PointerToInt, 12775 12776 /// IntToPointer - The assignment converts an int to a pointer, which we 12777 /// accept as an extension. 12778 IntToPointer, 12779 12780 /// FunctionVoidPointer - The assignment is between a function pointer and 12781 /// void*, which the standard doesn't allow, but we accept as an extension. 12782 FunctionVoidPointer, 12783 12784 /// IncompatiblePointer - The assignment is between two pointers types that 12785 /// are not compatible, but we accept them as an extension. 12786 IncompatiblePointer, 12787 12788 /// IncompatibleFunctionPointer - The assignment is between two function 12789 /// pointers types that are not compatible, but we accept them as an 12790 /// extension. 12791 IncompatibleFunctionPointer, 12792 12793 /// IncompatibleFunctionPointerStrict - The assignment is between two 12794 /// function pointer types that are not identical, but are compatible, 12795 /// unless compiled with -fsanitize=cfi, in which case the type mismatch 12796 /// may trip an indirect call runtime check. 12797 IncompatibleFunctionPointerStrict, 12798 12799 /// IncompatiblePointerSign - The assignment is between two pointers types 12800 /// which point to integers which have a different sign, but are otherwise 12801 /// identical. This is a subset of the above, but broken out because it's by 12802 /// far the most common case of incompatible pointers. 12803 IncompatiblePointerSign, 12804 12805 /// CompatiblePointerDiscardsQualifiers - The assignment discards 12806 /// c/v/r qualifiers, which we accept as an extension. 12807 CompatiblePointerDiscardsQualifiers, 12808 12809 /// IncompatiblePointerDiscardsQualifiers - The assignment 12810 /// discards qualifiers that we don't permit to be discarded, 12811 /// like address spaces. 12812 IncompatiblePointerDiscardsQualifiers, 12813 12814 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment 12815 /// changes address spaces in nested pointer types which is not allowed. 12816 /// For instance, converting __private int ** to __generic int ** is 12817 /// illegal even though __private could be converted to __generic. 12818 IncompatibleNestedPointerAddressSpaceMismatch, 12819 12820 /// IncompatibleNestedPointerQualifiers - The assignment is between two 12821 /// nested pointer types, and the qualifiers other than the first two 12822 /// levels differ e.g. char ** -> const char **, but we accept them as an 12823 /// extension. 12824 IncompatibleNestedPointerQualifiers, 12825 12826 /// IncompatibleVectors - The assignment is between two vector types that 12827 /// have the same size, which we accept as an extension. 12828 IncompatibleVectors, 12829 12830 /// IntToBlockPointer - The assignment converts an int to a block 12831 /// pointer. We disallow this. 12832 IntToBlockPointer, 12833 12834 /// IncompatibleBlockPointer - The assignment is between two block 12835 /// pointers types that are not compatible. 12836 IncompatibleBlockPointer, 12837 12838 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 12839 /// id type and something else (that is incompatible with it). For example, 12840 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 12841 IncompatibleObjCQualifiedId, 12842 12843 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 12844 /// object with __weak qualifier. 12845 IncompatibleObjCWeakRef, 12846 12847 /// Incompatible - We reject this conversion outright, it is invalid to 12848 /// represent it in the AST. 12849 Incompatible 12850 }; 12851 12852 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 12853 /// assignment conversion type specified by ConvTy. This returns true if the 12854 /// conversion was invalid or false if the conversion was accepted. 12855 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 12856 SourceLocation Loc, 12857 QualType DstType, QualType SrcType, 12858 Expr *SrcExpr, AssignmentAction Action, 12859 bool *Complained = nullptr); 12860 12861 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag 12862 /// enum. If AllowMask is true, then we also allow the complement of a valid 12863 /// value, to be used as a mask. 12864 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 12865 bool AllowMask) const; 12866 12867 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 12868 /// integer not in the range of enum values. 12869 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 12870 Expr *SrcExpr); 12871 12872 /// CheckAssignmentConstraints - Perform type checking for assignment, 12873 /// argument passing, variable initialization, and function return values. 12874 /// C99 6.5.16. 12875 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 12876 QualType LHSType, 12877 QualType RHSType); 12878 12879 /// Check assignment constraints and optionally prepare for a conversion of 12880 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS 12881 /// is true. 12882 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 12883 ExprResult &RHS, 12884 CastKind &Kind, 12885 bool ConvertRHS = true); 12886 12887 /// Check assignment constraints for an assignment of RHS to LHSType. 12888 /// 12889 /// \param LHSType The destination type for the assignment. 12890 /// \param RHS The source expression for the assignment. 12891 /// \param Diagnose If \c true, diagnostics may be produced when checking 12892 /// for assignability. If a diagnostic is produced, \p RHS will be 12893 /// set to ExprError(). Note that this function may still return 12894 /// without producing a diagnostic, even for an invalid assignment. 12895 /// \param DiagnoseCFAudited If \c true, the target is a function parameter 12896 /// in an audited Core Foundation API and does not need to be checked 12897 /// for ARC retain issues. 12898 /// \param ConvertRHS If \c true, \p RHS will be updated to model the 12899 /// conversions necessary to perform the assignment. If \c false, 12900 /// \p Diagnose must also be \c false. 12901 AssignConvertType CheckSingleAssignmentConstraints( 12902 QualType LHSType, ExprResult &RHS, bool Diagnose = true, 12903 bool DiagnoseCFAudited = false, bool ConvertRHS = true); 12904 12905 // If the lhs type is a transparent union, check whether we 12906 // can initialize the transparent union with the given expression. 12907 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 12908 ExprResult &RHS); 12909 12910 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 12911 12912 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 12913 12914 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 12915 AssignmentAction Action, 12916 bool AllowExplicit = false); 12917 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 12918 const ImplicitConversionSequence& ICS, 12919 AssignmentAction Action, 12920 CheckedConversionKind CCK 12921 = CCK_ImplicitConversion); 12922 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 12923 const StandardConversionSequence& SCS, 12924 AssignmentAction Action, 12925 CheckedConversionKind CCK); 12926 12927 ExprResult PerformQualificationConversion( 12928 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue, 12929 CheckedConversionKind CCK = CCK_ImplicitConversion); 12930 12931 /// the following "Check" methods will return a valid/converted QualType 12932 /// or a null QualType (indicating an error diagnostic was issued). 12933 12934 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 12935 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 12936 ExprResult &RHS); 12937 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 12938 ExprResult &RHS); 12939 QualType CheckPointerToMemberOperands( // C++ 5.5 12940 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 12941 SourceLocation OpLoc, bool isIndirect); 12942 QualType CheckMultiplyDivideOperands( // C99 6.5.5 12943 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 12944 bool IsDivide); 12945 QualType CheckRemainderOperands( // C99 6.5.5 12946 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 12947 bool IsCompAssign = false); 12948 QualType CheckAdditionOperands( // C99 6.5.6 12949 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 12950 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); 12951 QualType CheckSubtractionOperands( // C99 6.5.6 12952 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 12953 QualType* CompLHSTy = nullptr); 12954 QualType CheckShiftOperands( // C99 6.5.7 12955 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 12956 BinaryOperatorKind Opc, bool IsCompAssign = false); 12957 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); 12958 QualType CheckCompareOperands( // C99 6.5.8/9 12959 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 12960 BinaryOperatorKind Opc); 12961 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 12962 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 12963 BinaryOperatorKind Opc); 12964 QualType CheckLogicalOperands( // C99 6.5.[13,14] 12965 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 12966 BinaryOperatorKind Opc); 12967 // CheckAssignmentOperands is used for both simple and compound assignment. 12968 // For simple assignment, pass both expressions and a null converted type. 12969 // For compound assignment, pass both expressions and the converted type. 12970 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 12971 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, 12972 BinaryOperatorKind Opc); 12973 12974 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 12975 UnaryOperatorKind Opcode, Expr *Op); 12976 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 12977 BinaryOperatorKind Opcode, 12978 Expr *LHS, Expr *RHS); 12979 ExprResult checkPseudoObjectRValue(Expr *E); 12980 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 12981 12982 QualType CheckConditionalOperands( // C99 6.5.15 12983 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 12984 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 12985 QualType CXXCheckConditionalOperands( // C++ 5.16 12986 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 12987 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 12988 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 12989 ExprResult &RHS, 12990 SourceLocation QuestionLoc); 12991 12992 QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond, 12993 ExprResult &LHS, ExprResult &RHS, 12994 SourceLocation QuestionLoc); 12995 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 12996 bool ConvertArgs = true); 12997 QualType FindCompositePointerType(SourceLocation Loc, 12998 ExprResult &E1, ExprResult &E2, 12999 bool ConvertArgs = true) { 13000 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 13001 QualType Composite = 13002 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); 13003 E1 = E1Tmp; 13004 E2 = E2Tmp; 13005 return Composite; 13006 } 13007 13008 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 13009 SourceLocation QuestionLoc); 13010 13011 bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, 13012 SourceLocation QuestionLoc); 13013 13014 void DiagnoseAlwaysNonNullPointer(Expr *E, 13015 Expr::NullPointerConstantKind NullType, 13016 bool IsEqual, SourceRange Range); 13017 13018 /// type checking for vector binary operators. 13019 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 13020 SourceLocation Loc, bool IsCompAssign, 13021 bool AllowBothBool, bool AllowBoolConversion, 13022 bool AllowBoolOperation, bool ReportInvalid); 13023 QualType GetSignedVectorType(QualType V); 13024 QualType GetSignedSizelessVectorType(QualType V); 13025 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 13026 SourceLocation Loc, 13027 BinaryOperatorKind Opc); 13028 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 13029 SourceLocation Loc, 13030 BinaryOperatorKind Opc); 13031 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13032 SourceLocation Loc); 13033 13034 // type checking for sizeless vector binary operators. 13035 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 13036 SourceLocation Loc, bool IsCompAssign, 13037 ArithConvKind OperationKind); 13038 13039 /// Type checking for matrix binary operators. 13040 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 13041 SourceLocation Loc, 13042 bool IsCompAssign); 13043 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 13044 SourceLocation Loc, bool IsCompAssign); 13045 13046 bool isValidSveBitcast(QualType srcType, QualType destType); 13047 bool isValidRVVBitcast(QualType srcType, QualType destType); 13048 13049 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); 13050 13051 bool areVectorTypesSameSize(QualType srcType, QualType destType); 13052 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); 13053 bool isLaxVectorConversion(QualType srcType, QualType destType); 13054 bool anyAltivecTypes(QualType srcType, QualType destType); 13055 13056 /// type checking declaration initializers (C99 6.7.8) 13057 bool CheckForConstantInitializer(Expr *e, QualType t); 13058 13059 // type checking C++ declaration initializers (C++ [dcl.init]). 13060 13061 /// ReferenceCompareResult - Expresses the result of comparing two 13062 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 13063 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 13064 enum ReferenceCompareResult { 13065 /// Ref_Incompatible - The two types are incompatible, so direct 13066 /// reference binding is not possible. 13067 Ref_Incompatible = 0, 13068 /// Ref_Related - The two types are reference-related, which means 13069 /// that their unqualified forms (T1 and T2) are either the same 13070 /// or T1 is a base class of T2. 13071 Ref_Related, 13072 /// Ref_Compatible - The two types are reference-compatible. 13073 Ref_Compatible 13074 }; 13075 13076 // Fake up a scoped enumeration that still contextually converts to bool. 13077 struct ReferenceConversionsScope { 13078 /// The conversions that would be performed on an lvalue of type T2 when 13079 /// binding a reference of type T1 to it, as determined when evaluating 13080 /// whether T1 is reference-compatible with T2. 13081 enum ReferenceConversions { 13082 Qualification = 0x1, 13083 NestedQualification = 0x2, 13084 Function = 0x4, 13085 DerivedToBase = 0x8, 13086 ObjC = 0x10, 13087 ObjCLifetime = 0x20, 13088 13089 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) 13090 }; 13091 }; 13092 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; 13093 13094 ReferenceCompareResult 13095 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, 13096 ReferenceConversions *Conv = nullptr); 13097 13098 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13099 Expr *CastExpr, CastKind &CastKind, 13100 ExprValueKind &VK, CXXCastPath &Path); 13101 13102 /// Force an expression with unknown-type to an expression of the 13103 /// given type. 13104 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 13105 13106 /// Type-check an expression that's being passed to an 13107 /// __unknown_anytype parameter. 13108 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 13109 Expr *result, QualType ¶mType); 13110 13111 // CheckMatrixCast - Check type constraints for matrix casts. 13112 // We allow casting between matrixes of the same dimensions i.e. when they 13113 // have the same number of rows and column. Returns true if the cast is 13114 // invalid. 13115 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 13116 CastKind &Kind); 13117 13118 // CheckVectorCast - check type constraints for vectors. 13119 // Since vectors are an extension, there are no C standard reference for this. 13120 // We allow casting between vectors and integer datatypes of the same size. 13121 // returns true if the cast is invalid 13122 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 13123 CastKind &Kind); 13124 13125 /// Prepare `SplattedExpr` for a vector splat operation, adding 13126 /// implicit casts if necessary. 13127 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); 13128 13129 // CheckExtVectorCast - check type constraints for extended vectors. 13130 // Since vectors are an extension, there are no C standard reference for this. 13131 // We allow casting between vectors and integer datatypes of the same size, 13132 // or vectors and the element type of that vector. 13133 // returns the cast expr 13134 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 13135 CastKind &Kind); 13136 13137 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, 13138 SourceLocation LParenLoc, 13139 Expr *CastExpr, 13140 SourceLocation RParenLoc); 13141 13142 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; 13143 13144 /// Checks for invalid conversions and casts between 13145 /// retainable pointers and other pointer kinds for ARC and Weak. 13146 ARCConversionResult CheckObjCConversion(SourceRange castRange, 13147 QualType castType, Expr *&op, 13148 CheckedConversionKind CCK, 13149 bool Diagnose = true, 13150 bool DiagnoseCFAudited = false, 13151 BinaryOperatorKind Opc = BO_PtrMemD 13152 ); 13153 13154 Expr *stripARCUnbridgedCast(Expr *e); 13155 void diagnoseARCUnbridgedCast(Expr *e); 13156 13157 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 13158 QualType ExprType); 13159 13160 /// checkRetainCycles - Check whether an Objective-C message send 13161 /// might create an obvious retain cycle. 13162 void checkRetainCycles(ObjCMessageExpr *msg); 13163 void checkRetainCycles(Expr *receiver, Expr *argument); 13164 void checkRetainCycles(VarDecl *Var, Expr *Init); 13165 13166 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 13167 /// to weak/__unsafe_unretained type. 13168 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 13169 13170 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 13171 /// to weak/__unsafe_unretained expression. 13172 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 13173 13174 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 13175 /// \param Method - May be null. 13176 /// \param [out] ReturnType - The return type of the send. 13177 /// \return true iff there were any incompatible types. 13178 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, 13179 MultiExprArg Args, Selector Sel, 13180 ArrayRef<SourceLocation> SelectorLocs, 13181 ObjCMethodDecl *Method, bool isClassMessage, 13182 bool isSuperMessage, SourceLocation lbrac, 13183 SourceLocation rbrac, SourceRange RecRange, 13184 QualType &ReturnType, ExprValueKind &VK); 13185 13186 /// Determine the result of a message send expression based on 13187 /// the type of the receiver, the method expected to receive the message, 13188 /// and the form of the message send. 13189 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, 13190 ObjCMethodDecl *Method, bool isClassMessage, 13191 bool isSuperMessage); 13192 13193 /// If the given expression involves a message send to a method 13194 /// with a related result type, emit a note describing what happened. 13195 void EmitRelatedResultTypeNote(const Expr *E); 13196 13197 /// Given that we had incompatible pointer types in a return 13198 /// statement, check whether we're in a method with a related result 13199 /// type, and if so, emit a note describing what happened. 13200 void EmitRelatedResultTypeNoteForReturn(QualType destType); 13201 13202 class ConditionResult { 13203 Decl *ConditionVar; 13204 FullExprArg Condition; 13205 bool Invalid; 13206 std::optional<bool> KnownValue; 13207 13208 friend class Sema; ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)13209 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, 13210 bool IsConstexpr) 13211 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false) { 13212 if (IsConstexpr && Condition.get()) { 13213 if (std::optional<llvm::APSInt> Val = 13214 Condition.get()->getIntegerConstantExpr(S.Context)) { 13215 KnownValue = !!(*Val); 13216 } 13217 } 13218 } ConditionResult(bool Invalid)13219 explicit ConditionResult(bool Invalid) 13220 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), 13221 KnownValue(std::nullopt) {} 13222 13223 public: ConditionResult()13224 ConditionResult() : ConditionResult(false) {} isInvalid()13225 bool isInvalid() const { return Invalid; } get()13226 std::pair<VarDecl *, Expr *> get() const { 13227 return std::make_pair(cast_or_null<VarDecl>(ConditionVar), 13228 Condition.get()); 13229 } getKnownValue()13230 std::optional<bool> getKnownValue() const { return KnownValue; } 13231 }; ConditionError()13232 static ConditionResult ConditionError() { return ConditionResult(true); } 13233 13234 enum class ConditionKind { 13235 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. 13236 ConstexprIf, ///< A constant boolean condition from 'if constexpr'. 13237 Switch ///< An integral condition for a 'switch' statement. 13238 }; PreferredConditionType(ConditionKind K)13239 QualType PreferredConditionType(ConditionKind K) const { 13240 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy; 13241 } 13242 13243 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, 13244 ConditionKind CK, bool MissingOK = false); 13245 13246 ConditionResult ActOnConditionVariable(Decl *ConditionVar, 13247 SourceLocation StmtLoc, 13248 ConditionKind CK); 13249 13250 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 13251 13252 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 13253 SourceLocation StmtLoc, 13254 ConditionKind CK); 13255 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); 13256 13257 /// CheckBooleanCondition - Diagnose problems involving the use of 13258 /// the given expression as a boolean condition (e.g. in an if 13259 /// statement). Also performs the standard function and array 13260 /// decays, possibly changing the input variable. 13261 /// 13262 /// \param Loc - A location associated with the condition, e.g. the 13263 /// 'if' keyword. 13264 /// \return true iff there were any errors 13265 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, 13266 bool IsConstexpr = false); 13267 13268 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression 13269 /// found in an explicit(bool) specifier. 13270 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); 13271 13272 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. 13273 /// Returns true if the explicit specifier is now resolved. 13274 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); 13275 13276 /// DiagnoseAssignmentAsCondition - Given that an expression is 13277 /// being used as a boolean condition, warn if it's an assignment. 13278 void DiagnoseAssignmentAsCondition(Expr *E); 13279 13280 /// Redundant parentheses over an equality comparison can indicate 13281 /// that the user intended an assignment used as condition. 13282 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 13283 13284 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 13285 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); 13286 13287 /// Checks that the Objective-C declaration is declared in the global scope. 13288 /// Emits an error and marks the declaration as invalid if it's not declared 13289 /// in the global scope. 13290 bool CheckObjCDeclScope(Decl *D); 13291 13292 /// Abstract base class used for diagnosing integer constant 13293 /// expression violations. 13294 class VerifyICEDiagnoser { 13295 public: 13296 bool Suppress; 13297 Suppress(Suppress)13298 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 13299 13300 virtual SemaDiagnosticBuilder 13301 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); 13302 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 13303 SourceLocation Loc) = 0; 13304 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); ~VerifyICEDiagnoser()13305 virtual ~VerifyICEDiagnoser() {} 13306 }; 13307 13308 enum AllowFoldKind { 13309 NoFold, 13310 AllowFold, 13311 }; 13312 13313 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 13314 /// and reports the appropriate diagnostics. Returns false on success. 13315 /// Can optionally return the value of the expression. 13316 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13317 VerifyICEDiagnoser &Diagnoser, 13318 AllowFoldKind CanFold = NoFold); 13319 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13320 unsigned DiagID, 13321 AllowFoldKind CanFold = NoFold); 13322 ExprResult VerifyIntegerConstantExpression(Expr *E, 13323 llvm::APSInt *Result = nullptr, 13324 AllowFoldKind CanFold = NoFold); 13325 ExprResult VerifyIntegerConstantExpression(Expr *E, 13326 AllowFoldKind CanFold = NoFold) { 13327 return VerifyIntegerConstantExpression(E, nullptr, CanFold); 13328 } 13329 13330 /// VerifyBitField - verifies that a bit field expression is an ICE and has 13331 /// the correct width, and that the field type is valid. 13332 /// Returns false on success. 13333 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 13334 QualType FieldTy, bool IsMsStruct, Expr *BitWidth); 13335 13336 private: 13337 unsigned ForceCUDAHostDeviceDepth = 0; 13338 13339 public: 13340 /// Increments our count of the number of times we've seen a pragma forcing 13341 /// functions to be __host__ __device__. So long as this count is greater 13342 /// than zero, all functions encountered will be __host__ __device__. 13343 void PushForceCUDAHostDevice(); 13344 13345 /// Decrements our count of the number of times we've seen a pragma forcing 13346 /// functions to be __host__ __device__. Returns false if the count is 0 13347 /// before incrementing, so you can emit an error. 13348 bool PopForceCUDAHostDevice(); 13349 13350 /// Diagnostics that are emitted only if we discover that the given function 13351 /// must be codegen'ed. Because handling these correctly adds overhead to 13352 /// compilation, this is currently only enabled for CUDA compilations. 13353 llvm::DenseMap<CanonicalDeclPtr<const FunctionDecl>, 13354 std::vector<PartialDiagnosticAt>> 13355 DeviceDeferredDiags; 13356 13357 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the 13358 /// key in a hashtable, both the FD and location are hashed. 13359 struct FunctionDeclAndLoc { 13360 CanonicalDeclPtr<const FunctionDecl> FD; 13361 SourceLocation Loc; 13362 }; 13363 13364 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a 13365 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the 13366 /// same deferred diag twice. 13367 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; 13368 13369 /// An inverse call graph, mapping known-emitted functions to one of their 13370 /// known-emitted callers (plus the location of the call). 13371 /// 13372 /// Functions that we can tell a priori must be emitted aren't added to this 13373 /// map. 13374 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<const FunctionDecl>, 13375 /* Caller = */ FunctionDeclAndLoc> 13376 DeviceKnownEmittedFns; 13377 13378 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 13379 /// context is "used as device code". 13380 /// 13381 /// - If CurContext is a __host__ function, does not emit any diagnostics 13382 /// unless \p EmitOnBothSides is true. 13383 /// - If CurContext is a __device__ or __global__ function, emits the 13384 /// diagnostics immediately. 13385 /// - If CurContext is a __host__ __device__ function and we are compiling for 13386 /// the device, creates a diagnostic which is emitted if and when we realize 13387 /// that the function will be codegen'ed. 13388 /// 13389 /// Example usage: 13390 /// 13391 /// // Variable-length arrays are not allowed in CUDA device code. 13392 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) 13393 /// return ExprError(); 13394 /// // Otherwise, continue parsing as normal. 13395 SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, 13396 unsigned DiagID); 13397 13398 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 13399 /// context is "used as host code". 13400 /// 13401 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. 13402 SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); 13403 13404 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 13405 /// context is "used as device code". 13406 /// 13407 /// - If CurContext is a `declare target` function or it is known that the 13408 /// function is emitted for the device, emits the diagnostics immediately. 13409 /// - If CurContext is a non-`declare target` function and we are compiling 13410 /// for the device, creates a diagnostic which is emitted if and when we 13411 /// realize that the function will be codegen'ed. 13412 /// 13413 /// Example usage: 13414 /// 13415 /// // Variable-length arrays are not allowed in NVPTX device code. 13416 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) 13417 /// return ExprError(); 13418 /// // Otherwise, continue parsing as normal. 13419 SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, 13420 unsigned DiagID, 13421 const FunctionDecl *FD); 13422 13423 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 13424 /// context is "used as host code". 13425 /// 13426 /// - If CurContext is a `declare target` function or it is known that the 13427 /// function is emitted for the host, emits the diagnostics immediately. 13428 /// - If CurContext is a non-host function, just ignore it. 13429 /// 13430 /// Example usage: 13431 /// 13432 /// // Variable-length arrays are not allowed in NVPTX device code. 13433 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) 13434 /// return ExprError(); 13435 /// // Otherwise, continue parsing as normal. 13436 SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, 13437 unsigned DiagID, 13438 const FunctionDecl *FD); 13439 13440 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, 13441 const FunctionDecl *FD = nullptr); 13442 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, 13443 const PartialDiagnostic &PD, 13444 const FunctionDecl *FD = nullptr) { 13445 return targetDiag(Loc, PD.getDiagID(), FD) << PD; 13446 } 13447 13448 /// Check if the type is allowed to be used for the current target. 13449 void checkTypeSupport(QualType Ty, SourceLocation Loc, 13450 ValueDecl *D = nullptr); 13451 13452 /// Determines whether the given function is a CUDA device/host/kernel/etc. 13453 /// function. 13454 /// 13455 /// Use this rather than examining the function's attributes yourself -- you 13456 /// will get it wrong. Returns CFT_Host if D is null. 13457 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, 13458 bool IgnoreImplicitHDAttr = false); 13459 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); 13460 13461 enum CUDAVariableTarget { 13462 CVT_Device, /// Emitted on device side with a shadow variable on host side 13463 CVT_Host, /// Emitted on host side only 13464 CVT_Both, /// Emitted on both sides with different addresses 13465 CVT_Unified, /// Emitted as a unified address, e.g. managed variables 13466 }; 13467 /// Determines whether the given variable is emitted on host or device side. 13468 CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D); 13469 13470 /// Defines kinds of CUDA global host/device context where a function may be 13471 /// called. 13472 enum CUDATargetContextKind { 13473 CTCK_Unknown, /// Unknown context 13474 CTCK_InitGlobalVar, /// Function called during global variable 13475 /// initialization 13476 }; 13477 13478 /// Define the current global CUDA host/device context where a function may be 13479 /// called. Only used when a function is called outside of any functions. 13480 struct CUDATargetContext { 13481 CUDAFunctionTarget Target = CFT_HostDevice; 13482 CUDATargetContextKind Kind = CTCK_Unknown; 13483 Decl *D = nullptr; 13484 } CurCUDATargetCtx; 13485 13486 struct CUDATargetContextRAII { 13487 Sema &S; 13488 CUDATargetContext SavedCtx; 13489 CUDATargetContextRAII(Sema &S_, CUDATargetContextKind K, Decl *D); ~CUDATargetContextRAIICUDATargetContextRAII13490 ~CUDATargetContextRAII() { S.CurCUDATargetCtx = SavedCtx; } 13491 }; 13492 13493 /// Gets the CUDA target for the current context. CurrentCUDATarget()13494 CUDAFunctionTarget CurrentCUDATarget() { 13495 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); 13496 } 13497 13498 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); 13499 13500 // CUDA function call preference. Must be ordered numerically from 13501 // worst to best. 13502 enum CUDAFunctionPreference { 13503 CFP_Never, // Invalid caller/callee combination. 13504 CFP_WrongSide, // Calls from host-device to host or device 13505 // function that do not match current compilation 13506 // mode. 13507 CFP_HostDevice, // Any calls to host/device functions. 13508 CFP_SameSide, // Calls from host-device to host or device 13509 // function matching current compilation mode. 13510 CFP_Native, // host-to-host or device-to-device calls. 13511 }; 13512 13513 /// Identifies relative preference of a given Caller/Callee 13514 /// combination, based on their host/device attributes. 13515 /// \param Caller function which needs address of \p Callee. 13516 /// nullptr in case of global context. 13517 /// \param Callee target function 13518 /// 13519 /// \returns preference value for particular Caller/Callee combination. 13520 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, 13521 const FunctionDecl *Callee); 13522 13523 /// Determines whether Caller may invoke Callee, based on their CUDA 13524 /// host/device attributes. Returns false if the call is not allowed. 13525 /// 13526 /// Note: Will return true for CFP_WrongSide calls. These may appear in 13527 /// semantically correct CUDA programs, but only if they're never codegen'ed. IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)13528 bool IsAllowedCUDACall(const FunctionDecl *Caller, 13529 const FunctionDecl *Callee) { 13530 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; 13531 } 13532 13533 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, 13534 /// depending on FD and the current compilation settings. 13535 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, 13536 const LookupResult &Previous); 13537 13538 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD 13539 /// and current compilation settings. 13540 void MaybeAddCUDAConstantAttr(VarDecl *VD); 13541 13542 public: 13543 /// Check whether we're allowed to call Callee from the current context. 13544 /// 13545 /// - If the call is never allowed in a semantically-correct program 13546 /// (CFP_Never), emits an error and returns false. 13547 /// 13548 /// - If the call is allowed in semantically-correct programs, but only if 13549 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to 13550 /// be emitted if and when the caller is codegen'ed, and returns true. 13551 /// 13552 /// Will only create deferred diagnostics for a given SourceLocation once, 13553 /// so you can safely call this multiple times without generating duplicate 13554 /// deferred errors. 13555 /// 13556 /// - Otherwise, returns true without emitting any diagnostics. 13557 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); 13558 13559 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); 13560 13561 /// Set __device__ or __host__ __device__ attributes on the given lambda 13562 /// operator() method. 13563 /// 13564 /// CUDA lambdas by default is host device function unless it has explicit 13565 /// host or device attribute. 13566 void CUDASetLambdaAttrs(CXXMethodDecl *Method); 13567 13568 /// Record \p FD if it is a CUDA/HIP implicit host device function used on 13569 /// device side in device compilation. 13570 void CUDARecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD); 13571 13572 /// Finds a function in \p Matches with highest calling priority 13573 /// from \p Caller context and erases all functions with lower 13574 /// calling priority. 13575 void EraseUnwantedCUDAMatches( 13576 const FunctionDecl *Caller, 13577 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); 13578 13579 /// Given a implicit special member, infer its CUDA target from the 13580 /// calls it needs to make to underlying base/field special members. 13581 /// \param ClassDecl the class for which the member is being created. 13582 /// \param CSM the kind of special member. 13583 /// \param MemberDecl the special member itself. 13584 /// \param ConstRHS true if this is a copy operation with a const object on 13585 /// its RHS. 13586 /// \param Diagnose true if this call should emit diagnostics. 13587 /// \return true if there was an error inferring. 13588 /// The result of this call is implicit CUDA target attribute(s) attached to 13589 /// the member declaration. 13590 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, 13591 CXXSpecialMember CSM, 13592 CXXMethodDecl *MemberDecl, 13593 bool ConstRHS, 13594 bool Diagnose); 13595 13596 /// \return true if \p CD can be considered empty according to CUDA 13597 /// (E.2.3.1 in CUDA 7.5 Programming guide). 13598 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); 13599 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); 13600 13601 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In 13602 // case of error emits appropriate diagnostic and invalidates \p Var. 13603 // 13604 // \details CUDA allows only empty constructors as initializers for global 13605 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all 13606 // __shared__ variables whether they are local or not (they all are implicitly 13607 // static in CUDA). One exception is that CUDA allows constant initializers 13608 // for __constant__ and __device__ variables. 13609 void checkAllowedCUDAInitializer(VarDecl *VD); 13610 13611 /// Check whether NewFD is a valid overload for CUDA. Emits 13612 /// diagnostics and invalidates NewFD if not. 13613 void checkCUDATargetOverload(FunctionDecl *NewFD, 13614 const LookupResult &Previous); 13615 /// Copies target attributes from the template TD to the function FD. 13616 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); 13617 13618 /// Returns the name of the launch configuration function. This is the name 13619 /// of the function that will be called to configure kernel call, with the 13620 /// parameters specified via <<<>>>. 13621 std::string getCudaConfigureFuncName() const; 13622 13623 /// \name Code completion 13624 //@{ 13625 /// Describes the context in which code completion occurs. 13626 enum ParserCompletionContext { 13627 /// Code completion occurs at top-level or namespace context. 13628 PCC_Namespace, 13629 /// Code completion occurs within a class, struct, or union. 13630 PCC_Class, 13631 /// Code completion occurs within an Objective-C interface, protocol, 13632 /// or category. 13633 PCC_ObjCInterface, 13634 /// Code completion occurs within an Objective-C implementation or 13635 /// category implementation 13636 PCC_ObjCImplementation, 13637 /// Code completion occurs within the list of instance variables 13638 /// in an Objective-C interface, protocol, category, or implementation. 13639 PCC_ObjCInstanceVariableList, 13640 /// Code completion occurs following one or more template 13641 /// headers. 13642 PCC_Template, 13643 /// Code completion occurs following one or more template 13644 /// headers within a class. 13645 PCC_MemberTemplate, 13646 /// Code completion occurs within an expression. 13647 PCC_Expression, 13648 /// Code completion occurs within a statement, which may 13649 /// also be an expression or a declaration. 13650 PCC_Statement, 13651 /// Code completion occurs at the beginning of the 13652 /// initialization statement (or expression) in a for loop. 13653 PCC_ForInit, 13654 /// Code completion occurs within the condition of an if, 13655 /// while, switch, or for statement. 13656 PCC_Condition, 13657 /// Code completion occurs within the body of a function on a 13658 /// recovery path, where we do not have a specific handle on our position 13659 /// in the grammar. 13660 PCC_RecoveryInFunction, 13661 /// Code completion occurs where only a type is permitted. 13662 PCC_Type, 13663 /// Code completion occurs in a parenthesized expression, which 13664 /// might also be a type cast. 13665 PCC_ParenthesizedExpression, 13666 /// Code completion occurs within a sequence of declaration 13667 /// specifiers within a function, method, or block. 13668 PCC_LocalDeclarationSpecifiers, 13669 /// Code completion occurs at top-level in a REPL session 13670 PCC_TopLevelOrExpression, 13671 }; 13672 13673 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 13674 void CodeCompleteOrdinaryName(Scope *S, 13675 ParserCompletionContext CompletionContext); 13676 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 13677 bool AllowNonIdentifiers, 13678 bool AllowNestedNameSpecifiers); 13679 13680 struct CodeCompleteExpressionData; 13681 void CodeCompleteExpression(Scope *S, 13682 const CodeCompleteExpressionData &Data); 13683 void CodeCompleteExpression(Scope *S, QualType PreferredType, 13684 bool IsParenthesized = false); 13685 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, 13686 SourceLocation OpLoc, bool IsArrow, 13687 bool IsBaseExprStatement, 13688 QualType PreferredType); 13689 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, 13690 QualType PreferredType); 13691 void CodeCompleteTag(Scope *S, unsigned TagSpec); 13692 void CodeCompleteTypeQualifiers(DeclSpec &DS); 13693 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 13694 const VirtSpecifiers *VS = nullptr); 13695 void CodeCompleteBracketDeclarator(Scope *S); 13696 void CodeCompleteCase(Scope *S); 13697 enum class AttributeCompletion { 13698 Attribute, 13699 Scope, 13700 None, 13701 }; 13702 void CodeCompleteAttribute( 13703 AttributeCommonInfo::Syntax Syntax, 13704 AttributeCompletion Completion = AttributeCompletion::Attribute, 13705 const IdentifierInfo *Scope = nullptr); 13706 /// Determines the preferred type of the current function argument, by 13707 /// examining the signatures of all possible overloads. 13708 /// Returns null if unknown or ambiguous, or if code completion is off. 13709 /// 13710 /// If the code completion point has been reached, also reports the function 13711 /// signatures that were considered. 13712 /// 13713 /// FIXME: rename to GuessCallArgumentType to reduce confusion. 13714 QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, 13715 SourceLocation OpenParLoc); 13716 QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc, 13717 ArrayRef<Expr *> Args, 13718 SourceLocation OpenParLoc, 13719 bool Braced); 13720 QualType ProduceCtorInitMemberSignatureHelp( 13721 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 13722 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, 13723 bool Braced); 13724 QualType ProduceTemplateArgumentSignatureHelp( 13725 TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc); 13726 void CodeCompleteInitializer(Scope *S, Decl *D); 13727 /// Trigger code completion for a record of \p BaseType. \p InitExprs are 13728 /// expressions in the initializer list seen so far and \p D is the current 13729 /// Designation being parsed. 13730 void CodeCompleteDesignator(const QualType BaseType, 13731 llvm::ArrayRef<Expr *> InitExprs, 13732 const Designation &D); 13733 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); 13734 13735 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, 13736 bool IsUsingDeclaration, QualType BaseType, 13737 QualType PreferredType); 13738 void CodeCompleteUsing(Scope *S); 13739 void CodeCompleteUsingDirective(Scope *S); 13740 void CodeCompleteNamespaceDecl(Scope *S); 13741 void CodeCompleteNamespaceAliasDecl(Scope *S); 13742 void CodeCompleteOperatorName(Scope *S); 13743 void CodeCompleteConstructorInitializer( 13744 Decl *Constructor, 13745 ArrayRef<CXXCtorInitializer *> Initializers); 13746 13747 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 13748 bool AfterAmpersand); 13749 void CodeCompleteAfterFunctionEquals(Declarator &D); 13750 13751 void CodeCompleteObjCAtDirective(Scope *S); 13752 void CodeCompleteObjCAtVisibility(Scope *S); 13753 void CodeCompleteObjCAtStatement(Scope *S); 13754 void CodeCompleteObjCAtExpression(Scope *S); 13755 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 13756 void CodeCompleteObjCPropertyGetter(Scope *S); 13757 void CodeCompleteObjCPropertySetter(Scope *S); 13758 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 13759 bool IsParameter); 13760 void CodeCompleteObjCMessageReceiver(Scope *S); 13761 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 13762 ArrayRef<IdentifierInfo *> SelIdents, 13763 bool AtArgumentExpression); 13764 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 13765 ArrayRef<IdentifierInfo *> SelIdents, 13766 bool AtArgumentExpression, 13767 bool IsSuper = false); 13768 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 13769 ArrayRef<IdentifierInfo *> SelIdents, 13770 bool AtArgumentExpression, 13771 ObjCInterfaceDecl *Super = nullptr); 13772 void CodeCompleteObjCForCollection(Scope *S, 13773 DeclGroupPtrTy IterationVar); 13774 void CodeCompleteObjCSelector(Scope *S, 13775 ArrayRef<IdentifierInfo *> SelIdents); 13776 void CodeCompleteObjCProtocolReferences( 13777 ArrayRef<IdentifierLocPair> Protocols); 13778 void CodeCompleteObjCProtocolDecl(Scope *S); 13779 void CodeCompleteObjCInterfaceDecl(Scope *S); 13780 void CodeCompleteObjCClassForwardDecl(Scope *S); 13781 void CodeCompleteObjCSuperclass(Scope *S, 13782 IdentifierInfo *ClassName, 13783 SourceLocation ClassNameLoc); 13784 void CodeCompleteObjCImplementationDecl(Scope *S); 13785 void CodeCompleteObjCInterfaceCategory(Scope *S, 13786 IdentifierInfo *ClassName, 13787 SourceLocation ClassNameLoc); 13788 void CodeCompleteObjCImplementationCategory(Scope *S, 13789 IdentifierInfo *ClassName, 13790 SourceLocation ClassNameLoc); 13791 void CodeCompleteObjCPropertyDefinition(Scope *S); 13792 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 13793 IdentifierInfo *PropertyName); 13794 void CodeCompleteObjCMethodDecl(Scope *S, 13795 std::optional<bool> IsInstanceMethod, 13796 ParsedType ReturnType); 13797 void CodeCompleteObjCMethodDeclSelector(Scope *S, 13798 bool IsInstanceMethod, 13799 bool AtParameterName, 13800 ParsedType ReturnType, 13801 ArrayRef<IdentifierInfo *> SelIdents); 13802 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, 13803 SourceLocation ClassNameLoc, 13804 bool IsBaseExprStatement); 13805 void CodeCompletePreprocessorDirective(bool InConditional); 13806 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 13807 void CodeCompletePreprocessorMacroName(bool IsDefinition); 13808 void CodeCompletePreprocessorExpression(); 13809 void CodeCompletePreprocessorMacroArgument(Scope *S, 13810 IdentifierInfo *Macro, 13811 MacroInfo *MacroInfo, 13812 unsigned Argument); 13813 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); 13814 void CodeCompleteNaturalLanguage(); 13815 void CodeCompleteAvailabilityPlatformName(); 13816 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 13817 CodeCompletionTUInfo &CCTUInfo, 13818 SmallVectorImpl<CodeCompletionResult> &Results); 13819 //@} 13820 13821 //===--------------------------------------------------------------------===// 13822 // Extra semantic analysis beyond the C type system 13823 13824 public: 13825 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 13826 unsigned ByteNo) const; 13827 13828 enum FormatArgumentPassingKind { 13829 FAPK_Fixed, // values to format are fixed (no C-style variadic arguments) 13830 FAPK_Variadic, // values to format are passed as variadic arguments 13831 FAPK_VAList, // values to format are passed in a va_list 13832 }; 13833 13834 // Used to grab the relevant information from a FormatAttr and a 13835 // FunctionDeclaration. 13836 struct FormatStringInfo { 13837 unsigned FormatIdx; 13838 unsigned FirstDataArg; 13839 FormatArgumentPassingKind ArgPassingKind; 13840 }; 13841 13842 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 13843 bool IsVariadic, FormatStringInfo *FSI); 13844 13845 private: 13846 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13847 const ArraySubscriptExpr *ASE = nullptr, 13848 bool AllowOnePastEnd = true, bool IndexNegated = false); 13849 void CheckArrayAccess(const Expr *E); 13850 13851 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 13852 const FunctionProtoType *Proto); 13853 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 13854 ArrayRef<const Expr *> Args); 13855 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 13856 const FunctionProtoType *Proto); 13857 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 13858 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 13859 ArrayRef<const Expr *> Args, 13860 const FunctionProtoType *Proto, SourceLocation Loc); 13861 13862 void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg); 13863 13864 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 13865 StringRef ParamName, QualType ArgTy, QualType ParamTy); 13866 13867 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 13868 const Expr *ThisArg, ArrayRef<const Expr *> Args, 13869 bool IsMemberFunction, SourceLocation Loc, SourceRange Range, 13870 VariadicCallType CallType); 13871 13872 bool CheckObjCString(Expr *Arg); 13873 ExprResult CheckOSLogFormatStringArg(Expr *Arg); 13874 13875 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, 13876 unsigned BuiltinID, CallExpr *TheCall); 13877 13878 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13879 CallExpr *TheCall); 13880 13881 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); 13882 13883 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 13884 unsigned MaxWidth); 13885 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13886 CallExpr *TheCall); 13887 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 13888 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 13889 bool ParseSVEImmChecks(CallExpr *TheCall, 13890 SmallVector<std::tuple<int, int, int>, 3> &ImmChecks); 13891 bool CheckSMEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 13892 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13893 CallExpr *TheCall); 13894 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, 13895 bool WantCDE); 13896 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13897 CallExpr *TheCall); 13898 13899 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13900 CallExpr *TheCall); 13901 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 13902 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 13903 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 13904 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13905 CallExpr *TheCall); 13906 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 13907 CallExpr *TheCall); 13908 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 13909 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 13910 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); 13911 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); 13912 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); 13913 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 13914 ArrayRef<int> ArgNums); 13915 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); 13916 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 13917 ArrayRef<int> ArgNums); 13918 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13919 CallExpr *TheCall); 13920 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13921 CallExpr *TheCall); 13922 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 13923 bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum); 13924 bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13925 CallExpr *TheCall); 13926 void checkRVVTypeSupport(QualType Ty, SourceLocation Loc, Decl *D); 13927 bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, 13928 unsigned BuiltinID, CallExpr *TheCall); 13929 bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, 13930 unsigned BuiltinID, 13931 CallExpr *TheCall); 13932 bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 13933 CallExpr *TheCall); 13934 13935 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); 13936 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); 13937 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID); 13938 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs, 13939 unsigned BuiltinID); 13940 bool SemaBuiltinComplex(CallExpr *TheCall); 13941 bool SemaBuiltinVSX(CallExpr *TheCall); 13942 bool SemaBuiltinOSLogFormat(CallExpr *TheCall); 13943 bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum); 13944 13945 public: 13946 // Used by C++ template instantiation. 13947 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 13948 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 13949 SourceLocation BuiltinLoc, 13950 SourceLocation RParenLoc); 13951 13952 private: 13953 bool SemaBuiltinPrefetch(CallExpr *TheCall); 13954 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); 13955 bool SemaBuiltinArithmeticFence(CallExpr *TheCall); 13956 bool SemaBuiltinAssume(CallExpr *TheCall); 13957 bool SemaBuiltinAssumeAligned(CallExpr *TheCall); 13958 bool SemaBuiltinLongjmp(CallExpr *TheCall); 13959 bool SemaBuiltinSetjmp(CallExpr *TheCall); 13960 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 13961 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); 13962 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 13963 AtomicExpr::AtomicOp Op); 13964 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 13965 bool IsDelete); 13966 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 13967 llvm::APSInt &Result); 13968 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, 13969 int High, bool RangeIsError = true); 13970 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 13971 unsigned Multiple); 13972 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); 13973 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 13974 unsigned ArgBits); 13975 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, 13976 unsigned ArgBits); 13977 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 13978 int ArgNum, unsigned ExpectedFieldNum, 13979 bool AllowName); 13980 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); 13981 bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 13982 const char *TypeDesc); 13983 13984 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); 13985 13986 bool SemaBuiltinElementwiseMath(CallExpr *TheCall); 13987 bool SemaBuiltinElementwiseTernaryMath(CallExpr *TheCall); 13988 bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall); 13989 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall); 13990 13991 bool SemaBuiltinNonDeterministicValue(CallExpr *TheCall); 13992 13993 // Matrix builtin handling. 13994 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, 13995 ExprResult CallResult); 13996 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 13997 ExprResult CallResult); 13998 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 13999 ExprResult CallResult); 14000 14001 // WebAssembly builtin handling. 14002 bool BuiltinWasmRefNullExtern(CallExpr *TheCall); 14003 bool BuiltinWasmRefNullFunc(CallExpr *TheCall); 14004 bool BuiltinWasmTableGet(CallExpr *TheCall); 14005 bool BuiltinWasmTableSet(CallExpr *TheCall); 14006 bool BuiltinWasmTableSize(CallExpr *TheCall); 14007 bool BuiltinWasmTableGrow(CallExpr *TheCall); 14008 bool BuiltinWasmTableFill(CallExpr *TheCall); 14009 bool BuiltinWasmTableCopy(CallExpr *TheCall); 14010 14011 public: 14012 enum FormatStringType { 14013 FST_Scanf, 14014 FST_Printf, 14015 FST_NSString, 14016 FST_Strftime, 14017 FST_Strfmon, 14018 FST_Kprintf, 14019 FST_FreeBSDKPrintf, 14020 FST_OSTrace, 14021 FST_OSLog, 14022 FST_Unknown 14023 }; 14024 static FormatStringType GetFormatStringType(const FormatAttr *Format); 14025 14026 bool FormatStringHasSArg(const StringLiteral *FExpr); 14027 14028 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); 14029 14030 private: 14031 bool CheckFormatArguments(const FormatAttr *Format, 14032 ArrayRef<const Expr *> Args, bool IsCXXMember, 14033 VariadicCallType CallType, SourceLocation Loc, 14034 SourceRange Range, 14035 llvm::SmallBitVector &CheckedVarArgs); 14036 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 14037 FormatArgumentPassingKind FAPK, unsigned format_idx, 14038 unsigned firstDataArg, FormatStringType Type, 14039 VariadicCallType CallType, SourceLocation Loc, 14040 SourceRange range, 14041 llvm::SmallBitVector &CheckedVarArgs); 14042 14043 void CheckInfNaNFunction(const CallExpr *Call, const FunctionDecl *FDecl); 14044 14045 void CheckAbsoluteValueFunction(const CallExpr *Call, 14046 const FunctionDecl *FDecl); 14047 14048 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); 14049 14050 void CheckMemaccessArguments(const CallExpr *Call, 14051 unsigned BId, 14052 IdentifierInfo *FnName); 14053 14054 void CheckStrlcpycatArguments(const CallExpr *Call, 14055 IdentifierInfo *FnName); 14056 14057 void CheckStrncatArguments(const CallExpr *Call, 14058 IdentifierInfo *FnName); 14059 14060 void CheckFreeArguments(const CallExpr *E); 14061 14062 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 14063 SourceLocation ReturnLoc, 14064 bool isObjCMethod = false, 14065 const AttrVec *Attrs = nullptr, 14066 const FunctionDecl *FD = nullptr); 14067 14068 public: 14069 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, 14070 BinaryOperatorKind Opcode); 14071 14072 private: 14073 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 14074 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 14075 void CheckForIntOverflow(const Expr *E); 14076 void CheckUnsequencedOperations(const Expr *E); 14077 14078 /// Perform semantic checks on a completed expression. This will either 14079 /// be a full-expression or a default argument expression. 14080 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 14081 bool IsConstexpr = false); 14082 14083 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 14084 Expr *Init); 14085 14086 /// Check if there is a field shadowing. 14087 void CheckShadowInheritedFields(const SourceLocation &Loc, 14088 DeclarationName FieldName, 14089 const CXXRecordDecl *RD, 14090 bool DeclIsField = true); 14091 14092 /// Check if the given expression contains 'break' or 'continue' 14093 /// statement that produces control flow different from GCC. 14094 void CheckBreakContinueBinding(Expr *E); 14095 14096 /// Check whether receiver is mutable ObjC container which 14097 /// attempts to add itself into the container 14098 void CheckObjCCircularContainer(ObjCMessageExpr *Message); 14099 14100 void CheckTCBEnforcement(const SourceLocation CallExprLoc, 14101 const NamedDecl *Callee); 14102 14103 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); 14104 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 14105 bool DeleteWasArrayForm); 14106 public: 14107 /// Register a magic integral constant to be used as a type tag. 14108 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14109 uint64_t MagicValue, QualType Type, 14110 bool LayoutCompatible, bool MustBeNull); 14111 14112 struct TypeTagData { TypeTagDataTypeTagData14113 TypeTagData() {} 14114 TypeTagDataTypeTagData14115 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 14116 Type(Type), LayoutCompatible(LayoutCompatible), 14117 MustBeNull(MustBeNull) 14118 {} 14119 14120 QualType Type; 14121 14122 /// If true, \c Type should be compared with other expression's types for 14123 /// layout-compatibility. 14124 LLVM_PREFERRED_TYPE(bool) 14125 unsigned LayoutCompatible : 1; 14126 LLVM_PREFERRED_TYPE(bool) 14127 unsigned MustBeNull : 1; 14128 }; 14129 14130 /// A pair of ArgumentKind identifier and magic value. This uniquely 14131 /// identifies the magic value. 14132 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 14133 14134 private: 14135 /// A map from magic value to type information. 14136 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 14137 TypeTagForDatatypeMagicValues; 14138 14139 /// Peform checks on a call of a function with argument_with_type_tag 14140 /// or pointer_with_type_tag attributes. 14141 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14142 const ArrayRef<const Expr *> ExprArgs, 14143 SourceLocation CallSiteLoc); 14144 14145 /// Check if we are taking the address of a packed field 14146 /// as this may be a problem if the pointer value is dereferenced. 14147 void CheckAddressOfPackedMember(Expr *rhs); 14148 14149 /// The parser's current scope. 14150 /// 14151 /// The parser maintains this state here. 14152 Scope *CurScope; 14153 14154 mutable IdentifierInfo *Ident_super; 14155 14156 /// Nullability type specifiers. 14157 IdentifierInfo *Ident__Nonnull = nullptr; 14158 IdentifierInfo *Ident__Nullable = nullptr; 14159 IdentifierInfo *Ident__Nullable_result = nullptr; 14160 IdentifierInfo *Ident__Null_unspecified = nullptr; 14161 14162 IdentifierInfo *Ident_NSError = nullptr; 14163 14164 /// The handler for the FileChanged preprocessor events. 14165 /// 14166 /// Used for diagnostics that implement custom semantic analysis for #include 14167 /// directives, like -Wpragma-pack. 14168 sema::SemaPPCallbacks *SemaPPCallbackHandler; 14169 14170 protected: 14171 friend class Parser; 14172 friend class InitializationSequence; 14173 friend class ASTReader; 14174 friend class ASTDeclReader; 14175 friend class ASTWriter; 14176 14177 public: 14178 /// Retrieve the keyword associated 14179 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); 14180 14181 /// The struct behind the CFErrorRef pointer. 14182 RecordDecl *CFError = nullptr; 14183 bool isCFError(RecordDecl *D); 14184 14185 /// Retrieve the identifier "NSError". 14186 IdentifierInfo *getNSErrorIdent(); 14187 14188 /// Retrieve the parser's current scope. 14189 /// 14190 /// This routine must only be used when it is certain that semantic analysis 14191 /// and the parser are in precisely the same context, which is not the case 14192 /// when, e.g., we are performing any kind of template instantiation. 14193 /// Therefore, the only safe places to use this scope are in the parser 14194 /// itself and in routines directly invoked from the parser and *never* from 14195 /// template substitution or instantiation. getCurScope()14196 Scope *getCurScope() const { return CurScope; } 14197 incrementMSManglingNumber()14198 void incrementMSManglingNumber() const { 14199 return CurScope->incrementMSManglingNumber(); 14200 } 14201 14202 IdentifierInfo *getSuperIdentifier() const; 14203 14204 ObjCContainerDecl *getObjCDeclContext() const; 14205 getCurLexicalContext()14206 DeclContext *getCurLexicalContext() const { 14207 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 14208 } 14209 getCurObjCLexicalContext()14210 const DeclContext *getCurObjCLexicalContext() const { 14211 const DeclContext *DC = getCurLexicalContext(); 14212 // A category implicitly has the attribute of the interface. 14213 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 14214 DC = CatD->getClassInterface(); 14215 return DC; 14216 } 14217 14218 /// Determine the number of levels of enclosing template parameters. This is 14219 /// only usable while parsing. Note that this does not include dependent 14220 /// contexts in which no template parameters have yet been declared, such as 14221 /// in a terse function template or generic lambda before the first 'auto' is 14222 /// encountered. 14223 unsigned getTemplateDepth(Scope *S) const; 14224 14225 /// To be used for checking whether the arguments being passed to 14226 /// function exceeds the number of parameters expected for it. 14227 static bool TooManyArguments(size_t NumParams, size_t NumArgs, 14228 bool PartialOverloading = false) { 14229 // We check whether we're just after a comma in code-completion. 14230 if (NumArgs > 0 && PartialOverloading) 14231 return NumArgs + 1 > NumParams; // If so, we view as an extra argument. 14232 return NumArgs > NumParams; 14233 } 14234 14235 // Emitting members of dllexported classes is delayed until the class 14236 // (including field initializers) is fully parsed. 14237 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; 14238 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; 14239 14240 private: 14241 int ParsingClassDepth = 0; 14242 14243 class SavePendingParsedClassStateRAII { 14244 public: SavePendingParsedClassStateRAII(Sema & S)14245 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } 14246 ~SavePendingParsedClassStateRAII()14247 ~SavePendingParsedClassStateRAII() { 14248 assert(S.DelayedOverridingExceptionSpecChecks.empty() && 14249 "there shouldn't be any pending delayed exception spec checks"); 14250 assert(S.DelayedEquivalentExceptionSpecChecks.empty() && 14251 "there shouldn't be any pending delayed exception spec checks"); 14252 swapSavedState(); 14253 } 14254 14255 private: 14256 Sema &S; 14257 decltype(DelayedOverridingExceptionSpecChecks) 14258 SavedOverridingExceptionSpecChecks; 14259 decltype(DelayedEquivalentExceptionSpecChecks) 14260 SavedEquivalentExceptionSpecChecks; 14261 swapSavedState()14262 void swapSavedState() { 14263 SavedOverridingExceptionSpecChecks.swap( 14264 S.DelayedOverridingExceptionSpecChecks); 14265 SavedEquivalentExceptionSpecChecks.swap( 14266 S.DelayedEquivalentExceptionSpecChecks); 14267 } 14268 }; 14269 14270 /// Helper class that collects misaligned member designations and 14271 /// their location info for delayed diagnostics. 14272 struct MisalignedMember { 14273 Expr *E; 14274 RecordDecl *RD; 14275 ValueDecl *MD; 14276 CharUnits Alignment; 14277 MisalignedMemberMisalignedMember14278 MisalignedMember() : E(), RD(), MD() {} MisalignedMemberMisalignedMember14279 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, 14280 CharUnits Alignment) 14281 : E(E), RD(RD), MD(MD), Alignment(Alignment) {} MisalignedMemberMisalignedMember14282 explicit MisalignedMember(Expr *E) 14283 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} 14284 14285 bool operator==(const MisalignedMember &m) { return this->E == m.E; } 14286 }; 14287 /// Small set of gathered accesses to potentially misaligned members 14288 /// due to the packed attribute. 14289 SmallVector<MisalignedMember, 4> MisalignedMembers; 14290 14291 /// Adds an expression to the set of gathered misaligned members. 14292 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14293 CharUnits Alignment); 14294 14295 public: 14296 /// Diagnoses the current set of gathered accesses. This typically 14297 /// happens at full expression level. The set is cleared after emitting the 14298 /// diagnostics. 14299 void DiagnoseMisalignedMembers(); 14300 14301 /// This function checks if the expression is in the sef of potentially 14302 /// misaligned members and it is converted to some pointer type T with lower 14303 /// or equal alignment requirements. If so it removes it. This is used when 14304 /// we do not want to diagnose such misaligned access (e.g. in conversions to 14305 /// void*). 14306 void DiscardMisalignedMemberAddress(const Type *T, Expr *E); 14307 14308 /// This function calls Action when it determines that E designates a 14309 /// misaligned member due to the packed attribute. This is used to emit 14310 /// local diagnostics like in reference binding. 14311 void RefersToMemberWithReducedAlignment( 14312 Expr *E, 14313 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14314 Action); 14315 14316 /// Describes the reason a calling convention specification was ignored, used 14317 /// for diagnostics. 14318 enum class CallingConventionIgnoredReason { 14319 ForThisTarget = 0, 14320 VariadicFunction, 14321 ConstructorDestructor, 14322 BuiltinFunction 14323 }; 14324 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 14325 /// context is "used as device code". 14326 /// 14327 /// - If CurLexicalContext is a kernel function or it is known that the 14328 /// function will be emitted for the device, emits the diagnostics 14329 /// immediately. 14330 /// - If CurLexicalContext is a function and we are compiling 14331 /// for the device, but we don't know that this function will be codegen'ed 14332 /// for devive yet, creates a diagnostic which is emitted if and when we 14333 /// realize that the function will be codegen'ed. 14334 /// 14335 /// Example usage: 14336 /// 14337 /// Diagnose __float128 type usage only from SYCL device code if the current 14338 /// target doesn't support it 14339 /// if (!S.Context.getTargetInfo().hasFloat128Type() && 14340 /// S.getLangOpts().SYCLIsDevice) 14341 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; 14342 SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, 14343 unsigned DiagID); 14344 14345 void deepTypeCheckForSYCLDevice(SourceLocation UsedAt, 14346 llvm::DenseSet<QualType> Visited, 14347 ValueDecl *DeclToCheck); 14348 }; 14349 14350 DeductionFailureInfo 14351 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 14352 sema::TemplateDeductionInfo &Info); 14353 14354 /// Contains a late templated function. 14355 /// Will be parsed at the end of the translation unit, used by Sema & Parser. 14356 struct LateParsedTemplate { 14357 CachedTokens Toks; 14358 /// The template function declaration to be late parsed. 14359 Decl *D; 14360 /// Floating-point options in the point of definition. 14361 FPOptions FPO; 14362 }; 14363 14364 template <> 14365 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, 14366 PragmaMsStackAction Action, 14367 llvm::StringRef StackSlotLabel, 14368 AlignPackInfo Value); 14369 14370 std::unique_ptr<sema::RISCVIntrinsicManager> 14371 CreateRISCVIntrinsicManager(Sema &S); 14372 } // end namespace clang 14373 14374 namespace llvm { 14375 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its 14376 // SourceLocation. 14377 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { 14378 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; 14379 using FDBaseInfo = 14380 DenseMapInfo<clang::CanonicalDeclPtr<const clang::FunctionDecl>>; 14381 14382 static FunctionDeclAndLoc getEmptyKey() { 14383 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; 14384 } 14385 14386 static FunctionDeclAndLoc getTombstoneKey() { 14387 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; 14388 } 14389 14390 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { 14391 return hash_combine(FDBaseInfo::getHashValue(FDL.FD), 14392 FDL.Loc.getHashValue()); 14393 } 14394 14395 static bool isEqual(const FunctionDeclAndLoc &LHS, 14396 const FunctionDeclAndLoc &RHS) { 14397 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; 14398 } 14399 }; 14400 } // namespace llvm 14401 14402 #endif 14403